예제 #1
0
파일: Util.cs 프로젝트: riteshparekh/NuGet
        /// <summary>
        /// Creates a test package.
        /// </summary>
        /// <param name="packageId">The id of the created package.</param>
        /// <param name="version">The version of the created package.</param>
        /// <param name="path">The directory where the package is created.</param>
        /// <returns>The full path of the created package file.</returns>
        public static string CreateTestPackage(string packageId, string version, string path, Uri licenseUrl = null)
        {
            var packageBuilder = new PackageBuilder
            {
                Id = packageId,
                Version = new SemanticVersion(version),
                Description = "Test desc"
            };

            if (licenseUrl != null)
            {
                packageBuilder.LicenseUrl = licenseUrl;
            }

            packageBuilder.Files.Add(CreatePackageFile(@"content\test1.txt"));
            packageBuilder.Authors.Add("test author");

            var packageFileName = string.Format("{0}.{1}.nupkg", packageId, version);
            var packageFileFullPath = Path.Combine(path, packageFileName);
            using (var fileStream = File.Create(packageFileFullPath))
            {
                packageBuilder.Save(fileStream);
            }

            return packageFileFullPath;
        }
예제 #2
0
        public void Burn_InstallUninstallBundleWithEmbeddedBundle()
        {
            // Build the packages.
            string packageA1 = new PackageBuilder(this, "A").Build().Output;
            string packageB1 = new PackageBuilder(this, "B").Build().Output;

            // Create the named bind paths to the packages.
            Dictionary<string, string> bindPaths = new Dictionary<string, string>();
            bindPaths.Add("packageA", packageA1);
            bindPaths.Add("packageB", packageB1);

            // Build the embedded bundle.
            string bundleB = new BundleBuilder(this, "BundleB") { BindPaths = bindPaths, Extensions = Extensions }.Build().Output;

            // Build the parent bundle
            bindPaths.Add("bundleB", bundleB);
            string bundleA = new BundleBuilder(this, "BundleA") { BindPaths = bindPaths, Extensions = Extensions }.Build().Output;

            // Install the bundles.
            BundleInstaller installerA = new BundleInstaller(this, bundleA).Install();

            // Test package is installed.
            Assert.True(MsiVerifier.IsPackageInstalled(packageA1));
            Assert.True(MsiVerifier.IsPackageInstalled(packageB1));

            // Attempt to uninstall bundleA.
            installerA.Uninstall();

            // Test package is uninstalled.
            Assert.False(MsiVerifier.IsPackageInstalled(packageA1));
            Assert.False(MsiVerifier.IsPackageInstalled(packageB1));

            this.Complete();
        }
예제 #3
0
        public void CreatePackageAddsVersionStampIfFrameworkAssembliesAreUsed()
        {
            // Arrange
            PackageBuilder builder = new PackageBuilder() {
                Id = "A",
                Version = new Version("1.0"),
                Description = "Descriptions",
            };
            builder.Authors.Add("David");
            builder.FrameworkReferences.Add(new FrameworkAssemblyReference("System.Web"));
            var ms = new MemoryStream();

            // Act
            Manifest.Create(builder).Save(ms);
            ms.Seek(0, SeekOrigin.Begin);

            // Assert
            Assert.AreEqual(@"<?xml version=""1.0"" encoding=""utf-8""?>
            <package xmlns=""http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"">
              <metadata schemaVersion=""2"">
            <id>A</id>
            <version>1.0</version>
            <authors>David</authors>
            <owners>David</owners>
            <requireLicenseAcceptance>false</requireLicenseAcceptance>
            <description>Descriptions</description>
            <frameworkAssemblies>
              <frameworkAssembly assemblyName=""System.Web"" targetFramework="""" />
            </frameworkAssemblies>
              </metadata>
            </package>", ms.ReadToEnd());
        }
예제 #4
0
        public void Burn_InstallUninstall()
        {
            string v2Version = "2.0.0.0";

            // Build the packages.
            string packageA = new PackageBuilder(this, "A") { Extensions = Extensions }.Build().Output;
            string packageC = new PackageBuilder(this, "C") { Extensions = Extensions }.Build().Output;

            // Create the named bind paths to the packages.
            Dictionary<string, string> bindPaths = new Dictionary<string, string>();
            bindPaths.Add("packageA", packageA);
            bindPaths.Add("packageC", packageC);
            // Add the bindpath for the cab for C to enable to add it as a payload for BundleA
            bindPaths.Add("packageCcab", Path.Combine(Path.GetDirectoryName(packageC), "cab1.cab"));

            // Build the embedded bundle.
            string bundleBv2 = new BundleBuilder(this, "BundleBv2") { BindPaths = bindPaths, Extensions = Extensions, PreprocessorVariables = new Dictionary<string, string>() { { "Version", v2Version } } }.Build().Output;

            // Build the parent bundle.
            bindPaths.Add("bundleBv2", bundleBv2);
            string bundleA = new BundleBuilder(this, "BundleA") { BindPaths = bindPaths, Extensions = Extensions }.Build().Output;

            // Install the parent bundle that will install the embedded bundle.
            BundleInstaller installerA = new BundleInstaller(this, bundleA).Install();
            Assert.True(MsiVerifier.IsPackageInstalled(packageA));
            Assert.True(MsiVerifier.IsPackageInstalled(packageC));

            // Attempt to uninstall bundleA, which will uninstall bundleB since it is a patch related bundle.
            installerA.Uninstall();

            Assert.False(MsiVerifier.IsPackageInstalled(packageA));
            Assert.False(MsiVerifier.IsPackageInstalled(packageC));

            this.Complete();
        }
예제 #5
0
        public void Burn_CancelExecuteWhileCaching()
        {
            // Build the packages.
            string packageA = new PackageBuilder(this, "A") { Extensions = Extensions }.Build().Output;
            string packageB = new PackageBuilder(this, "B") { Extensions = Extensions }.Build().Output;

            // Create the named bind paths to the packages.
            Dictionary<string, string> bindPaths = new Dictionary<string, string>();
            bindPaths.Add("packageA", packageA);
            bindPaths.Add("packageB", packageB);

            // Build the bundle.
            string bundleA = new BundleBuilder(this, "BundleB") { BindPaths = bindPaths, Extensions = Extensions }.Build().Output;

            // Slow the caching of package B to ensure that package A starts installing and cancels.
            this.SetPackageCancelExecuteAtProgress("PackageA", 50);
            this.SetPackageSlowCache("PackageB", 1000);

            // Install the bundle and hopefully it fails.
            BundleInstaller installerA = new BundleInstaller(this, bundleA).Install(expectedExitCode: ErrorCodes.ERROR_INSTALL_USEREXIT);
            Assert.IsFalse(MsiVerifier.IsPackageInstalled(packageA));
            Assert.IsFalse(MsiVerifier.IsPackageInstalled(packageB));

            this.CleanTestArtifacts = true;
        }
		public void Fill (PackageBuilder builder, SolutionItem selection)
		{
			store.Clear ();
			
			this.builder = builder;
			if (selection is SolutionFolder) {
				foreach (SolutionItem e in ((SolutionFolder)selection).GetAllItems ()) {
					if (builder.CanBuild (e))
						selectedEntries [e] = e;
				}
			}
			else if (selection != null) {
				selectedEntries [selection] = selection;
			}
			
			if (selection != null)
				solution = selection.ParentSolution;
			else {
				solution = IdeApp.ProjectOperations.CurrentSelectedSolution;
				if (solution == null) {
					ReadOnlyCollection<Solution> items = IdeApp.ProjectOperations.CurrentSelectedWorkspaceItem.GetAllSolutions ();
					if (items.Count > 0)
						solution = items [0];
					else
						return;
				}
			}
			AddEntry (TreeIter.Zero, solution.RootFolder);
		}
예제 #7
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);
        }
예제 #8
0
        public void Burn_RedirectPackageCache()
        {
            const string PolicyName = "PackageCache";

            // Build the packages.
            string packageA = new PackageBuilder(this, "A") { Extensions = Extensions }.Build().Output;
            string packageB = new PackageBuilder(this, "B") { Extensions = Extensions }.Build().Output;

            // Create the named bind paths to the packages.
            Dictionary<string, string> bindPaths = new Dictionary<string, string>();
            bindPaths.Add("packageA", packageA);
            bindPaths.Add("packageB", packageB);

            // Build the bundles.
            string bundleA = new BundleBuilder(this, "BundleA") { BindPaths = bindPaths, Extensions = Extensions }.Build().Output;
            string bundleB = new BundleBuilder(this, "BundleB") { BindPaths = bindPaths, Extensions = Extensions }.Build().Output;

            RegistryKey policy = Registry.LocalMachine.CreateSubKey(@"Software\Policies\WiX\Burn");
            string currentPackageCache = null;

            try
            {
                currentPackageCache = policy.GetValue(PolicyName) as string;

                // Install the first bundle using the default package cache.
                policy.DeleteValue(PolicyName);

                BundleInstaller installerA = new BundleInstaller(this, bundleA).Install();
                Assert.True(MsiVerifier.IsPackageInstalled(packageA));

                // Install the second bundle which has a shared package using the redirected package cache.
                string path = Path.Combine(Path.GetTempPath(), "Package Cache");
                policy.SetValue(PolicyName, path);

                BundleInstaller installerB = new BundleInstaller(this, bundleB).Install();
                Assert.True(MsiVerifier.IsPackageInstalled(packageA));
                Assert.True(MsiVerifier.IsPackageInstalled(packageB));

                // The first bundle should leave package A behind.
                installerA.Uninstall();

                // Now make sure that the second bundle removes packages from either cache directory.
                installerB.Uninstall();

                this.Complete();
            }
            finally
            {
                if (!string.IsNullOrEmpty(currentPackageCache))
                {
                    policy.SetValue(PolicyName, currentPackageCache);
                }
                else
                {
                    policy.DeleteValue(PolicyName);
                }

                policy.Dispose();
            }
        }
예제 #9
0
        public void Burn_PermanentInstallUninstall()
        {
            // Build the packages.
            string packageA = new PackageBuilder(this, "A") { Extensions = Extensions }.Build().Output;
            string packageB = new PackageBuilder(this, "B") { Extensions = Extensions }.Build().Output;

            // Create the named bind paths to the packages.
            Dictionary<string, string> bindPaths = new Dictionary<string, string>();
            bindPaths.Add("packageA", packageA);
            bindPaths.Add("packageB", packageB);

            // Build the bundles.
            string bundleA = new BundleBuilder(this, "BundleA") { BindPaths = bindPaths, Extensions = Extensions }.Build().Output;

            // Install Bundle A.
            BundleInstaller installerA = new BundleInstaller(this, bundleA).Install();

            Assert.True(MsiVerifier.IsPackageInstalled(packageA));
            Assert.True(MsiVerifier.IsPackageInstalled(packageB));

            // Uninstall bundleA.
            installerA.Uninstall();

            Assert.True(MsiVerifier.IsPackageInstalled(packageA));
            Assert.False(MsiVerifier.IsPackageInstalled(packageB));

            this.Complete();
        }
예제 #10
0
        public void Burn_PermanentInstallForceUninstall()
        {
            // Build the packages.
            string packageA = new PackageBuilder(this, "A") { Extensions = Extensions }.Build().Output;
            string packageB = new PackageBuilder(this, "B") { Extensions = Extensions }.Build().Output;

            // Create the named bind paths to the packages.
            Dictionary<string, string> bindPaths = new Dictionary<string, string>();
            bindPaths.Add("packageA", packageA);
            bindPaths.Add("packageB", packageB);

            // Build the bundles.
            string bundleA = new BundleBuilder(this, "BundleA") { BindPaths = bindPaths, Extensions = Extensions }.Build().Output;

            // Install Bundle A.
            BundleInstaller installerA = new BundleInstaller(this, bundleA).Install();

            Assert.True(MsiVerifier.IsPackageInstalled(packageA));
            Assert.True(MsiVerifier.IsPackageInstalled(packageB));

            // Force Uninstall Bundle A.
            this.SetPackageRequestedState("PackageA", Microsoft.Tools.WindowsInstallerXml.Bootstrapper.RequestState.ForceAbsent);
            this.SetPackageRequestedState("PackageB", Microsoft.Tools.WindowsInstallerXml.Bootstrapper.RequestState.ForceAbsent);
            installerA.Uninstall();

            Assert.False(MsiVerifier.IsPackageInstalled(packageA));
            Assert.False(MsiVerifier.IsPackageInstalled(packageB));

            this.Complete();
        }
예제 #11
0
        public void ServerPackageRepositoryReadsDerivedData()
        {
            // Arrange
            var mockProjectSystem = new Mock<MockProjectSystem>() { CallBase = true };
            var package = new PackageBuilder() { Id = "Test", Version = new System.Version("1.0"), Description = "Description" };
            var mockFile = new Mock<IPackageFile>();
            mockFile.Setup(m => m.Path).Returns("foo");
            mockFile.Setup(m => m.GetStream()).Returns(new MemoryStream());
            package.Files.Add(mockFile.Object);
            package.Authors.Add("Test Author");
            var memoryStream = new MemoryStream();
            package.Save(memoryStream);
            memoryStream.Seek(0, SeekOrigin.Begin);
            mockProjectSystem.Object.AddFile("foo.nupkg");
            mockProjectSystem.Setup(c => c.OpenFile(It.IsAny<string>())).Returns(() => new MemoryStream(memoryStream.ToArray()));
            var serverRepository = new ServerPackageRepository(new DefaultPackagePathResolver(mockProjectSystem.Object), mockProjectSystem.Object);
            serverRepository.HashProvider = GetHashProvider();

            // Act
            var packages = serverRepository.GetPackagesWithDerivedData();

            // Assert
            byte[] data = memoryStream.ToArray();
            Assert.AreEqual(data.Length, packages.Single().PackageSize);
            CollectionAssert.AreEquivalent(data.Select(Invert).ToArray(), Convert.FromBase64String(packages.Single().PackageHash));
            Assert.AreEqual(data.Length, packages.Single().PackageSize);
        }
예제 #12
0
        public void ReleaseNotesAttributeIsRecognized()
        {
            // Arrange
            PackageBuilder builder = new PackageBuilder()
            {
                Id = "A",
                Version = new SemanticVersion("1.0"),
                Description = "Description",
                ReleaseNotes = "Release Notes"
            };
            builder.Authors.Add("David");
            var ms = new MemoryStream();

            // Act
            Manifest.Create(builder).Save(ms);
            ms.Seek(0, SeekOrigin.Begin);

            // Assert
            Assert.Equal(@"<?xml version=""1.0""?>
<package xmlns=""http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd"">
  <metadata>
    <id>A</id>
    <version>1.0</version>
    <authors>David</authors>
    <owners>David</owners>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>Description</description>
    <releaseNotes>Release Notes</releaseNotes>
  </metadata>
</package>", ms.ReadToEnd());
        }
예제 #13
0
파일: Util.cs 프로젝트: kumavis/NuGet
        /// <summary>
        /// Creates a test package.
        /// </summary>
        /// <param name="packageId">The id of the created package.</param>
        /// <param name="version">The version of the created package.</param>
        /// <param name="path">The directory where the package is created.</param>
        /// <returns>The full path of the created package file.</returns>
        public static string CreateTestPackage(string packageId, string version, string path, Uri licenseUrl = null)
        {
            var packageBuilder = new PackageBuilder
            {
                Id = packageId,
                Version = new SemanticVersion(version),
                Description = "Test desc"
            };

            if (licenseUrl != null)
            {
                packageBuilder.LicenseUrl = licenseUrl;
            }

            var dependencies = new PackageDependency("Dummy");
            packageBuilder.DependencySets.Add(new PackageDependencySet(null, new[] { dependencies }));
            packageBuilder.Authors.Add("test author");

            var packageFileName = string.Format("{0}.{1}.nupkg", packageId, version);
            var packageFileFullPath = Path.Combine(path, packageFileName);
            using (var fileStream = File.Create(packageFileFullPath))
            {
                packageBuilder.Save(fileStream);
            }

            return packageFileFullPath;
        }
예제 #14
0
        public void OwnersFallsBackToAuthorsIfNoneSpecified()
        {
            // Arrange
            PackageBuilder builder = new PackageBuilder()
            {
                Id = "A",
                Version = new SemanticVersion("1.0"),
                Description = "Description"
            };
            builder.Authors.Add("JohnDoe");
            var ms = new MemoryStream();

            // Act
            Manifest.Create(builder).Save(ms);
            ms.Seek(0, SeekOrigin.Begin);

            // Assert
            Assert.Equal(@"<?xml version=""1.0""?>
<package xmlns=""http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"">
  <metadata>
    <id>A</id>
    <version>1.0</version>
    <authors>JohnDoe</authors>
    <owners>JohnDoe</owners>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>Description</description>
  </metadata>
</package>", ms.ReadToEnd());
        }
예제 #15
0
        public void Burn_ComponentSearchResults()
        {
            // Build the packages.
            string packageA = new PackageBuilder(this, "A") { Extensions = Extensions }.Build().Output;
            string packageB = new PackageBuilder(this, "B") { Extensions = Extensions }.Build().Output;

            Dictionary<string, string> bindPaths = new Dictionary<string, string>();
            bindPaths.Add("packageA", packageA);
            bindPaths.Add("packageB", packageB);

            // Build the bundles.
            string bundleA = new BundleBuilder(this, "BundleA") { BindPaths = bindPaths, Extensions = Extensions }.Build().Output;
            string bundleB = new BundleBuilder(this, "BundleB") { BindPaths = bindPaths, Extensions = Extensions }.Build().Output;

            // Install the bundles.
            BundleInstaller installerA = new BundleInstaller(this, bundleA).Install();
            BundleInstaller installerB = new BundleInstaller(this, bundleB).Install();

            // PackageB will be installed if all ComponentSearches worked.
            Assert.True(MsiVerifier.IsPackageInstalled(packageA));
            Assert.True(MsiVerifier.IsPackageInstalled(packageB));

            // Uninstall the main bundle and add-on.
            installerA.Uninstall();

            this.Complete();
        }
		public void Fill (PackageBuilder builder, SolutionFolderItem selection)
		{
			store.Clear ();
			
			this.builder = builder;
			if (selection is SolutionFolder) {
				foreach (SolutionFolderItem e in ((SolutionFolder)selection).GetAllItems ()) {
					if (builder.CanBuild (e))
						selectedEntries [e] = e;
				}
			}
			else if (selection != null) {
				selectedEntries [selection] = selection;
			}
			
			if (selection != null)
				solution = selection.ParentSolution;
			else {
				solution = IdeApp.ProjectOperations.CurrentSelectedSolution;
				if (solution == null) {
					solution = IdeApp.ProjectOperations.CurrentSelectedWorkspaceItem.GetAllItems<Solution> ().FirstOrDefault();
					if (solution == null)
						return;
				}
			}
			AddEntry (TreeIter.Zero, solution.RootFolder);
		}
예제 #17
0
 private void GenerateArchiveDataFromPackage(PackageBuilder packageBuilder)
 {
     using (var archiveStream = new MemoryStream())
     {
         packageBuilder.GeneratePackageArchive(archiveStream);
         _archiveData = archiveStream.ToArray();
     }
 }
예제 #18
0
 private string DeployPackage(string id, PackageBuilder builder)
 {
     string path = Path.Combine(_tempDir, id);
     builder.WritePackageInto(path);
     ManifestTest.CreateDotFile(path, ManifestFormat.FromPrefix(id), _handler);
     FileUtils.EnableWriteProtection(path);
     return path;
 }
예제 #19
0
        public void GivenParentProductCategory_WhenPackageIsDefined_ThenValidationHasErrors()
        {
            var package = new PackageBuilder(this.DatabaseSession).WithName("package").Build();

            var parent = new ProductCategoryBuilder(this.DatabaseSession).WithDescription("parent").WithPackage(package).Build();
            var child = new ProductCategoryBuilder(this.DatabaseSession).WithDescription("child").WithParent(parent).Build();

            Assert.IsTrue(new Derivation(this.DatabaseSession).Derive().HasErrors);
        }
예제 #20
0
        private PackageBuilder GetPackageA()
        {
            if (null == this.packageA)
            {
                this.packageA = this.CreatePackage("A");
            }

            return this.packageA;
        }
예제 #21
0
        public void GivenLeafeProductCategory_WhenPackageIsDefined_ThenValidationHasNoErrors()
        {
            var package = new PackageBuilder(this.DatabaseSession).WithName("package").Build();

            new ProductCategoryBuilder(this.DatabaseSession).WithDescription("Category").WithPackage(package).Build();

            Assert.IsFalse(new Derivation(this.DatabaseSession).Derive().HasErrors);

            this.DatabaseSession.Rollback();
        }
예제 #22
0
        public void Burn_InstallUninstallAddonPatchRelatedBundle()
        {
            // Build the packages.
            string packageA = new PackageBuilder(this, "A").Build().Output;
            string packageC1 = new PackageBuilder(this, "C").Build().Output;
            string packageC2 = new PackageBuilder(this, "C") { PreprocessorVariables = new Dictionary<string, string>() { { "Version", "1.0.1.0" } } }.Build().Output;
            string packageD = new PackageBuilder(this, "D").Build().Output;

            // Create the named bind paths to the packages.
            Dictionary<string, string> bindPaths = new Dictionary<string, string>();
            bindPaths.Add("packageA", packageA);
            bindPaths.Add("packageC", packageC1);
            bindPaths.Add("packageD", packageD);

            // Build the base and addon bundles.
            string bundleA = new BundleBuilder(this, "BundleA") { BindPaths = bindPaths, Extensions = Extensions }.Build().Output;
            string bundleC = new BundleBuilder(this, "BundleC") { BindPaths = bindPaths, Extensions = Extensions }.Build().Output;

            // Update path to C2 and build the addon patch bundle.
            bindPaths["packageC"] = packageC2;
            string bundleE = new BundleBuilder(this, "BundleE") { BindPaths = bindPaths, Extensions = Extensions, PreprocessorVariables = new Dictionary<string, string>() { { "Version", "1.0.1.0" } } }.Build().Output;

            // Install the base and addon bundles.
            BundleInstaller installerA = new BundleInstaller(this, bundleA).Install();
            BundleInstaller installerC = new BundleInstaller(this, bundleC).Install();

            // Test that packages A and C1 but not D are installed.
            Assert.IsTrue(MsiVerifier.IsPackageInstalled(packageA));
            Assert.IsTrue(MsiVerifier.IsPackageInstalled(packageC1));
            Assert.IsFalse(MsiVerifier.IsPackageInstalled(packageC2));
            Assert.IsFalse(MsiVerifier.IsPackageInstalled(packageD));

            // Install the patch to the addon.
            BundleInstaller installerE = new BundleInstaller(this, bundleE).Install();

            // Test that packages A and C2 but not D are installed, and that C1 was upgraded.
            Assert.IsTrue(MsiVerifier.IsPackageInstalled(packageA));
            Assert.IsFalse(MsiVerifier.IsPackageInstalled(packageC1));
            Assert.IsTrue(MsiVerifier.IsPackageInstalled(packageC2));
            Assert.IsFalse(MsiVerifier.IsPackageInstalled(packageD));

            // Attempt to uninstall bundleA.
            installerA.Uninstall();

            // Test that uninstalling bundle A detected and removed bundle C, which removed bundle E (can't easily reference log).
            Assert.IsTrue(LogVerifier.MessageInLogFileRegex(installerA.LastLogFile, @"Detected related bundle: \{[0-9A-Za-z\-]{36}\}, type: Addon, scope: PerMachine, version: 1\.0\.0\.0, operation: Remove"));

            // Test that all packages are uninstalled.
            Assert.IsFalse(MsiVerifier.IsPackageInstalled(packageA));
            Assert.IsFalse(MsiVerifier.IsPackageInstalled(packageC1));
            Assert.IsFalse(MsiVerifier.IsPackageInstalled(packageC2));
            Assert.IsFalse(MsiVerifier.IsPackageInstalled(packageD));

            this.CleanTestArtifacts = true;
        }
예제 #23
0
		public override void CopyFrom (PackageBuilder other)
		{
			base.CopyFrom (other);
			CommandPackageBuilder t = other as CommandPackageBuilder;
			if (t != null) {
				command = t.command;
				args = t.args;
				externalConsole = t.externalConsole;
				closeConsoleWhenDone = t.closeConsoleWhenDone;
			}
		}
        public string GenerateSingleCustomPackage(PackageDefinition definition,
                                              string binFolderPath,
                                              string outputFolderPath,
                                              string releaseVersion,
                                              IEnumerable<string> singleDLLPackages,
                                              IEnumerable<string> customPackages,
                                              string packageNamePrefix)
        {
            // if no dependencies exist, don't create package from definition
              IEnumerable<ManifestDependency> dependencies = this.GenerateDependencies(definition.Dependencies,
                                                                               binFolderPath,
                                                                               releaseVersion,
                                                                               singleDLLPackages,
                                                                               customPackages,
                                                                               packageNamePrefix);
              if (!dependencies.Any())
              {
            return String.Empty;
              }

              // Create nupkg file
              var packageId = packageNamePrefix + definition.Id + "." + releaseVersion;
              var nugetFilePath = Path.Combine(outputFolderPath, packageId + ".nupkg");

              var metadata = new ManifestMetadata
              {
            Id = packageNamePrefix + definition.Id,
            Title = packageNamePrefix + definition.Id,
            Version = releaseVersion,
            Tags = definition.Tag,
            Authors = "Sitecore",
            Owners = "Sitecore",
            Description = definition.Description,
            RequireLicenseAcceptance = false,
            IconUrl = "http://www.sitecore.net/favicon.ico",
            DependencySets = new List<ManifestDependencySet>
                {
                  new ManifestDependencySet
                  {
                        Dependencies =  dependencies.ToList()
                  }
                }
              };

              var builder = new PackageBuilder();
              builder.Populate(metadata);
              using (FileStream stream = File.Open(nugetFilePath, FileMode.OpenOrCreate))
              {
            builder.Save(stream);
              }

              return nugetFilePath;
        }
예제 #25
0
 private PackageBuilder BuildSamplePackageHierarchy()
 {
     var packageBuilder = new PackageBuilder()
         .AddFile("file1", "First file")
         .AddFile("file2", new byte[] {0});
     packageBuilder.AddFolder("emptyFolder");
     packageBuilder.AddFolder("sub").AddFolder("folder")
         .AddFile("nestedFile", "File 3\n")
         .AddFolder("nestedFolder").AddFile("doublyNestedFile", "File 4");
     _package = packageBuilder.Hierarchy;
     return packageBuilder;
 }
예제 #26
0
        public void Burn_InstallUpdatedBundleOptionalUpdateRegistration()
        {
            string v2Version = "2.0.0.0";

            // Build the packages.
            string packageAv1 = new PackageBuilder(this, "A").Build().Output;
            string packageAv2 = new PackageBuilder(this, "A") { PreprocessorVariables = new Dictionary<string, string>() { { "Version", v2Version } } }.Build().Output;

            // Create the named bind paths to the packages.
            Dictionary<string, string> bindPathsv1 = new Dictionary<string, string>() { { "packageA", packageAv1 } };
            Dictionary<string, string> bindPathsv2 = new Dictionary<string, string>() { { "packageA", packageAv2 } };

            // Build the bundles.
            string bundleAv1 = new BundleBuilder(this, "BundleA") { BindPaths = bindPathsv1, Extensions = Extensions }.Build().Output;
            string bundleAv2 = new BundleBuilder(this, "BundleA") { BindPaths = bindPathsv2, Extensions = Extensions, PreprocessorVariables = new Dictionary<string, string>() { { "Version", v2Version } } }.Build().Output;

            // Initialize with first bundle.
            BundleInstaller installerAv1 = new BundleInstaller(this, bundleAv1).Install();
            Assert.True(MsiVerifier.IsPackageInstalled(packageAv1));

            // Make sure the OptionalUpdateRegistration exists.
            // SOFTWARE\[Manufacturer]\Updates\[ProductFamily]\[Name]
            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft Corporation\Updates\~Burn_InstallUpdatedBundleOptionalUpdateRegistration - Bundle A"))
            {
                Assert.Equal("Y", key.GetValue("ThisVersionInstalled"));
                Assert.Equal("1.0.0.0", key.GetValue("PackageVersion"));
            }

            // Install second bundle which will major upgrade away v1.
            BundleInstaller installerAv2 = new BundleInstaller(this, bundleAv2).Install();
            Assert.False(MsiVerifier.IsPackageInstalled(packageAv1));
            Assert.True(MsiVerifier.IsPackageInstalled(packageAv2));

            // Make sure the OptionalUpdateRegistration exists.
            // SOFTWARE\[Manufacturer]\Updates\[ProductFamily]\[Name]
            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft Corporation\Updates\~Burn_InstallUpdatedBundleOptionalUpdateRegistration - Bundle A"))
            {
                Assert.Equal("Y", key.GetValue("ThisVersionInstalled"));
                Assert.Equal("2.0.0.0", key.GetValue("PackageVersion"));
            }

            // Uninstall the second bundle and everything should be gone.
            installerAv2.Uninstall();
            Assert.False(MsiVerifier.IsPackageInstalled(packageAv1));
            Assert.False(MsiVerifier.IsPackageInstalled(packageAv2));

            // Make sure the key is removed.
            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft Corporation\Updates\~Burn_InstallUpdatedBundleOptionalUpdateRegistration - Bundle A"))
            {
                Assert.Null(key);
            }
        }
        public void SetUp()
        {
            var packageBuilder = new PackageBuilder()
                .AddFolder("someFolder")
                .AddFolder("someOtherFolder")
                .AddFile("nestedFile1", "abc")
                .AddFile("nestedFile2", "123");

            _sandbox = new TemporaryDirectory("0install-unit-tests");
            packageBuilder.WritePackageInto(_sandbox);

            _someGenerator = new ManifestGenerator(_sandbox, ManifestFormat.Sha256);
        }
예제 #28
0
파일: PackageTests.cs 프로젝트: Allors/apps
        public void GivenPackage_WhenDeriving_ThenRequiredRelationsMustExist()
        {
            var builder = new PackageBuilder(this.DatabaseSession);
            var package = builder.Build();

            Assert.IsTrue(this.DatabaseSession.Derive().HasErrors);

            this.DatabaseSession.Rollback();

            builder.WithName("package");
            package = builder.Build();

            Assert.IsFalse(this.DatabaseSession.Derive().HasErrors);
        }
예제 #29
0
        public void RemoveExcludedFilesRemovesManifestAndOtherNuGetageFiles()
        {
            // Arrange
            var packageBuilder = new PackageBuilder();
            var files = new[] { "somefile.nuspec", @"\foo\bar\somefile.nupkg", @"\baz\1.cs" };
            packageBuilder.Files.AddRange(from f in files  // This almost sounds like a cuss word!
                                          select new PhysicalPackageFile { TargetPath = f });

            // Act
            NewPackageCommand.RemoveExludedFiles(packageBuilder);

            // Assert
            Assert.Equal(@"\baz\1.cs", packageBuilder.Files.Single().Path);
        }
예제 #30
0
        public void SingleAssemblyTest()
        {
            // Arrange
            string search = "foo.dll";
            string target = "lib";
            string root = CreateFileSystem(new File("foo.dll"));
            Stream manifest = GetManifest(search, target);

            // Act
            var packageBuilder = new PackageBuilder(manifest, root);

            // Assert
            Assert.Equal(packageBuilder.Files.Count, 1);
            Assert.Equal(packageBuilder.Files.First().Path, @"lib\foo.dll");
        }
예제 #31
0
        public void Enum_with_flags()
        {
            var package = new PackageBuilder("Test")
                          .Module_Enum_Default(typeof(FlagsEnum))
                          .Build();

            var result = RenderModule(package, $".\\{nameof(FlagsEnum)}");

            Assert.Equal(@"// source: Odachi.CodeModel.Tests.FlagsEnum

enum FlagsEnum {
	foo = 1,
	bar = 2,
	cookies = 32,
	combo = 33,
}

const names = {
	[FlagsEnum.foo]: 'foo',
	[FlagsEnum.bar]: 'bar',
	[FlagsEnum.cookies]: 'cookies',
	[FlagsEnum.combo]: 'combo',
};

namespace FlagsEnum {
	export function create(value: any): FlagsEnum {
	    if (typeof value !== 'number') {
	        throw new Error(`Value '${value}' is not valid for enum FlagsEnum`);
	    }

	    let remainder = value;
	    for (let k in FlagsEnum) {
	        const v = FlagsEnum[k];
	        if (!FlagsEnum.hasOwnProperty(v)) {
	            continue;
	        }

	        remainder = remainder & ~v;
	    }

		if (remainder !== 0) {
			throw new Error(`Remainder '${remainder}' of '${value}' is not valid for enum FlagsEnum`);
		}

		return value as FlagsEnum;
	};

	export function getValues(): FlagsEnum[] {
		return [
			FlagsEnum.foo,
			FlagsEnum.bar,
			FlagsEnum.cookies,
			FlagsEnum.combo,
		];
	}

	export function getNames(): string[] {
		return [
			'foo',
			'bar',
			'cookies',
			'combo',
		];
	}

	export function getName(value: FlagsEnum): string {
		const name = names[value];

		if (name === undefined) {
			throw new Error(`Cannot get name of FlagsEnum '${value}'`);
		}

		return name;
	}
}

export default FlagsEnum;
export { FlagsEnum };
", result);
        }
        public void Burn_UninstallUpgradedBundle()
        {
            const string expectedVersion1 = "1.0.0.0";
            const string expectedVersion2 = "1.0.1.0";

            // Build the packages.
            string packageA = new PackageBuilder(this, "A")
            {
                Extensions = Extensions
            }.Build().Output;
            string packageB = new PackageBuilder(this, "B")
            {
                Extensions = Extensions
            }.Build().Output;
            string packageA1 = new PackageBuilder(this, "A")
            {
                Extensions = Extensions, PreprocessorVariables = new Dictionary <string, string>()
                {
                    { "Version", expectedVersion2 }
                }
            }.Build().Output;

            // Create the named bind paths to the packages.
            Dictionary <string, string> bindPaths = new Dictionary <string, string>();

            bindPaths.Add("packageA", packageA);
            bindPaths.Add("packageB", packageB);

            // Build the bundles.
            string bundleA = new BundleBuilder(this, "BundleA")
            {
                BindPaths = bindPaths, Extensions = Extensions
            }.Build().Output;
            string bundleB = new BundleBuilder(this, "BundleB")
            {
                BindPaths = bindPaths, Extensions = Extensions
            }.Build().Output;

            // Override the path for A to A1.
            bindPaths["packageA"] = packageA1;
            string bundleA1 = new BundleBuilder(this, "BundleA")
            {
                BindPaths = bindPaths, Extensions = Extensions, PreprocessorVariables = new Dictionary <string, string>()
                {
                    { "Version", expectedVersion2 }
                }
            }.Build().Output;

            // Install the bundles.
            BundleInstaller installerA = new BundleInstaller(this, bundleA).Install();
            BundleInstaller installerB = new BundleInstaller(this, bundleB).Install();

            // Make sure the MSIs and EXE are installed.
            Assert.True(MsiVerifier.IsPackageInstalled(packageA));
            Assert.True(MsiVerifier.IsPackageInstalled(packageB));
            using (RegistryKey root = this.GetTestRegistryRoot())
            {
                string actualVersion = root.GetValue("Version") as string;
                Assert.Equal(expectedVersion1, actualVersion);
            }

            // Attempt to upgrade bundleA.
            BundleInstaller installerA1 = new BundleInstaller(this, bundleA1).Install();

            // Verify packageA1 was installed and packageA was uninstalled.
            Assert.True(MsiVerifier.IsPackageInstalled(packageA1));
            Assert.False(MsiVerifier.IsPackageInstalled(packageA));
            using (RegistryKey root = this.GetTestRegistryRoot())
            {
                string actualVersion = root.GetValue("Version") as string;
                Assert.Equal(expectedVersion2, actualVersion);
            }

            // Uninstall bundleA1 and verify that packageA1 is still installed.
            installerA1.Uninstall();
            Assert.True(MsiVerifier.IsPackageInstalled(packageA1));

            // Uninstall bundleB now.
            // // SFBUG:3307315, or (new) 2555 - Detect for upgraded package also.
            installerB.Uninstall();

            // Make sure the MSIs are not installed.
            Assert.False(MsiVerifier.IsPackageInstalled(packageB));
            Assert.False(MsiVerifier.IsPackageInstalled(packageA1));
            Assert.False(MsiVerifier.IsPackageInstalled(packageA));
            Assert.Null(this.GetTestRegistryRoot());

            this.Complete();
        }
예제 #33
0
 public PackCommandRunner(PackArgs packArgs, CreateProjectFactory createProjectFactory, PackageBuilder packageBuilder) : this(packArgs, createProjectFactory)
 {
     this._packageBuilder = packageBuilder;
 }
예제 #34
0
        public void Burn_MajorUpgradeWithSlipstream()
        {
            const string originalVersion = "1.0.0.0";
            const string upgradeVersion  = "2.0.0.0";
            const string patchedVersion  = "2.0.1.0";

            // Build the packages.
            string originalPackageA = this.GetPackageA().Output;
            string upgradePackageA  = new PackageBuilder(this, "A")
            {
                PreprocessorVariables = new Dictionary <string, string>()
                {
                    { "Version", upgradeVersion }
                },
            }.Build().Output;
            string packageAUpdate = new PackageBuilder(this, "A")
            {
                PreprocessorVariables = new Dictionary <string, string>()
                {
                    { "Version", patchedVersion }
                }, NeverGetsInstalled = true
            }.Build().Output;
            string patchA = new PatchBuilder(this, "PatchA")
            {
                PreprocessorVariables = new Dictionary <string, string>()
                {
                    { "Version", patchedVersion }
                }, TargetPaths = new string[] { upgradePackageA }, UpgradePaths = new string[] { packageAUpdate }
            }.Build().Output;

            // Create the named bind paths to the packages in the bundle.
            Dictionary <string, string> bindPaths = new Dictionary <string, string>();

            bindPaths.Add("packageA", upgradePackageA);
            bindPaths.Add("patchA", patchA);

            string bundleA = new BundleBuilder(this, "BundleA")
            {
                BindPaths = bindPaths, Extensions = Extensions
            }.Build().Output;

            // Install the original MSI.
            MSIExec.InstallProduct(originalPackageA, MSIExec.MSIExecReturnCode.SUCCESS);

            Assert.True(MsiVerifier.IsPackageInstalled(originalPackageA));
            using (RegistryKey root = this.GetTestRegistryRoot())
            {
                // Original Product A should be present.
                string actualVersion = root.GetValue("A") as string;
                Assert.Equal(originalVersion, actualVersion);
            }

            // Now install the bundle that should upgrade the MSI and apply the patch.
            BundleInstaller install = new BundleInstaller(this, bundleA).Install();

            Assert.False(MsiVerifier.IsPackageInstalled(originalPackageA));
            Assert.True(MsiVerifier.IsPackageInstalled(upgradePackageA));
            using (RegistryKey root = this.GetTestRegistryRoot())
            {
                // Product A should've slipstreamed with its patch.
                string actualVersion = root.GetValue("A") as string;
                Assert.Equal(patchedVersion, actualVersion);
            }

            install.Uninstall();

            Assert.True(null == this.GetTestRegistryRoot(), "Test registry key should have been removed during uninstall.");

            this.Complete();
        }
예제 #35
0
        private static void BuildPackage(string nuspecPath)
        {
            var repositoryPath = Path.GetDirectoryName(nuspecPath);
            var basePath       = Path.Combine(repositoryPath, "files", Path.GetFileNameWithoutExtension(nuspecPath));

            Directory.CreateDirectory(basePath);

            var  createdFiles = new List <string>();
            bool deleteDir    = true;

            using (var fileStream = File.OpenRead(nuspecPath))
            {
                var manifest       = Manifest.ReadFrom(fileStream, validateSchema: true);
                var packageBuilder = new PackageBuilder();
                packageBuilder.Populate(manifest.Metadata);
                if (!manifest.Files.IsEmpty())
                {
                    foreach (var file in manifest.Files)
                    {
                        string outputPath = Path.Combine(basePath, file.Source);
                        if (File.Exists(outputPath))
                        {
                            deleteDir = false;
                            // A user created file exists. Continue to next file.
                            continue;
                        }

                        createdFiles.Add(outputPath);
                        string outputDir = Path.GetDirectoryName(outputPath);
                        if (!Directory.Exists(outputDir))
                        {
                            Directory.CreateDirectory(outputDir);
                        }

                        if (file.Source.StartsWith(@"lib" + Path.DirectorySeparatorChar) &&
                            (file.Source.EndsWith(".dll") && !file.Source.EndsWith("resources.dll")))
                        {
                            var name = Path.GetFileNameWithoutExtension(file.Source);
                            CreateAssembly(new PackageInfo(manifest.Metadata.Id + ":" + manifest.Metadata.Version),
                                           outputPath: outputPath);
                        }
                        else
                        {
                            File.WriteAllBytes(outputPath, new byte[0]);
                        }
                    }

                    packageBuilder.PopulateFiles(basePath, manifest.Files);
                }

                string nupkgDirectory = Path.GetFullPath("packages");
                Directory.CreateDirectory(nupkgDirectory);
                string nupkgPath = Path.Combine(nupkgDirectory, Path.GetFileNameWithoutExtension(nuspecPath)) + ".nupkg";
                using (var nupkgStream = File.Create(nupkgPath))
                {
                    packageBuilder.Save(nupkgStream);
                }
            }
            try
            {
                if (deleteDir)
                {
                    Directory.Delete(basePath, recursive: true);
                }
                else
                {
                    // Delete files that we created.
                    createdFiles.ForEach(File.Delete);
                }
            }
            catch { }
        }
예제 #36
0
 public bool CanEdit(PackageBuilder target)
 {
     return(target is SourcesZipPackageBuilder);
 }
예제 #37
0
        public PackageId CreatePackageFromTemplate(PackageId templateId, string packageName)
        {
            DocumentPackage sdkPackage = PackageBuilder.NewPackageNamed(packageName).Build();

            return(CreatePackageFromTemplate(templateId, sdkPackage));
        }
        public void Burn_InstallPatchBundleUpgrade()
        {
            const string expectedVersion1 = "1.0.1.0";
            const string expectedVersion2 = "1.0.2.0";

            // Build the packages.
            string packageA1 = new PackageBuilder(this, "A")
            {
                Extensions = Extensions
            }.Build().Output;
            string packageA2 = new PackageBuilder(this, "A")
            {
                Extensions = Extensions, PreprocessorVariables = new Dictionary <string, string>()
                {
                    { "Version", expectedVersion1 }
                }, NeverGetsInstalled = true
            }.Build().Output;
            string packageA3 = new PackageBuilder(this, "A")
            {
                Extensions = Extensions, PreprocessorVariables = new Dictionary <string, string>()
                {
                    { "Version", expectedVersion2 }
                }, NeverGetsInstalled = true
            }.Build().Output;
            string packageB = new PackageBuilder(this, "B")
            {
                Extensions = Extensions
            }.Build().Output;
            string patchA = new PatchBuilder(this, "PatchA")
            {
                PreprocessorVariables = new Dictionary <string, string>()
                {
                    { "Version", expectedVersion1 }
                }, TargetPath = packageA1, UpgradePath = packageA2
            }.Build().Output;
            string patchB = new PatchBuilder(this, "PatchB")
            {
                PreprocessorVariables = new Dictionary <string, string>()
                {
                    { "Version", expectedVersion2 }
                }, TargetPath = packageA1, UpgradePath = packageA3
            }.Build().Output;

            // Create the named bind paths to the packages.
            Dictionary <string, string> bindPaths = new Dictionary <string, string>();

            bindPaths.Add("packageA", packageA1);
            bindPaths.Add("packageB", packageB);
            bindPaths.Add("patchA", patchA);
            bindPaths.Add("patchB", patchB);

            // Build the bundles.
            string bundleF = new BundleBuilder(this, "BundleF")
            {
                BindPaths = bindPaths, Extensions = Extensions
            }.Build().Output;
            string bundleG = new BundleBuilder(this, "BundleG")
            {
                BindPaths = bindPaths, Extensions = Extensions, PreprocessorVariables = new Dictionary <string, string>()
                {
                    { "Version", expectedVersion1 }
                }
            }.Build().Output;
            string bundleI = new BundleBuilder(this, "BundleI")
            {
                BindPaths = bindPaths, Extensions = Extensions, PreprocessorVariables = new Dictionary <string, string>()
                {
                    { "Version", expectedVersion2 }
                }
            }.Build().Output;

            // Install the base bundle and make sure all packages are installed.
            BundleInstaller installerF = new BundleInstaller(this, bundleF).Install();

            Assert.True(MsiVerifier.IsPackageInstalled(packageA1));
            Assert.True(MsiVerifier.IsPackageInstalled(packageB));

            // Install patch bundle and make sure all packages are installed.
            BundleInstaller installerG = new BundleInstaller(this, bundleG).Install();

            Assert.True(MsiVerifier.IsPackageInstalled(packageA1));
            Assert.True(MsiVerifier.IsPackageInstalled(packageB));
            Assert.True(MsiUtils.IsPatchInstalled(patchA));

            // Install patch bundle upgrade and make sure all packages are installed.
            BundleInstaller installerI = new BundleInstaller(this, bundleI).Install();

            Assert.True(MsiVerifier.IsPackageInstalled(packageA1));
            Assert.True(MsiVerifier.IsPackageInstalled(packageB));
            Assert.True(MsiUtils.IsPatchInstalled(patchA));
            Assert.True(MsiUtils.IsPatchInstalled(patchB));

            // Uninstall the base bundle and make sure all packages are uninstalled.
            installerF.Uninstall();
            Assert.False(MsiVerifier.IsPackageInstalled(packageA1));
            Assert.False(MsiVerifier.IsPackageInstalled(packageB));
            Assert.False(MsiUtils.IsPatchInstalled(patchA));
            Assert.False(MsiUtils.IsPatchInstalled(patchB));

            this.Complete();
        }
        public void Burn_MixedScopeUpgradedBundle()
        {
            const string upgradeVersion = "1.0.1.0";

            // Build the packages.
            string packageA = new PackageBuilder(this, "A")
            {
                Extensions = Extensions
            }.Build().Output;
            string packageD1 = new PackageBuilder(this, "D")
            {
                Extensions = Extensions
            }.Build().Output;
            string packageD2 = new PackageBuilder(this, "D")
            {
                Extensions = Extensions, PreprocessorVariables = new Dictionary <string, string>()
                {
                    { "Version", upgradeVersion }
                }
            }.Build().Output;

            // Create the named bind paths to the packages.
            Dictionary <string, string> bindPaths = new Dictionary <string, string>();

            bindPaths.Add("packageA", packageA);
            bindPaths.Add("packageD", packageD1);

            // Build the base bundle.
            string bundleH1 = new BundleBuilder(this, "BundleH")
            {
                BindPaths = bindPaths, Extensions = Extensions
            }.Build().Output;

            // Override the path for D1 to D2 and build the upgrade bundle.
            bindPaths["packageD"] = packageD2;
            string bundleH2 = new BundleBuilder(this, "BundleH")
            {
                BindPaths = bindPaths, Extensions = Extensions, PreprocessorVariables = new Dictionary <string, string>()
                {
                    { "Version", upgradeVersion }
                }
            }.Build().Output;

            // Install the base bundle.
            BundleInstaller installerH1 = new BundleInstaller(this, bundleH1).Install();

            // Make sure the MSIs are installed.
            Assert.True(MsiVerifier.IsPackageInstalled(packageA));
            Assert.True(MsiVerifier.IsPackageInstalled(packageD1));

            Assert.True(LogVerifier.MessageInLogFileRegex(installerH1.LastLogFile, @"Skipping cross-scope dependency registration on package: PackageA, bundle scope: PerUser, package scope: PerMachine"));

            // Install the upgrade bundle. Verify the base bundle was removed.
            BundleInstaller installerH2 = new BundleInstaller(this, bundleH2).Install();

            // Verify packageD2 was installed and packageD1 was uninstalled.
            Assert.True(MsiVerifier.IsPackageInstalled(packageA));
            Assert.False(MsiVerifier.IsPackageInstalled(packageD1));
            Assert.True(MsiVerifier.IsPackageInstalled(packageD2));

            Assert.True(LogVerifier.MessageInLogFileRegex(installerH2.LastLogFile, @"Skipping cross-scope dependency registration on package: PackageA, bundle scope: PerUser, package scope: PerMachine"));
            Assert.True(LogVerifier.MessageInLogFileRegex(installerH2.LastLogFile, @"Detected related bundle: \{[0-9A-Za-z\-]{36}\}, type: Upgrade, scope: PerUser, version: 1\.0\.0\.0, operation: MajorUpgrade"));

            // Uninstall the upgrade bundle now.
            installerH2.Uninstall();

            // Verify that permanent packageA is still installed and then remove.
            Assert.True(MsiVerifier.IsPackageInstalled(packageA));
            MSIExec.UninstallProduct(packageA, MSIExec.MSIExecReturnCode.SUCCESS);

            // Make sure the MSIs were uninstalled.
            Assert.False(MsiVerifier.IsPackageInstalled(packageA));
            Assert.False(MsiVerifier.IsPackageInstalled(packageD2));

            this.Complete();
        }
        public void Burn_UninstallBundleWithDependent()
        {
            const string expectedVersion = "1.0.0.0";

            // Build the packages.
            string packageA = new PackageBuilder(this, "A")
            {
                Extensions = Extensions
            }.Build().Output;
            string packageB = new PackageBuilder(this, "B")
            {
                Extensions = Extensions
            }.Build().Output;

            // Create the named bind paths to the packages.
            Dictionary <string, string> bindPaths = new Dictionary <string, string>();

            bindPaths.Add("packageA", packageA);
            bindPaths.Add("packageB", packageB);

            // Build the bundles.
            string bundleA = new BundleBuilder(this, "BundleA")
            {
                BindPaths = bindPaths, Extensions = Extensions
            }.Build().Output;
            string bundleB = new BundleBuilder(this, "BundleB")
            {
                BindPaths = bindPaths, Extensions = Extensions
            }.Build().Output;

            // Install the bundles.
            BundleInstaller installerA = new BundleInstaller(this, bundleA).Install();
            BundleInstaller installerB = new BundleInstaller(this, bundleB).Install();

            // Make sure the MSIs and EXE are installed.
            Assert.True(MsiVerifier.IsPackageInstalled(packageA));
            Assert.True(MsiVerifier.IsPackageInstalled(packageB));
            using (RegistryKey root = this.GetTestRegistryRoot())
            {
                string actualVersion = root.GetValue("Version") as string;
                Assert.Equal(expectedVersion, actualVersion);
            }

            // Attempt to uninstall bundleA.
            installerA.Uninstall();

            // Verify packageA and ExeA are still installed.
            Assert.True(MsiVerifier.IsPackageInstalled(packageA));
            using (RegistryKey root = this.GetTestRegistryRoot())
            {
                string actualVersion = root.GetValue("Version") as string;
                Assert.Equal(expectedVersion, actualVersion);
            }

            // Uninstall bundleB now.
            installerB.Uninstall();

            // Make sure the MSIs are installed.
            Assert.False(MsiVerifier.IsPackageInstalled(packageB));
            Assert.False(MsiVerifier.IsPackageInstalled(packageA));
            Assert.Null(this.GetTestRegistryRoot());

            this.Complete();
        }
        public void Burn_DifferentPackageRequestStates()
        {
            const string expectedVersion = "1.0.0.0";

            // Build the package.
            string packageA = new PackageBuilder(this, "A")
            {
                Extensions = Extensions
            }.Build().Output;
            string packageB = new PackageBuilder(this, "B")
            {
                Extensions = Extensions
            }.Build().Output;

            // Create the named bind paths to the packages.
            Dictionary <string, string> bindPaths = new Dictionary <string, string>();

            bindPaths.Add("packageA", packageA);
            bindPaths.Add("packageB", packageB);

            // Build the bundles.
            string bundleA = new BundleBuilder(this, "BundleA")
            {
                BindPaths = bindPaths, Extensions = Extensions
            }.Build().Output;
            string bundleB = new BundleBuilder(this, "BundleB")
            {
                BindPaths = bindPaths, Extensions = Extensions
            }.Build().Output;

            // Install the base bundle and make sure it's installed.
            BundleInstaller installerA = new BundleInstaller(this, bundleA).Install();

            Assert.True(MsiVerifier.IsPackageInstalled(packageA));
            Assert.False(MsiVerifier.IsPackageInstalled(packageB));
            using (RegistryKey root = this.GetTestRegistryRoot())
            {
                string actualVersion = root.GetValue("Version") as string;
                Assert.Equal(expectedVersion, actualVersion);
            }

            // SFBUG:3469206 - install a bundle without installing the shared package, which should not be ref-counted.
            this.SetPackageRequestedState("PackageA", RequestState.None);

            // Also don't install packageB since it has an authored dependency on packageA and would fail this test case.
            this.SetPackageRequestedState("PackageB", RequestState.None);

            BundleInstaller installerB = new BundleInstaller(this, bundleB).Install();

            Assert.True(MsiVerifier.IsPackageInstalled(packageA));
            Assert.False(MsiVerifier.IsPackageInstalled(packageB));
            using (RegistryKey root = this.GetTestRegistryRoot())
            {
                string actualVersion = root.GetValue("Version") as string;
                Assert.Equal(expectedVersion, actualVersion);
            }

            // Uninstall the first bundle and make sure packageA is uninstalled.
            this.ResetPackageStates("PackageA");
            installerA.Uninstall();
            Assert.False(MsiVerifier.IsPackageInstalled(packageA));
            Assert.False(MsiVerifier.IsPackageInstalled(packageB));
            using (RegistryKey root = this.GetTestRegistryRoot())
            {
                string actualVersion = root.GetValue("Version") as string;
                Assert.Equal(expectedVersion, actualVersion);
            }

            // Uninstall the second bundle and make sure all packages are uninstalled.
            installerB.Uninstall();
            Assert.False(MsiVerifier.IsPackageInstalled(packageA));
            Assert.False(MsiVerifier.IsPackageInstalled(packageB));
            using (RegistryKey root = this.GetTestRegistryRoot())
            {
                Assert.Null(root.GetValue("Version"));
            }

            this.Complete();
        }
        public void Burn_UninstallAddonBundle()
        {
            const string expectedVersion = "1.0.0.0";

            // Build the packages.
            string packageA = new PackageBuilder(this, "A")
            {
                Extensions = Extensions
            }.Build().Output;
            string packageB = new PackageBuilder(this, "B")
            {
                Extensions = Extensions
            }.Build().Output;

            // Create the named bind paths to the packages.
            Dictionary <string, string> bindPaths = new Dictionary <string, string>();

            bindPaths.Add("packageA", packageA);
            bindPaths.Add("packageB", packageB);

            // Build the bundles.
            string bundleA1 = new BundleBuilder(this, "BundleA")
            {
                BindPaths = bindPaths, Extensions = Extensions
            }.Build().Output;
            string bundleA2 = new BundleBuilder(this, "BundleA")
            {
                BindPaths = bindPaths, Extensions = Extensions
            }.Build().Output;
            string bundleF = new BundleBuilder(this, "BundleF")
            {
                BindPaths = bindPaths, Extensions = Extensions
            }.Build().Output;

            // Install the base bundle and make sure all packages are installed.
            BundleInstaller installerF = new BundleInstaller(this, bundleF).Install();

            Assert.True(MsiVerifier.IsPackageInstalled(packageA));
            Assert.True(MsiVerifier.IsPackageInstalled(packageB));

            // Install an addon bundle and make sure all packages are installed.
            BundleInstaller installerA1 = new BundleInstaller(this, bundleA1).Install();

            Assert.True(MsiVerifier.IsPackageInstalled(packageA));
            Assert.True(MsiVerifier.IsPackageInstalled(packageB));
            using (RegistryKey root = this.GetTestRegistryRoot())
            {
                string actualVersion = root.GetValue("Version") as string;
                Assert.Equal(expectedVersion, actualVersion);
            }

            // Install a second addon bundle and make sure all packages are installed.
            BundleInstaller installerA2 = new BundleInstaller(this, bundleA2).Install();

            Assert.True(MsiVerifier.IsPackageInstalled(packageA));
            Assert.True(MsiVerifier.IsPackageInstalled(packageB));
            using (RegistryKey root = this.GetTestRegistryRoot())
            {
                string actualVersion = root.GetValue("Version") as string;
                Assert.Equal(expectedVersion, actualVersion);
            }

            // Uninstall the base bundle and make sure all packages are uninstalled.
            installerF.Uninstall();
            Assert.False(MsiVerifier.IsPackageInstalled(packageA));
            Assert.False(MsiVerifier.IsPackageInstalled(packageB));
            Assert.Null(this.GetTestRegistryRoot());

            this.Complete();
        }
        override public void Execute()
        {
            DocumentPackage superDuperPackage = PackageBuilder.NewPackageNamed("DocumentVisibilityExample: " + DateTime.Now)
                                                .WithSigner(SignerBuilder.NewSignerWithEmail(email1)
                                                            .WithCustomId(SIGNER1_ID)
                                                            .WithFirstName("John1")
                                                            .WithLastName("Smith1"))
                                                .WithSigner(SignerBuilder.NewSignerWithEmail(email2)
                                                            .WithCustomId(SIGNER2_ID)
                                                            .WithFirstName("John2")
                                                            .WithLastName("Smith2"))
                                                .WithSigner(SignerBuilder.NewSignerWithEmail(email3)
                                                            .WithCustomId(SIGNER3_ID)
                                                            .WithFirstName("John3")
                                                            .WithLastName("Smith3"))
                                                .WithDocument(DocumentBuilder.NewDocumentNamed(DOC1_NAME)
                                                              .WithId(DOC1_ID)
                                                              .FromStream(fileStream1, DocumentType.PDF)
                                                              .WithSignature(SignatureBuilder.SignatureFor(email1)
                                                                             .OnPage(0)
                                                                             .AtPosition(100, 100)))
                                                .WithDocument(DocumentBuilder.NewDocumentNamed(DOC2_NAME)
                                                              .WithId(DOC2_ID)
                                                              .FromStream(fileStream2, DocumentType.PDF)
                                                              .WithSignature(SignatureBuilder.SignatureFor(email2)
                                                                             .OnPage(0)
                                                                             .AtPosition(100, 100)))
                                                .WithDocument(DocumentBuilder.NewDocumentNamed(DOC3_NAME)
                                                              .WithId(DOC3_ID)
                                                              .FromStream(fileStream3, DocumentType.PDF)
                                                              .WithSignature(SignatureBuilder.SignatureFor(email3)
                                                                             .OnPage(0)
                                                                             .AtPosition(100, 100)))
                                                .Build();

            packageId = eslClient.CreatePackage(superDuperPackage);



            DocumentVisibility visibility = DocumentVisibilityBuilder.NewDocumentVisibility()
                                            .AddConfiguration(DocumentVisibilityConfigurationBuilder.NewDocumentVisibilityConfiguration(DOC1_ID)
                                                              .WithSignerIds(new List <string> {
                SIGNER1_ID, SIGNER3_ID
            }))
                                            .AddConfiguration(DocumentVisibilityConfigurationBuilder.NewDocumentVisibilityConfiguration(DOC2_ID)
                                                              .WithSignerIds(new List <string> {
                SIGNER2_ID, SIGNER3_ID
            }))
                                            .AddConfiguration(DocumentVisibilityConfigurationBuilder.NewDocumentVisibilityConfiguration(DOC3_ID)
                                                              .WithSignerIds(new List <string> {
                SIGNER3_ID, SIGNER2_ID
            }))
                                            .Build();

            //      You can also set up a document visibility based on signer.

            /*
             * DocumentVisibility visibility = DocumentVisibilityBasedOnSignerBuilder.NewDocumentVisibilityBasedOnSigner()
             *  .AddConfiguration(DocumentVisibilityConfigurationBasedOnSignerBuilder.NewDocumentVisibilityConfigurationBasedOnSigner(SIGNER1_ID)
             *      .WithDocumentIds(new List<string>{ DOC1_ID }))
             *  .AddConfiguration(DocumentVisibilityConfigurationBasedOnSignerBuilder.NewDocumentVisibilityConfigurationBasedOnSigner(SIGNER2_ID)
             *      .WithDocumentIds(new List<string>{ DOC2_ID, DOC3_ID }))
             *  .AddConfiguration(DocumentVisibilityConfigurationBasedOnSignerBuilder.NewDocumentVisibilityConfigurationBasedOnSigner(SIGNER3_ID)
             *      .WithDocumentIds(new List<string>{ DOC1_ID, DOC2_ID, DOC3_ID }))
             * .Build();
             */

            eslClient.ConfigureDocumentVisibility(packageId, visibility);

            retrievedVisibility = eslClient.getDocumentVisibility(packageId);

            eslClient.SendPackage(packageId);
            retrievedPackage = eslClient.GetPackage(packageId);

            documentsForSigner1 = eslClient.GetDocuments(packageId, SIGNER1_ID);
            documentsForSigner2 = eslClient.GetDocuments(packageId, SIGNER2_ID);
            documentsForSigner3 = eslClient.GetDocuments(packageId, SIGNER3_ID);

            signersForDocument1 = eslClient.GetSigners(packageId, DOC1_ID);
            signersForDocument2 = eslClient.GetSigners(packageId, DOC2_ID);
            signersForDocument3 = eslClient.GetSigners(packageId, DOC3_ID);
        }
예제 #44
0
 private TemporaryFile CreateSamplePackage()
 {
     return(new TemporaryFile(PackageBuilder.BuildSamplePackage(FileShare.PackageId, FileShare.Version.ToString())));
 }
예제 #45
0
        public void Pack(string nuspecPath, bool packSymbols)
        {
            try
            {
                PackageBuilder builder = new PackageBuilder();

                using (var nuspecFile = File.Open(nuspecPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
                {
                    string   baseDirectoryPath = (string.IsNullOrEmpty(BaseDirectory)) ? Path.GetDirectoryName(nuspecPath) : BaseDirectory;
                    Manifest manifest          = Manifest.ReadFrom(nuspecFile, false);
                    builder.Populate(manifest.Metadata);
                    builder.PopulateFiles(baseDirectoryPath, manifest.Files);

                    PathResolver.FilterPackageFiles(
                        builder.Files,
                        file => file.Path,
                        packSymbols ? SymbolPackageExcludes : LibPackageExcludes);
                }

                if (packSymbols)
                {
                    // Symbol packages are only valid if they contain both symbols and sources.
                    Dictionary <string, bool> pathHasMatches = LibPackageExcludes.ToDictionary(
                        path => path,
                        path => PathResolver.GetMatches(builder.Files, file => file.Path, new[] { path }).Any());

                    if (!pathHasMatches.Values.Any(i => i))
                    {
                        Log.LogMessage(LogImportance.Low, $"Nuspec {nuspecPath} does not contain symbol or source files. Not creating symbol package.");
                        return;
                    }
                    foreach (var pathPair in pathHasMatches.Where(pathMatchPair => !pathMatchPair.Value))
                    {
                        Log.LogMessage(LogImportance.Low, $"Nuspec {nuspecPath} does not contain any files matching {pathPair.Key}. Not creating symbol package.");
                        return;
                    }
                }

                // Overriding the Version from the Metadata if one gets passed in.
                if (!string.IsNullOrEmpty(PackageVersion))
                {
                    NuGetVersion overrideVersion;
                    if (NuGetVersion.TryParse(PackageVersion, out overrideVersion))
                    {
                        builder.Version = overrideVersion;
                    }
                    else
                    {
                        Log.LogError($"Failed to parse Package Version: '{PackageVersion}' is not a valid version.");
                        return;
                    }
                }

                string id = builder.Id, version = builder.Version.ToString();

                if (String.IsNullOrEmpty(id))
                {
                    Log.LogError($"Nuspec {nuspecPath} does not contain a valid Id");
                    return;
                }

                if (String.IsNullOrEmpty(version))
                {
                    Log.LogError($"Nuspec {nuspecPath} does not contain a valid version");
                    return;
                }

                string nupkgOutputDirectory = OutputDirectory;

                if (packSymbols && !string.IsNullOrEmpty(SymbolPackageOutputDirectory))
                {
                    nupkgOutputDirectory = SymbolPackageOutputDirectory;
                }

                string nupkgExtension       = packSymbols ? ".symbols.nupkg" : ".nupkg";
                string nupkgPath            = Path.Combine(nupkgOutputDirectory, $"{id}.{version}{nupkgExtension}");

                var directory = Path.GetDirectoryName(nupkgPath);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                using (var fileStream = File.Create(nupkgPath))
                {
                    builder.Save(fileStream);
                }

                Log.LogMessage($"Created '{nupkgPath}'");
            }
            catch (Exception e)
            {
                string packageType = packSymbols ? "symbol" : "lib";
                Log.LogError($"Error when creating nuget {packageType} package from {nuspecPath}. {e}");
            }
        }
예제 #46
0
        public void GetPackages_ReturnsAllPackagesInsideDirectory()
        {
            // Arrange
            var fooPackage = new PackageBuilder
            {
                Id          = "Foo",
                Version     = new SemanticVersion("1.0.0"),
                Description = "Some description",
            };

            fooPackage.Authors.Add("test author");
            fooPackage.Files.Add(
                PackageUtility.CreateMockedPackageFile(@"lib\net40", "Foo.dll", "lib contents").Object);

            var barPackage = new PackageBuilder
            {
                Id          = "Bar",
                Version     = new SemanticVersion("1.0.0-beta1"),
                Description = "Some description",
            };

            barPackage.Authors.Add("test author");
            barPackage.Files.Add(
                PackageUtility.CreateMockedPackageFile("", "README.md", "lib contents").Object);
            barPackage.Files.Add(
                PackageUtility.CreateMockedPackageFile(@"content", "qwerty.js", "bar contents").Object);

            barPackage.Files.Add(
                PackageUtility.CreateMockedPackageFile(@"lib\net451", "test.dll", "test-dll").Object);

            var fileSystem = new MockFileSystem();
            var fooRoot    = Path.Combine("Foo", "1.0.0");

            fileSystem.AddFile(Path.Combine(fooRoot, "Foo.nuspec"),
                               @"<?xml version=""1.0""?><package><metadata><id>Foo</id><version>1.0.0</version><authors>None</authors><description>None</description></metadata></package>");
            fileSystem.AddFile(Path.Combine("Foo", "1.0.0", "Foo.1.0.0.nupkg.sha512"), "Foo-sha");
            fileSystem.AddFile(Path.Combine("Foo", "1.0.0", "Foo.1.0.0.nupkg"), GetPackageStream(fooPackage));

            var barRoot = Path.Combine("Bar", "1.0.0-beta1");

            fileSystem.AddFile(Path.Combine(barRoot, "Bar.nuspec"),
                               @"<?xml version=""1.0""?><package><metadata><id>Bar</id><version>1.0.0.0-beta1</version><authors>None</authors><description>None</description></metadata></package>");
            fileSystem.AddFile(Path.Combine("Bar", "1.0.0-beta1", "Bar.1.0.0-beta1.nupkg.sha512"), "bar-sha");
            fileSystem.AddFile(Path.Combine("Bar", "1.0.0-beta1", "Bar.1.0.0-beta1.nupkg"), GetPackageStream(barPackage));

            var repository = new ExpandedPackageRepository(fileSystem);

            // Act
            var packages = repository.GetPackages().ToList();

            // Assert
            Assert.Equal(2, packages.Count);

            var package = packages[0];

            Assert.Equal("Foo", package.Id);
            Assert.Equal(new SemanticVersion("1.0.0"), package.Version);
            var packageFile = Assert.Single(package.GetFiles());

            Assert.Equal(@"lib\net40\Foo.dll", packageFile.Path);
            Assert.Equal(".NETFramework,Version=v4.0", packageFile.TargetFramework.FullName);

            package = packages[1];
            Assert.Equal("Bar", package.Id);
            Assert.Equal(new SemanticVersion("1.0.0-beta1"), package.Version);

            var files = package.GetFiles().OrderBy(p => p.Path.Length).ToList();

            Assert.Equal(3, files.Count);
            Assert.Equal(@"README.md", files[0].Path);

            packageFile = files[1];
            Assert.Equal(@"content\qwerty.js", packageFile.Path);
            Assert.Null(packageFile.TargetFramework);

            packageFile = files[2];
            Assert.Equal(@"lib\net451\test.dll", packageFile.Path);
            Assert.Equal(".NETFramework,Version=v4.5.1", packageFile.TargetFramework.FullName);
        }
예제 #47
0
 public Gtk.Widget CreateEditor(PackageBuilder target)
 {
     return(new SourcesZipEditorWidget(target, null));
 }
예제 #48
0
 public PackageDescriptor(string kind, PackageBuilder builder)
 {
     this.kind    = kind;
     this.builder = builder;
 }
예제 #49
0
        override public void Execute()
        {
            DocumentPackage superDuperPackage =
                PackageBuilder.NewPackageNamed("SignatureManipulationExample: " + DateTime.Now)
                .DescribedAs("This is a package created using the e-SignLive SDK")
                .ExpiresOn(DateTime.Now.AddMonths(100))
                .WithSigner(SignerBuilder.NewSignerWithEmail(email1)
                            .WithCustomId("signatureId1")
                            .WithFirstName("firstName1")
                            .WithLastName("lastName1")
                            )
                .WithSigner(SignerBuilder.NewSignerWithEmail(email2)
                            .WithCustomId("signatureId2")
                            .WithFirstName("firstName2")
                            .WithLastName("lastName2")
                            )
                .WithSigner(SignerBuilder.NewSignerWithEmail(email3)
                            .WithCustomId("signatureId3")
                            .WithFirstName("firstName3")
                            .WithLastName("lastName3")
                            )
                .WithDocument(DocumentBuilder.NewDocumentNamed(DOCUMENT_NAME)
                              .WithId("documentId")
                              .FromStream(fileStream, DocumentType.PDF)
                              )

                .Build();

            packageId = eslClient.CreatePackage(superDuperPackage);

            signature1 = SignatureBuilder.SignatureFor(email1)
                         .OnPage(0)
                         .WithId(new SignatureId("signatureId1"))
                         .AtPosition(100, 100)
                         .Build();

            signature2 = SignatureBuilder.SignatureFor(email2)
                         .OnPage(0)
                         .WithId(new SignatureId("signatureId2"))
                         .AtPosition(100, 200)
                         .Build();

            signature3 = SignatureBuilder.SignatureFor(email3)
                         .OnPage(0)
                         .WithId(new SignatureId("signatureId3"))
                         .AtPosition(100, 300)
                         .Build();

            modifiedSignature = SignatureBuilder.SignatureFor(email1)
                                .OnPage(0)
                                .WithId(new SignatureId("signatureId3"))
                                .AtPosition(200, 400)
                                .Build();

            // Adding the signatures
            createdPackage = eslClient.GetPackage(packageId);
            eslClient.ApprovalService.AddApproval(createdPackage, documentId, signature1);
            eslClient.ApprovalService.AddApproval(createdPackage, documentId, signature2);
            eslClient.ApprovalService.AddApproval(createdPackage, documentId, signature3);
            addedSignatures = eslClient.GetPackage(packageId).Documents[DOCUMENT_NAME].Signatures;

            // Deleting signature for signer 1
            eslClient.ApprovalService.DeleteApproval(packageId, "documentId", "signatureId1");
            deletedSignatures = eslClient.GetPackage(packageId).Documents[DOCUMENT_NAME].Signatures;

            // Updating the information for the third signature
            createdPackage = eslClient.GetPackage(packageId);
            eslClient.ApprovalService.ModifyApproval(createdPackage, "documentId", modifiedSignature);
            modifiedSignatures = eslClient.GetPackage(packageId).Documents[DOCUMENT_NAME].Signatures;

            // Update all the signatures in the document with the provided list of signatures
            updatedSignature1 = SignatureBuilder.SignatureFor(email2)
                                .OnPage(0)
                                .AtPosition(300, 300)
                                .WithId(new SignatureId("signatureId2"))
                                .WithField(FieldBuilder.SignerName()
                                           .AtPosition(100, 100)
                                           .OnPage(0))
                                .Build();

            updatedSignature2 = SignatureBuilder.SignatureFor(email3)
                                .OnPage(0)
                                .AtPosition(300, 500)
                                .WithId(new SignatureId("signatureId3"))
                                .Build();

            List <Signature> signatureList = new List <Signature>();

            signatureList.Add(updatedSignature1);
            signatureList.Add(updatedSignature2);
            eslClient.ApprovalService.UpdateApprovals(createdPackage, documentId, signatureList);
            updatedSignatures = eslClient.GetPackage(packageId).Documents[DOCUMENT_NAME].Signatures;
        }
        public PackageBuilder CreateBuilder(string basePath, NuGetVersion version, string suffix, bool buildIfNeeded, PackageBuilder builder)
        {
            // Add output files
            Files.Clear();
            builder.Files.Clear();

            AddOutputFiles(builder);

            // Add content files if there are any. They could come from a project or nuspec file
            AddContentFiles(builder);

            // Add sources if this is a symbol package
            if (IncludeSymbols)
            {
                AddSourceFiles();
            }

            var manifest     = new Manifest(new ManifestMetadata(builder), Files);
            var manifestPath = PackCommandRunner.GetOutputPath(
                builder,
                PackArgs,
                IncludeSymbols,
                builder.Version,
                PackTargetArgs.NuspecOutputPath,
                isNupkg: false);

            var manifestDirectory = Path.GetDirectoryName(manifestPath);

            if (!Directory.Exists(manifestDirectory))
            {
                Directory.CreateDirectory(manifestDirectory);
            }

            using (Stream stream = new FileStream(manifestPath, FileMode.Create))
            {
                manifest.Save(stream);
            }

            builder.PopulateFiles(string.Empty, Files);

            return(builder);
        }
 public void Init()
 {
     packageV1 = new TemporaryFile(PackageBuilder.BuildSamplePackage("Acme.Web", "1.0.0"));
     packageV2 = new TemporaryFile(PackageBuilder.BuildSamplePackage("Acme.Web", "2.0.0"));
 }
예제 #52
0
        /// <summary>
        /// Exports the page.
        /// </summary>
        /// <param name="page">The page.</param>
        /// <param name="isRecursive">if set to <c>true</c> [should export children].</param>
        /// <returns>a <see cref="T:System.IO.MemoryStream"/> of the exported page package.</returns>
        public MemoryStream ExportPage(Page page, bool isRecursive)
        {
            // Create a temp directory to hold package contents in staging area
            string packageId        = Guid.NewGuid().ToString();
            var    packageDirectory = CreatePackageDirectory(page.InternalName, packageId);
            var    webRootPath      = HttpContext.Current.Server.MapPath("~");

            // Create a manifest for this page export...
            Manifest manifest = new Manifest();

            manifest.Metadata             = new ManifestMetadata();
            manifest.Metadata.Authors     = "PageExport";
            manifest.Metadata.Version     = "0.0";
            manifest.Metadata.Id          = packageId;
            manifest.Metadata.Description = (string.IsNullOrEmpty(page.Description)) ? "a page export" : page.Description;
            manifest.Files = new List <ManifestFile>();

            // Generate the JSON from model data and write it to disk, then add it to the manifest
            var json = GetJson(page, isRecursive);

            using (var file = new StreamWriter(Path.Combine(packageDirectory.FullName, "export.json")))
            {
                file.Write(json);
            }
            AddToManifest(manifest, packageDirectory.FullName, webRootPath, "export.json", SearchOption.TopDirectoryOnly);

            // * Find out from `page` which Blocks need to be packaged up (recursively if ExportChildren box is checked)
            // * Grab asset folders for each Block's code file uniquely (Scripts, Assets, CSS folders)
            // * Add them to the package manifest
            var blockTypes        = new Dictionary <Guid, BlockType>();
            var uniqueDirectories = new Dictionary <string, string>();

            FindUniqueBlockTypesAndDirectories(page, isRecursive, blockTypes, uniqueDirectories);

            foreach (var blockType in blockTypes.Values)
            {
                var sourcePath = HttpContext.Current.Server.MapPath(blockType.Path);
                var directory  = sourcePath.Substring(0, sourcePath.LastIndexOf(Path.DirectorySeparatorChar));
                var fileName   = Path.GetFileNameWithoutExtension(sourcePath);
                var pattern    = string.Format("{0}.*", fileName);
                AddToManifest(manifest, directory, webRootPath, pattern, SearchOption.TopDirectoryOnly);
            }

            // Second pass through blocks. Determine which folders (by convention) need to be added
            // to the package manifest.
            foreach (var dir in uniqueDirectories.Keys)
            {
                var sourcePath = HttpContext.Current.Server.MapPath(dir);
                // Are there any folders present named "CSS", "Scripts" or "Assets"?
                AddToManifest(manifest, Path.Combine(sourcePath, "CSS"), webRootPath);
                AddToManifest(manifest, Path.Combine(sourcePath, "Scripts"), webRootPath);
                AddToManifest(manifest, Path.Combine(sourcePath, "Assets"), webRootPath);
            }

            // Save the manifest as "pageexport.nuspec" in the temp folder
            string basePath     = packageDirectory.FullName;
            string manifestPath = Path.Combine(basePath, "pageexport.nuspec");

            using (Stream fileStream = File.Create(manifestPath))
            {
                manifest.Save(fileStream);
            }

            // Create a NuGet package from the manifest and 'save' it to a memory stream for the consumer...
            // BTW - don't use anything older than nuget 2.1 due to Manifest bug (http://nuget.codeplex.com/workitem/2813)
            // which will cause the PackageBuilder constructor to fail due to <Files> vs <files> being in the manifest.
            PackageBuilder packageBuilder = new PackageBuilder(manifestPath, basePath, NullPropertyProvider.Instance, false);

            var outputStream = new MemoryStream();

            packageBuilder.Save(outputStream);

            // Clean up staging area
            packageDirectory.Delete(recursive: true);
            return(outputStream);
        }
예제 #53
0
        public void Burn_AutomaticSlipstreamInstallUninstall()
        {
            const string originalVersion = "1.0.0.0";
            const string patchedVersion  = "1.0.1.0";

            // Build the packages.
            string packageA       = this.GetPackageA().Output;
            string packageAUpdate = this.GetPackageAv101().Output;
            string packageB       = this.GetPackageB().Output;
            string packageBUpdate = new PackageBuilder(this, "B")
            {
                PreprocessorVariables = new Dictionary <string, string>()
                {
                    { "Version", patchedVersion }
                }, NeverGetsInstalled = true
            }.Build().Output;
            string patchA = new PatchBuilder(this, "PatchA")
            {
                PreprocessorVariables = new Dictionary <string, string>()
                {
                    { "Version", patchedVersion }
                }, TargetPaths = new string[] { packageA, packageB }, UpgradePaths = new string[] { packageAUpdate, packageBUpdate }
            }.Build().Output;
            string patchB = new PatchBuilder(this, "PatchB")
            {
                PreprocessorVariables = new Dictionary <string, string>()
                {
                    { "Version", patchedVersion }
                }, TargetPaths = new string[] { packageA, packageB }, UpgradePaths = new string[] { packageAUpdate, packageBUpdate }
            }.Build().Output;

            // Create the named bind paths to the packages.
            Dictionary <string, string> bindPaths = new Dictionary <string, string>();

            bindPaths.Add("packageA", packageA);
            bindPaths.Add("packageB", packageB);
            bindPaths.Add("patchA", patchA);
            bindPaths.Add("patchB", patchB);

            string bundleC = new BundleBuilder(this, "BundleC")
            {
                BindPaths = bindPaths, Extensions = Extensions
            }.Build().Output;
            BundleInstaller install = new BundleInstaller(this, bundleC).Install();

            using (RegistryKey root = this.GetTestRegistryRoot())
            {
                // Product A should've slipstreamed both patches.
                string actualVersion = root.GetValue("A") as string;
                Assert.Equal(patchedVersion, actualVersion);

                actualVersion = root.GetValue("A2") as string;
                Assert.Equal(patchedVersion, actualVersion);

                // Product B should've only slipstreamed patch B.
                actualVersion = root.GetValue("B") as string;
                Assert.Equal(originalVersion, actualVersion);

                actualVersion = root.GetValue("B2") as string;
                Assert.Equal(patchedVersion, actualVersion);
            }

            install.Uninstall();

            Assert.True(null == this.GetTestRegistryRoot(), "Test registry key should have been removed during uninstall.");

            this.Complete();
        }
예제 #54
0
        public PackageId CreateTemplateFromPackage(PackageId originalPackageId, string templateName)
        {
            DocumentPackage sdkPackage = PackageBuilder.NewPackageNamed(templateName).Build();

            return(CreateTemplateFromPackage(originalPackageId, sdkPackage));
        }
예제 #55
0
        public PackageBuilder GetPackageBuilder(IPackTaskRequest <IMSBuildItem> request)
        {
            // Load the assets JSON file produced by restore.
            var assetsFilePath = Path.Combine(request.RestoreOutputPath, LockFileFormat.AssetsFileName);

            if (!File.Exists(assetsFilePath))
            {
                throw new PackagingException(NuGetLogCode.NU5023, string.Format(
                                                 CultureInfo.CurrentCulture,
                                                 Strings.AssetsFileNotFound,
                                                 assetsFilePath));
            }

            var builder = new PackageBuilder(request.Deterministic)
            {
                Id                       = request.PackageId,
                Description              = request.Description,
                Title                    = request.Title,
                Copyright                = request.Copyright,
                ReleaseNotes             = request.ReleaseNotes,
                RequireLicenseAcceptance = request.RequireLicenseAcceptance,
                PackageTypes             = ParsePackageTypes(request)
            };

            if (request.DevelopmentDependency)
            {
                builder.DevelopmentDependency = true;
            }

            if (request.PackageVersion != null)
            {
                NuGetVersion version;
                if (!NuGetVersion.TryParse(request.PackageVersion, out version))
                {
                    throw new PackagingException(NuGetLogCode.NU5024, string.Format(
                                                     CultureInfo.CurrentCulture,
                                                     Strings.InvalidPackageVersion,
                                                     request.PackageVersion));
                }
                builder.Version = version;
            }
            else
            {
                builder.Version = new NuGetVersion("1.0.0");
            }

            if (request.Authors != null)
            {
                builder.Authors.AddRange(request.Authors);
            }

            if (request.Tags != null)
            {
                builder.Tags.AddRange(request.Tags);
            }

            Uri tempUri;

            if (Uri.TryCreate(request.LicenseUrl, UriKind.Absolute, out tempUri))
            {
                builder.LicenseUrl = tempUri;
            }
            if (Uri.TryCreate(request.ProjectUrl, UriKind.Absolute, out tempUri))
            {
                builder.ProjectUrl = tempUri;
            }
            if (Uri.TryCreate(request.IconUrl, UriKind.Absolute, out tempUri))
            {
                builder.IconUrl = tempUri;
            }
            if (!string.IsNullOrEmpty(request.RepositoryUrl) || !string.IsNullOrEmpty(request.RepositoryType))
            {
                builder.Repository = new RepositoryMetadata(
                    request.RepositoryType,
                    request.RepositoryUrl,
                    request.RepositoryBranch,
                    request.RepositoryCommit);
            }

            builder.LicenseMetadata = BuildLicenseMetadata(request);

            builder.Icon = request.PackageIcon;

            if (request.MinClientVersion != null)
            {
                Version version;
                if (!Version.TryParse(request.MinClientVersion, out version))
                {
                    throw new PackagingException(NuGetLogCode.NU5022, string.Format(
                                                     CultureInfo.CurrentCulture,
                                                     Strings.InvalidMinClientVersion,
                                                     request.MinClientVersion));
                }

                builder.MinClientVersion = version;
            }

            // The assets file is necessary for project and package references. Pack should not do any traversal,
            // so we leave that work up to restore (which produces the assets file).
            var lockFileFormat = new LockFileFormat();
            var assetsFile     = lockFileFormat.Read(assetsFilePath);

            if (assetsFile.PackageSpec == null)
            {
                throw new PackagingException(NuGetLogCode.NU5025, string.Format(
                                                 CultureInfo.CurrentCulture,
                                                 Strings.AssetsFileDoesNotHaveValidPackageSpec,
                                                 assetsFilePath));
            }

            var projectRefToVersionMap = new Dictionary <string, string>(PathUtility.GetStringComparerBasedOnOS());

            if (request.ProjectReferencesWithVersions != null && request.ProjectReferencesWithVersions.Any())
            {
                projectRefToVersionMap = request
                                         .ProjectReferencesWithVersions
                                         .ToDictionary(msbuildItem => msbuildItem.Identity,
                                                       msbuildItem => msbuildItem.GetProperty("ProjectVersion"), PathUtility.GetStringComparerBasedOnOS());
            }
            var nuGetFrameworkComparer = new NuGetFrameworkFullComparer();
            var frameworksWithSuppressedDependencies = new HashSet <NuGetFramework>(nuGetFrameworkComparer);

            if (request.FrameworksWithSuppressedDependencies != null && request.FrameworksWithSuppressedDependencies.Any())
            {
                frameworksWithSuppressedDependencies =
                    new HashSet <NuGetFramework>(request.FrameworksWithSuppressedDependencies
                                                 .Select(t => NuGetFramework.Parse(t.Identity)).ToList(), nuGetFrameworkComparer);
            }

            PopulateProjectAndPackageReferences(builder,
                                                assetsFile,
                                                projectRefToVersionMap,
                                                frameworksWithSuppressedDependencies);

            PopulateFrameworkAssemblyReferences(builder, request);
            PopulateFrameworkReferences(builder, assetsFile);

            return(builder);
        }
예제 #56
0
        override public void Execute()
        {
            DocumentPackage package = PackageBuilder.NewPackageNamed(PackageName)
                                      .DescribedAs("This is a new package")
                                      .WithSigner(SignerBuilder.NewSignerWithEmail(email1)
                                                  .WithFirstName("John")
                                                  .WithLastName("Smith"))
                                      .WithDocument(DocumentBuilder.NewDocumentNamed(DOCUMENT_NAME)
                                                    .FromStream(fileStream1, DocumentType.PDF)
                                                    .WithSignature(SignatureBuilder.SignatureFor(email1)
                                                                   .OnPage(0)
                                                                   .AtPosition(500, 100)
                                                                   .WithField(FieldBuilder.TextField()
                                                                              .WithId(TEXTFIELD_ID)
                                                                              .WithFontSize(TEXTFIELD_FONT_SIZE)
                                                                              .OnPage(TEXTFIELD_PAGE)
                                                                              .AtPosition(500, 200))
                                                                   .WithField(FieldBuilder.CheckBox()
                                                                              .WithId(CHECKBOX_ID)
                                                                              .WithValue(CHECKBOX_VALUE)
                                                                              .OnPage(CHECKBOX_PAGE)
                                                                              .AtPosition(500, 300))
                                                                   .WithField(FieldBuilder.RadioButton(RADIO_GROUP_1)
                                                                              .WithId(RADIO_ID_1)
                                                                              .WithValue(false)
                                                                              .WithSize(RADIO_WIDTH, RADIO_HEIGHT)
                                                                              .OnPage(RADIO_PAGE)
                                                                              .AtPosition(500, 400))
                                                                   .WithField(FieldBuilder.RadioButton(RADIO_GROUP_1)
                                                                              .WithId(RADIO_ID_2)
                                                                              .WithValue(true)
                                                                              .WithSize(RADIO_WIDTH, RADIO_HEIGHT)
                                                                              .OnPage(RADIO_PAGE)
                                                                              .AtPosition(500, 450))
                                                                   .WithField(FieldBuilder.RadioButton(RADIO_GROUP_2)
                                                                              .WithId(RADIO_ID_3)
                                                                              .WithValue(true)
                                                                              .WithSize(RADIO_WIDTH, RADIO_HEIGHT)
                                                                              .OnPage(RADIO_PAGE)
                                                                              .AtPosition(500, 500))
                                                                   .WithField(FieldBuilder.RadioButton(RADIO_GROUP_2)
                                                                              .WithId(RADIO_ID_4)
                                                                              .WithValue(false)
                                                                              .WithSize(RADIO_WIDTH, RADIO_HEIGHT)
                                                                              .OnPage(RADIO_PAGE)
                                                                              .AtPosition(500, 550))
                                                                   .WithField(FieldBuilder.DropList()
                                                                              .WithId(DROP_LIST_ID)
                                                                              .WithValue(DROP_LIST_OPTION2)
                                                                              .WithFontSize(DROP_LIST_FONT_SIZE)
                                                                              .WithValidation(FieldValidatorBuilder.Basic()
                                                                                              .WithOption(DROP_LIST_OPTION1)
                                                                                              .WithOption(DROP_LIST_OPTION2)
                                                                                              .WithOption(DROP_LIST_OPTION3))
                                                                              .OnPage(DROP_LIST_PAGE)
                                                                              .WithSize(100, 200)
                                                                              .AtPosition(100, 100))
                                                                   .WithField(FieldBuilder.TextArea()
                                                                              .WithId(TEXT_AREA_ID)
                                                                              .WithValue(TEXT_AREA_VALUE)
                                                                              .WithFontSize(TEXT_AREA_FONT_SIZE)
                                                                              .OnPage(TEXT_AREA_PAGE)
                                                                              .WithSize(400, 600)
                                                                              .AtPosition(200, 200))
                                                                   .WithField(FieldBuilder.Label()
                                                                              .WithId(LABEL_ID)
                                                                              .WithValue(LABEL_VALUE)
                                                                              .WithFontSize(LABEL_FIELD_FONT_SIZE)
                                                                              .OnPage(LABEL_PAGE)
                                                                              .WithSize(100, 60)
                                                                              .AtPosition(220, 220))
                                                                   .WithField(FieldBuilder.Datepicker()
                                                                              .WithId(DATEPICKER_ID)
                                                                              .WithName(DATEPICKER_NAME)
                                                                              .WithValue(DATEPICKER_VALUE)
                                                                              .WithFontSize(DATEPICKER_FIELD_FONT_SIZE)
                                                                              .OnPage(DATEPICKER_PAGE)
                                                                              .WithSize(100, 60)
                                                                              .AtPosition(150, 150)
                                                                              .WithValidation(FieldValidatorBuilder.DatepickerFormat(DATEPICKER_FORMAT)
                                                                                              .Required()))))
                                      .Build();

            packageId = eslClient.CreatePackage(package);

            eslClient.SendPackage(PackageId);
            retrievedPackage = eslClient.GetPackage(packageId);
        }
예제 #57
0
        private bool BuildInternal(string projectPath)
        {
            var projectDiagnostics = new List <ICompilationMessage>();

            if (!Runtime.Project.TryGetProject(projectPath, out _currentProject, projectDiagnostics))
            {
                LogError(string.Format("Unable to locate {0}.", Runtime.Project.ProjectFileName));
                return(false);
            }

            var sw = Stopwatch.StartNew();

            var baseOutputPath = GetBuildOutputDir(_currentProject);
            var configurations = _buildOptions.Configurations.DefaultIfEmpty("Debug");

            string frameworkSelectionError;
            var    frameworks = FrameworkSelectionHelper.SelectFrameworks(_currentProject,
                                                                          _buildOptions.TargetFrameworks,
                                                                          _applicationEnvironment.RuntimeFramework,
                                                                          out frameworkSelectionError);

            if (frameworks == null)
            {
                LogError(frameworkSelectionError);
                return(false);
            }

            if (_buildOptions.GeneratePackages &&
                !ScriptExecutor.Execute(_currentProject, "prepack", GetScriptVariable))
            {
                LogError(ScriptExecutor.ErrorMessage);
                return(false);
            }

            if (!ScriptExecutor.Execute(_currentProject, "prebuild", GetScriptVariable))
            {
                LogError(ScriptExecutor.ErrorMessage);
                return(false);
            }

            var success = true;

            var allDiagnostics = new List <ICompilationMessage>();


            PackageBuilder packageBuilder       = null;
            PackageBuilder symbolPackageBuilder = null;
            InstallBuilder installBuilder       = null;
            SourceBuilder  sourceBuilder        = null;

            // Build all specified configurations
            foreach (var configuration in configurations)
            {
                if (_buildOptions.GeneratePackages)
                {
                    // Create a new builder per configuration
                    packageBuilder       = new PackageBuilder();
                    symbolPackageBuilder = new PackageBuilder();
                    InitializeBuilder(_currentProject, packageBuilder);
                    InitializeBuilder(_currentProject, symbolPackageBuilder);
                    installBuilder = new InstallBuilder(_currentProject, packageBuilder, _buildOptions.Reports);
                    sourceBuilder  = new SourceBuilder(_currentProject, packageBuilder, _buildOptions.Reports);
                }

                var configurationSuccess = true;

                var outputPath = Path.Combine(baseOutputPath, configuration);

                // Build all target frameworks a project supports
                foreach (var targetFramework in frameworks)
                {
                    _buildOptions.Reports.Information.WriteLine();
                    _buildOptions.Reports.Information.WriteLine("Building {0} for {1}",
                                                                _currentProject.Name, targetFramework.ToString().Yellow().Bold());

                    var diagnostics = new List <ICompilationMessage>();

                    var context = new BuildContext(_hostServices,
                                                   _applicationEnvironment,
                                                   _cache,
                                                   _cacheContextAccessor,
                                                   _currentProject,
                                                   targetFramework,
                                                   configuration,
                                                   outputPath);

                    context.Initialize(_buildOptions.Reports.Quiet);

                    if (context.Build(diagnostics))
                    {
                        if (_buildOptions.GeneratePackages)
                        {
                            context.PopulateDependencies(packageBuilder);
                            context.AddLibs(packageBuilder, "*.dll");
                            context.AddLibs(packageBuilder, "*.xml");

                            context.PopulateDependencies(symbolPackageBuilder);
                            context.AddLibs(symbolPackageBuilder, "*.*");
                        }
                    }
                    else
                    {
                        configurationSuccess = false;
                    }

                    allDiagnostics.AddRange(diagnostics);

                    WriteDiagnostics(diagnostics);
                }

                success = success && configurationSuccess;

                if (_buildOptions.GeneratePackages)
                {
                    // Create a package per configuration
                    string nupkg        = GetPackagePath(_currentProject, outputPath);
                    string symbolsNupkg = GetPackagePath(_currentProject, outputPath, symbols: true);

                    if (configurationSuccess)
                    {
                        // Generates the application package only if this is an application packages
                        configurationSuccess = installBuilder.Build(outputPath);
                        success = success && configurationSuccess;
                    }

                    if (configurationSuccess)
                    {
                        configurationSuccess = sourceBuilder.Build(outputPath);
                        success = success && configurationSuccess;
                    }

                    if (configurationSuccess)
                    {
                        foreach (var sharedFile in _currentProject.Files.SharedFiles)
                        {
                            var file = new PhysicalPackageFile();
                            file.SourcePath = sharedFile;
                            file.TargetPath = String.Format(@"shared\{0}", Path.GetFileName(sharedFile));
                            packageBuilder.Files.Add(file);
                        }

                        var root = _currentProject.ProjectDirectory;

                        foreach (var path in _currentProject.Files.SourceFiles)
                        {
                            var srcFile = new PhysicalPackageFile();
                            srcFile.SourcePath = path;
                            srcFile.TargetPath = Path.Combine("src", PathUtility.GetRelativePath(root, path));
                            symbolPackageBuilder.Files.Add(srcFile);
                        }

                        using (var fs = File.Create(nupkg))
                        {
                            packageBuilder.Save(fs);
                            _buildOptions.Reports.Quiet.WriteLine("{0} -> {1}", _currentProject.Name, Path.GetFullPath(nupkg));
                        }

                        if (symbolPackageBuilder.Files.Any())
                        {
                            using (var fs = File.Create(symbolsNupkg))
                            {
                                symbolPackageBuilder.Save(fs);
                                _buildOptions.Reports.Quiet.WriteLine("{0} -> {1}", _currentProject.Name, Path.GetFullPath(symbolsNupkg));
                            }
                        }
                    }
                }
            }

            if (!success)
            {
                return(false);
            }

            if (!ScriptExecutor.Execute(_currentProject, "postbuild", GetScriptVariable))
            {
                LogError(ScriptExecutor.ErrorMessage);
                return(false);
            }

            if (_buildOptions.GeneratePackages &&
                !ScriptExecutor.Execute(_currentProject, "postpack", GetScriptVariable))
            {
                LogError(ScriptExecutor.ErrorMessage);
                return(false);
            }

            sw.Stop();

            if (projectDiagnostics.Any())
            {
                // Add a new line to separate the project diagnostics information from compilation diagnostics
                _buildOptions.Reports.Information.WriteLine();

                projectDiagnostics.ForEach(d => LogWarning(d.FormattedMessage));
            }

            allDiagnostics.AddRange(projectDiagnostics);
            WriteSummary(allDiagnostics);

            _buildOptions.Reports.Information.WriteLine("Time elapsed {0}", sw.Elapsed);
            return(success);
        }
예제 #58
0
        protected override void ProcessRecord()
        {
            _path = string.IsNullOrEmpty(_path) ? _literalPath : _path;

            // Get the .psd1 file or .ps1 file
            // Returns the name of the file or the name of the directory, depending on path
            var    pkgFileOrDir = new DirectoryInfo(_path);
            string moduleManifestOrScriptPath;

            if (isScript)
            {
                moduleManifestOrScriptPath = pkgFileOrDir.FullName;
                pkgName = pkgFileOrDir.Name.Remove(pkgFileOrDir.Name.Length - 4);
            }
            else
            {
                moduleManifestOrScriptPath = System.IO.Path.Combine(_path, pkgFileOrDir.Name + ".psd1");
                // Validate that there's a module manifest
                if (!File.Exists(moduleManifestOrScriptPath))
                {
                    var message = String.Format("No file with a .psd1 extension was found in {0}.  Please specify a path to a valid modulemanifest.", moduleManifestOrScriptPath);
                    var ex      = new ArgumentException(message);
                    var moduleManifestNotFound = new ErrorRecord(ex, "moduleManifestNotFound", ErrorCategory.ObjectNotFound, null);

                    this.ThrowTerminatingError(moduleManifestNotFound);
                }
                pkgName = pkgFileOrDir.Name;
            }

            FileInfo moduleFileInfo;

            moduleFileInfo = new FileInfo(moduleManifestOrScriptPath);
            // if there's no specified destination path to publish the nupkg, we'll just create a temp folder and delete it later
            string outputDir = !string.IsNullOrEmpty(_destinationPath) ? _destinationPath : System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString());

            if (!Directory.Exists(outputDir))
            {
                Directory.CreateDirectory(outputDir);
            }

            // if user does not specify that they want to use a nuspec they've created, we'll create a nuspec
            var dependencies = new Hashtable();

            if (string.IsNullOrEmpty(_nuspec))
            {
                _nuspec = createNuspec(outputDir, moduleFileInfo);
            }
            else
            {
                // Read the nuspec passed in to pull out the dependency information
                XDocument doc = XDocument.Load(_nuspec);

                // ex: <version>2.2.1</version>
                var versionNode = doc.Descendants("version");
                NuGetVersion.TryParse(versionNode.FirstOrDefault().Value, out NuGetVersion version);

                if (version == null)
                {
                    var message         = "Version is not specified in the .nuspec provided. Please provide a valid version in the .nuspec.";
                    var ex              = new ArgumentException(message);
                    var versionNotFound = new ErrorRecord(ex, "versionNotFound", ErrorCategory.NotSpecified, null);

                    this.ThrowTerminatingError(versionNotFound);
                }

                // ex: <dependency id="Carbon" version="2.9.2" />
                var dependencyNode = doc.Descendants("dependency");
                foreach (var dep in dependencyNode)
                {
                    dependencies.Add(dep.Attribute("id"), dep.Attribute("version"));
                }
            }

            // find repository
            var r             = new RespositorySettings();
            var repositoryUrl = r.Read(new[] { _repository });

            if (!repositoryUrl.Any())
            {
                var message            = String.Format("The resource repository '{0}' is not a registered. Please run 'Register-PSResourceRepository' in order to publish to this repository.", _repository);
                var ex                 = new ArgumentException(message);
                var repositoryNotFound = new ErrorRecord(ex, "repositoryNotFound", ErrorCategory.ObjectNotFound, null);

                this.ThrowTerminatingError(repositoryNotFound);
            }

            if (!_skipDependenciesCheck)
            {
                // Check to see that all dependencies are in the repository
                var findHelper = new FindHelper();

                foreach (var dependency in dependencies.Keys)
                {
                    // Need to make individual calls since we're look for exact version numbers or ranges.
                    var depName    = new[] { (string)dependency };
                    var depVersion = (string)dependencies[dependency];
                    var type       = new[] { "module", "script" };
                    var repository = new[] { _repository };

                    // Search for and return the dependency if it's in the repository.
                    var dependencyFound = findHelper.beginFindHelper(depName, type, depVersion, true, null, null, repository, _credential, false, false);

                    if (!dependencyFound.Any())
                    {
                        var message            = String.Format("Dependency {0} was not found in repository {1}.  Make sure the dependency is published to the repository before publishing this module.", depName, _repository);
                        var ex                 = new ArgumentException(message); // System.ArgumentException vs PSArgumentException
                        var dependencyNotFound = new ErrorRecord(ex, "DependencyNotFound", ErrorCategory.ObjectNotFound, null);

                        this.ThrowTerminatingError(dependencyNotFound);
                    }
                }
            }

            if (isScript)
            {
                File.Copy(_path, System.IO.Path.Combine(outputDir, pkgName + ".ps1"), true);
            }
            else
            {
                // Create subdirectory structure in temp folder
                foreach (string dir in System.IO.Directory.GetDirectories(_path, "*", System.IO.SearchOption.AllDirectories))
                {
                    var dirName = dir.Substring(_path.Length).Trim(PathSeparators);
                    System.IO.Directory.CreateDirectory(System.IO.Path.Combine(outputDir, dirName));
                }
                // Copy files over to temp folder
                foreach (string fileNamePath in System.IO.Directory.GetFiles(_path, "*", System.IO.SearchOption.AllDirectories))
                {
                    var fileName = fileNamePath.Substring(_path.Length).Trim(PathSeparators);
                    System.IO.File.Copy(fileNamePath, System.IO.Path.Combine(outputDir, fileName));
                }
            }

            var outputDirectory = System.IO.Path.Combine(outputDir, "nupkg");
            // Pack the module or script into a nupkg given a nuspec.
            var builder = new PackageBuilder();
            var runner  = new PackCommandRunner(
                new PackArgs
            {
                CurrentDirectory = outputDir,
                OutputDirectory  = outputDirectory,
                Path             = _nuspec,
                Exclude          = _exclude,
                Symbols          = false,
                Logger           = NullLogger.Instance
            },
                MSBuildProjectFactory.ProjectCreator,
                builder);

            runner.BuildPackage();


            // Push the nupkg to the appropriate repository
            // Pkg version is parsed from .ps1 file or .psd1 file
            var fullNupkgPath = System.IO.Path.Combine(outputDirectory, pkgName + "." + pkgVersion.ToNormalizedString() + ".nupkg");

            var repoURL         = repositoryUrl.First().Properties["Url"].Value.ToString();
            var publishLocation = repoURL.EndsWith("/v2", StringComparison.OrdinalIgnoreCase) ? repoURL + "/package" : repoURL;

            var settings = NuGet.Configuration.Settings.LoadDefaultSettings(null, null, null);

            NuGet.Common.ILogger log = new NuGetLogger();
            PushRunner.Run(
                Settings.LoadDefaultSettings(root: null, configFileName: null, machineWideSettings: null),
                new PackageSourceProvider(settings),
                fullNupkgPath,
                publishLocation,
                _APIKey, // api key
                null,    // symbols source
                null,    // symbols api key
                0,       // timeout
                false,   // disable buffering
                false,   // no symbols
                         // Skip duplicate: if a package and version already exists, skip it and continue with the next package in the push, if any.
                false,   // no skip duplicate
                false,   // enable server endpoint
                log).GetAwaiter().GetResult();
        }
        public void Burn_InstallUpgradeSlipstreamBundle()
        {
            const string expectedVersion1 = "1.0.0.0";
            const string expectedVersion2 = "1.0.1.0";

            // Build the packages.
            string packageA = new PackageBuilder(this, "A")
            {
                Extensions = Extensions
            }.Build().Output;
            string packageA1 = new PackageBuilder(this, "A")
            {
                Extensions = Extensions, PreprocessorVariables = new Dictionary <string, string>()
                {
                    { "Version", expectedVersion2 }
                }, NeverGetsInstalled = true
            }.Build().Output;
            string patchA = new PatchBuilder(this, "PatchA")
            {
                PreprocessorVariables = new Dictionary <string, string>()
                {
                    { "Version", expectedVersion2 }
                }, TargetPath = packageA, UpgradePath = packageA1
            }.Build().Output;

            // Create the named bind paths to the packages.
            Dictionary <string, string> bindPaths = new Dictionary <string, string>();

            bindPaths.Add("packageA", packageA);
            bindPaths.Add("patchA", patchA);

            // Build the bundles.
            string bundleA = new BundleBuilder(this, "BundleA")
            {
                BindPaths = bindPaths, Extensions = Extensions
            }.Build().Output;
            string bundleC = new BundleBuilder(this, "BundleC")
            {
                BindPaths = bindPaths, Extensions = Extensions, PreprocessorVariables = new Dictionary <string, string>()
                {
                    { "Version", expectedVersion2 }
                }
            }.Build().Output;

            // Install the base bundle and make sure it's installed.
            BundleInstaller installerA = new BundleInstaller(this, bundleA).Install();

            Assert.True(MsiVerifier.IsPackageInstalled(packageA));
            using (RegistryKey root = this.GetTestRegistryRoot())
            {
                string actualVersion = root.GetValue("Version") as string;
                Assert.Equal(expectedVersion1, actualVersion);
            }

            // Install the upgrade bundle with a slipstreamed patch and make sure the patch is installed.
            // SFBUG:3387046 - Uninstalling bundle registers a dependency on a package
            BundleInstaller installerC = new BundleInstaller(this, bundleC).Install();

            Assert.True(MsiUtils.IsPatchInstalled(patchA));

            // BundleC doesn't carry the EXE, so make sure it's removed.
            using (RegistryKey root = this.GetTestRegistryRoot())
            {
                Assert.Null(root.GetValue("Version"));
            }

            // Repair the upgrade bundle to make sure it does not prompt for source.
            // SFBUG:3386927 - MSIs get removed from cache during upgrade
            installerC.Repair();

            // Uninstall the slipstream bundle and make sure both packages are uninstalled.
            installerC.Uninstall();
            Assert.False(MsiUtils.IsPatchInstalled(patchA));
            Assert.False(MsiVerifier.IsPackageInstalled(packageA));

            this.Complete();
        }
예제 #60
0
        public void Burn_RedirectPackageCache()
        {
            const string PolicyName = "PackageCache";

            // Build the packages.
            string packageA = new PackageBuilder(this, "A")
            {
                Extensions = Extensions
            }.Build().Output;
            string packageB = new PackageBuilder(this, "B")
            {
                Extensions = Extensions
            }.Build().Output;

            // Create the named bind paths to the packages.
            Dictionary <string, string> bindPaths = new Dictionary <string, string>();

            bindPaths.Add("packageA", packageA);
            bindPaths.Add("packageB", packageB);

            // Build the bundles.
            string bundleA = new BundleBuilder(this, "BundleA")
            {
                BindPaths = bindPaths, Extensions = Extensions
            }.Build().Output;
            string bundleB = new BundleBuilder(this, "BundleB")
            {
                BindPaths = bindPaths, Extensions = Extensions
            }.Build().Output;

            RegistryKey policy = Registry.LocalMachine.CreateSubKey(@"Software\Policies\WiX\Burn");
            string      currentPackageCache = null;

            try
            {
                currentPackageCache = policy.GetValue(PolicyName) as string;

                // Install the first bundle using the default package cache.
                policy.DeleteValue(PolicyName);

                BundleInstaller installerA = new BundleInstaller(this, bundleA).Install();
                Assert.True(MsiVerifier.IsPackageInstalled(packageA));

                // Install the second bundle which has a shared package using the redirected package cache.
                string path = Path.Combine(Path.GetTempPath(), "Package Cache");
                policy.SetValue(PolicyName, path);

                BundleInstaller installerB = new BundleInstaller(this, bundleB).Install();
                Assert.True(MsiVerifier.IsPackageInstalled(packageA));
                Assert.True(MsiVerifier.IsPackageInstalled(packageB));

                // The first bundle should leave package A behind.
                installerA.Uninstall();

                // Now make sure that the second bundle removes packages from either cache directory.
                installerB.Uninstall();

                this.Complete();
            }
            finally
            {
                if (!string.IsNullOrEmpty(currentPackageCache))
                {
                    policy.SetValue(PolicyName, currentPackageCache);
                }
                else
                {
                    policy.DeleteValue(PolicyName);
                }

                policy.Dispose();
            }
        }