/// <summary> /// Harvest a directory. /// </summary> /// <param name="argument">The path of the directory.</param> /// <returns>The harvested directory.</returns> public override Wix.Fragment[] Harvest(string argument) { if (null == argument) { throw new ArgumentNullException("argument"); } Wix.Directory directory = this.HarvestDirectory(argument, "SourceDir\\", true); Wix.DirectoryRef directoryRef = new Wix.DirectoryRef(); directoryRef.Id = this.rootedDirectoryRef; if (this.suppressRootDirectory) { foreach (Wix.ISchemaElement element in directory.Children) { directoryRef.AddChild(element); } } else { directoryRef.AddChild(directory); } Wix.Fragment fragment = new Wix.Fragment(); fragment.AddChild(directoryRef); return(new Wix.Fragment[] { fragment }); }
/// <summary> /// Gets the directory object for the provided application root path. /// </summary> /// <param name="recalculate">Recalculate root directory.</param> /// <returns>Directory for root.</returns> public Wix.Directory GetRootDirectory(bool recalculate) { if (null == this.source) { throw new ArgumentNullException("Source"); } if (recalculate || null == this.rootDirectory) { DirectoryHarvester directoryHarvester = new DirectoryHarvester(); this.rootDirectory = directoryHarvester.HarvestDirectory(this.source, true); Wix.Wix wix = new Wix.Wix(); Wix.Fragment fragment = new Wix.Fragment(); wix.AddChild(fragment); fragment.AddChild(this.rootDirectory); UtilMutator utilMutator = new UtilMutator(); utilMutator.GenerateGuids = true; utilMutator.SetUniqueIdentifiers = true; utilMutator.Mutate(wix); UtilFinalizeHarvesterMutator finalMutator = new UtilFinalizeHarvesterMutator(); finalMutator.Mutate(wix); } return(this.rootDirectory); }
/// <summary> /// Harvest a directory. /// </summary> /// <param name="path">The path of the directory.</param> /// <param name="relativePath">The relative path that will be used when harvesting.</param> /// <param name="harvestChildren">The option to harvest child directories and files.</param> /// <returns>The harvested directory.</returns> public Wix.Directory HarvestDirectory(string path, string relativePath, bool harvestChildren) { if (null == path) { throw new ArgumentNullException("path"); } if (File.Exists(path)) { throw new WixException(WixErrors.ExpectedDirectoryGotFile("dir", path)); } if (null == this.rootedDirectoryRef) { this.rootedDirectoryRef = "TARGETDIR"; } // use absolute paths path = Path.GetFullPath(path); // Remove any trailing separator to ensure Path.GetFileName() will return the directory name. path = path.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); Wix.Directory directory = new Wix.Directory(); directory.Name = Path.GetFileName(path); directory.FileSource = path; if (this.setUniqueIdentifiers) { if (this.suppressRootDirectory) { directory.Id = this.Core.GenerateIdentifier(DirectoryPrefix, this.rootedDirectoryRef); } else { directory.Id = this.Core.GenerateIdentifier(DirectoryPrefix, this.rootedDirectoryRef, directory.Name); } } if (harvestChildren) { try { int fileCount = this.HarvestDirectory(path, relativePath, directory); // its an error to not harvest anything with the option to keep empty directories off if (0 == fileCount && !this.keepEmptyDirectories) { throw new WixException(UtilErrors.EmptyDirectory(path)); } } catch (DirectoryNotFoundException) { throw new WixException(UtilErrors.DirectoryNotFound(path)); } } return(directory); }
/// <summary> /// Harvest a reg file. /// </summary> /// <param name="path">The path of the file.</param> /// <returns>A harvested registy file.</returns> public Wix.Fragment HarvestRegFile(string path) { if (null == path) { throw new ArgumentNullException("path"); } if (!File.Exists(path)) { throw new WixException(UtilErrors.FileNotFound(path)); } Wix.Directory directory = new Wix.Directory(); directory.Id = "TARGETDIR"; // Use absolute paths path = Path.GetFullPath(path); FileInfo file = new FileInfo(path); using (StreamReader sr = file.OpenText()) { string line; this.currentLineNumber = 0; while (null != (line = this.GetNextLine(sr))) { if (line.StartsWith(@"Windows Registry Editor Version 5.00")) { this.unicodeRegistry = true; } else if (line.StartsWith(@"REGEDIT4")) { this.unicodeRegistry = false; } else if (line.StartsWith(@"[HKEY_CLASSES_ROOT\")) { this.ConvertKey(sr, ref directory, Wix.RegistryRootType.HKCR, line.Substring(19, line.Length - 20)); } else if (line.StartsWith(@"[HKEY_CURRENT_USER\")) { this.ConvertKey(sr, ref directory, Wix.RegistryRootType.HKCU, line.Substring(19, line.Length - 20)); } else if (line.StartsWith(@"[HKEY_LOCAL_MACHINE\")) { this.ConvertKey(sr, ref directory, Wix.RegistryRootType.HKLM, line.Substring(20, line.Length - 21)); } else if (line.StartsWith(@"[HKEY_USERS\")) { this.ConvertKey(sr, ref directory, Wix.RegistryRootType.HKU, line.Substring(12, line.Length - 13)); } } } Console.WriteLine("Processing complete"); Wix.Fragment fragment = new Wix.Fragment(); fragment.AddChild(directory); return(fragment); }
/// <summary> /// Harvest a WiX document. /// </summary> /// <param name="argument">The argument for harvesting.</param> /// <returns>The harvested Fragment.</returns> public override Wix.Fragment[] Harvest(string argument) { DirectoryHarvester directoryHarvester = new DirectoryHarvester(); directoryHarvester.Core = this.Core; directoryHarvester.KeepEmptyDirectories = true; IIsWebSiteHarvester iisWebSiteHarvester = new IIsWebSiteHarvester(); iisWebSiteHarvester.Core = this.Core; IIs.WebSite webSite = iisWebSiteHarvester.HarvestWebSite(argument); Wix.Component component = new Wix.Component(); component.AddChild(new Wix.CreateFolder()); component.AddChild(webSite); this.Core.RootDirectory = webSite.Directory; Wix.Directory directory = directoryHarvester.HarvestDirectory(webSite.Directory, true); directory.AddChild(component); Wix.Fragment fragment = new Wix.Fragment(); fragment.AddChild(directory); return(new Wix.Fragment[] { fragment }); }
/// <summary> /// Harvest a file. /// </summary> /// <param name="argument">The path of the file.</param> /// <returns>A harvested file.</returns> public override Wix.Fragment[] Harvest(string argument) { if (null == argument) { throw new ArgumentNullException("argument"); } if (null == this.rootedDirectoryRef) { this.rootedDirectoryRef = "TARGETDIR"; } string fullPath = Path.GetFullPath(argument); Wix.DirectoryRef directoryRef = new Wix.DirectoryRef(); directoryRef.Id = this.rootedDirectoryRef; Wix.File file = this.HarvestFile(fullPath); if (!this.suppressRootDirectory) { file.Source = String.Concat("SourceDir\\", Path.GetFileName(Path.GetDirectoryName(fullPath)), "\\", Path.GetFileName(fullPath)); } Wix.Component component = new Wix.Component(); component.AddChild(file); Wix.Directory directory = new Wix.Directory(); if (this.suppressRootDirectory) { directoryRef.AddChild(component); } else { string directoryPath = Path.GetDirectoryName(Path.GetFullPath(argument)); directory.Name = Path.GetFileName(directoryPath); if (this.setUniqueIdentifiers) { directory.Id = this.Core.GenerateIdentifier(DirectoryPrefix, directoryRef.Id, directory.Name); } directory.AddChild(component); directoryRef.AddChild(directory); } if (this.setUniqueIdentifiers) { file.Id = this.Core.GenerateIdentifier(FilePrefix, (this.suppressRootDirectory) ? directoryRef.Id : directory.Id, Path.GetFileName(file.Source)); component.Id = this.Core.GenerateIdentifier(ComponentPrefix, (this.suppressRootDirectory) ? directoryRef.Id : directory.Id, file.Id); } Wix.Fragment fragment = new Wix.Fragment(); fragment.AddChild(directoryRef); return(new Wix.Fragment[] { fragment }); }
/// <summary> /// Gets the file object for the ApplicationEntry. /// </summary> public Wix.File GetApplicationEntryFile() { if (null != this.applicationRoot && null != this.applicationEntry.Content && null == this.applicationEntryFile) { Wix.Directory applicationDir = this.GetApplicationRootDirectory(); this.applicationEntryFile = this.GetFile(this.applicationEntry.Content, this.applicationRootDirectory); } return(this.applicationEntryFile); }
/// <summary> /// Converts the registry key to a WiX component element. /// </summary> /// <param name="sr">The registry file stream.</param> /// <param name="directory">A WiX directory reference.</param> /// <param name="root">The root key.</param> /// <param name="line">The current line.</param> private void ConvertKey(StreamReader sr, ref Wix.Directory directory, Wix.RegistryRootType root, string line) { Wix.Component component = new Wix.Component(); component.Id = this.Core.GenerateIdentifier(ComponentPrefix, line); component.KeyPath = Wix.YesNoType.yes; this.ConvertValues(sr, ref component, root, line); directory.AddChild(component); }
/// <summary> /// Add a scraped directory to the UI. /// </summary> /// <param name="nodes">The NodeCollection under which the new directory should be added.</param> /// <param name="rootDirectory">Root of the scraped directory info's.</param> /// <param name="directory">The scraped directory to add.</param> /// <param name="skip">true if the directory itself shouldn't be added; false otherwise.</param> private void AddDirectory(TreeNodeCollection nodes, string currentPath, Wix.Directory rootDirectory, Wix.Directory directory, bool skip) { // get the directory icon, add it to the image list, then free it immediately if (!skip) { Icon folderIcon = NativeMethods.GetDirectoryIcon(true, false); DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(currentPath, directory.Name)); TreeNode node = (TreeNode)this.Invoke(this.addTreeNodeCallback, new object[] { nodes, folderIcon, directory.Name, directoryInfo, false }); folderIcon.Dispose(); // add sub-directories and files to this node nodes = node.Nodes; currentPath = Path.Combine(currentPath, directory.Name); } foreach (Wix.ISchemaElement element in directory.Children) { Wix.Component component = element as Wix.Component; if (null != component) { foreach (Wix.ISchemaElement child in component.Children) { Wix.File file = child as Wix.File; if (null != file) { bool selected = false; FileInfo fileInfo = new FileInfo(Path.Combine(currentPath, file.Name)); // if there is no application entry point and we've found an executable make this the application entry point if (this.packageBuilder.ApplicationEntry == null && String.Compare(fileInfo.Extension, ".exe", true, CultureInfo.InvariantCulture) == 0) { //this.packageBuilder.ApplicationEntry = fileInfo.FullName.Substring(rootDirectory.FullName.Length + 1); selected = true; } // get the file icon, add it to the image list, then free it immediately Icon fileIcon = NativeMethods.GetFileIcon(fileInfo.FullName, true, false); this.Invoke(this.addTreeNodeCallback, new object[] { nodes, fileIcon, file.Name, fileInfo, selected }); fileIcon.Dispose(); } } } else { Wix.Directory subDirectory = element as Wix.Directory; if (null != subDirectory) { this.AddDirectory(nodes, currentPath, rootDirectory, subDirectory, false); } } } }
/// <summary> /// Index an element. /// </summary> /// <param name="element">The element to index.</param> private void IndexElement(Wix.ISchemaElement element) { if (element is IIs.WebAddress) { this.webAddresses.Add(element); } else if (element is IIs.WebDir) { this.webDirs.Add(element); } else if (element is IIs.WebDirProperties) { this.webDirProperties.Add(element); } else if (element is IIs.WebFilter) { this.webFilters.Add(element); } else if (element is IIs.WebSite) { this.webSites.Add(element); } else if (element is IIs.WebVirtualDir) { this.webVirtualDirs.Add(element); } else if (element is Wix.Component) { this.components.Add(element); } else if (element is Wix.Directory) { Wix.Directory directory = (Wix.Directory)element; if (null != directory.FileSource) { this.directoryPaths.Add(directory.FileSource, directory); } } else if (element is Wix.Fragment || element is Wix.Module || element is Wix.PatchCreation || element is Wix.Product) { this.rootElement = (Wix.IParentElement)element; } // index the child elements if (element is Wix.IParentElement) { foreach (Wix.ISchemaElement childElement in ((Wix.IParentElement)element).Children) { this.IndexElement(childElement); } } }
/// <summary> /// Returns the File matching the relative path in the Directory tree. /// </summary> /// <param name="rootDirectory">Directory tree to search for relative path in.</param> /// <param name="relativePath">Relative path to the file to find in the directory.</param> /// <returns>File at relativePath in rootDirectory.</returns> private Wix.File GetFile(Wix.Directory rootDirectory, string relativePath) { IEnumerable enumerable = rootDirectory.Children; string[] directory = relativePath.Split(Path.DirectorySeparatorChar); for (int i = 0; i < directory.Length; ++i) { bool found = false; if (i < directory.Length - 1) { foreach (Wix.ISchemaElement element in enumerable) { Wix.Directory childDirectory = element as Wix.Directory; if (null != childDirectory && directory[i] == childDirectory.Name) { enumerable = childDirectory.Children; found = true; break; } } } else { foreach (Wix.ISchemaElement element in enumerable) { Wix.Component component = element as Wix.Component; if (null != component) { foreach (Wix.ISchemaElement child in component.Children) { Wix.File file = child as Wix.File; if (null != file && directory[i] == file.Name) { return(file); } } } } } if (!found) { throw new ApplicationException("Did not find file name"); } } return(null); }
/// <summary> /// Gets the directory object for the ApplicationRoot. /// </summary> public Wix.Directory GetApplicationRootDirectory() { if (null != this.applicationRoot && null == this.applicationRootDirectory) { this.applicationRootDirectory = this.directoryHarvester.HarvestDirectory(this.applicationRoot.Content, true); Wix.Wix wix = new Wix.Wix(); Wix.Fragment fragment = new Wix.Fragment(); wix.AddChild(fragment); fragment.AddChild(this.applicationRootDirectory); this.utilMutator.Mutate(wix); this.finalMutator.Mutate(wix); } return(this.applicationRootDirectory); }
/// <summary> /// Harvest a new directory or return one that was previously harvested. /// </summary> /// <param name="path">The path of the directory.</param> /// <param name="harvestChildren">The option to harvest the children of the directory.</param> /// <returns>The harvested directory.</returns> private Wix.Directory HarvestUniqueDirectory(string path, bool harvestChildren) { if (this.directoryPaths.Contains(path)) { return((Wix.Directory) this.directoryPaths[path]); } else { Wix.Directory directory = this.directoryHarvester.HarvestDirectory(path, harvestChildren); this.rootElement.AddChild(directory); // index this new directory and all of its children this.IndexElement(directory); return(directory); } }
/// <summary> /// Walks a directory structure obtaining Component Id's and Standard Directory Id's. /// </summary> /// <param name="directory">The Directory to walk.</param> /// <returns>true if the directory is TARGETDIR.</returns> private bool WalkDirectory(Wix.Directory directory) { bool isTargetDir = false; if ("TARGETDIR" == directory.Id) { isTargetDir = true; } string standardDirectoryId = null; if (Melter.StartsWithStandardDirectoryId(directory.Id, out standardDirectoryId) && !isTargetDir) { this.AddSetPropertyCustomAction(directory.Id, String.Format(CultureInfo.InvariantCulture, "[{0}]", standardDirectoryId)); } foreach (Wix.ISchemaElement child in directory.Children) { Wix.Directory childDir = child as Wix.Directory; if (null != childDir) { if (isTargetDir) { this.primaryDirectoryRef.AddChild(child); } this.WalkDirectory(childDir); } else { Wix.Component childComponent = child as Wix.Component; if (null != childComponent) { if (isTargetDir) { this.primaryDirectoryRef.AddChild(child); } this.AddComponentRef(childComponent); } } } return(isTargetDir); }
/// <summary> /// Index an element. /// </summary> /// <param name="element">The element to index.</param> private void IndexElement(Wix.ISchemaElement element) { if (element is IIs.WebFilter) { this.webFilters.Add(element); } else if (element is IIs.WebSite) { this.webSites.Add(element); } else if (element is IIs.WebVirtualDir) { this.webVirtualDirs.Add(element); } else if (element is Wix.Directory) { Wix.Directory directory = (Wix.Directory)element; if (null != directory.Id && null != directory.FileSource) { this.directoryPaths.Add(directory.FileSource, directory.Id); } } else if (element is Wix.File) { Wix.File file = (Wix.File)element; if (null != file.Id && null != file.Source) { this.filePaths[file.Source] = String.Concat("[#", file.Id, "]"); } } // index the child elements if (element is Wix.IParentElement) { foreach (Wix.ISchemaElement childElement in ((Wix.IParentElement)element).Children) { this.IndexElement(childElement); } } }
/// <summary> /// Callback for scraping the file system. /// </summary> /// <param name="obj">The path to scrape.</param> private void GetDirectoryTreeCallback(object obj) { string path = obj as string; Debug.Assert(path != null); // disable UI // this.Invoke(new MethodInvoker(this.fabricator.DisableUI)); // scrape Wix.Directory directory = this.fabricator.GetApplicationRootDirectory(); // prepare tree view for inserting data this.Invoke(new MethodInvoker(this.PrepareUI)); // insert data this.AddDirectory(this.treeView.Nodes, path, directory, directory, true); // end data insertion and enable UI this.Invoke(new MethodInvoker(this.EnableUI)); }
/// <summary> /// Callback for scraping the file system. /// </summary> /// <param name="obj">The path to scrape.</param> private void ScrapeFileSystemCallback(object obj) { string path = obj as string; Debug.Assert(path != null); // disable UI this.Invoke(new MethodInvoker(this.DisableUI)); // scrape this.packageBuilder.ApplicationRoot = path; Wix.Directory directory = this.packageBuilder.GetApplicationRootDirectory(); // prepare tree view for inserting data this.Invoke(new MethodInvoker(this.PrepareUI)); // insert data this.AddDirectory(this.filesTreeView.Nodes, path, directory, directory, true); // end data insertion and enable UI this.Invoke(new MethodInvoker(this.EnableUI)); }
/// <summary> /// Mutate the WebFilter elements. /// </summary> private void MutateWebFilters() { IdentifierGenerator identifierGenerator = null; if (this.setUniqueIdentifiers) { identifierGenerator = new IdentifierGenerator("WebFilter"); // index all the existing identifiers and names foreach (IIs.WebFilter webFilter in this.webFilters) { if (null != webFilter.Id) { identifierGenerator.IndexExistingIdentifier(webFilter.Id); } else { identifierGenerator.IndexName(webFilter.Name); } } } foreach (IIs.WebFilter webFilter in this.webFilters) { if (this.setUniqueIdentifiers && null == webFilter.Id) { webFilter.Id = identifierGenerator.GetIdentifier(webFilter.Name); } // harvest the file for this WebFilter Wix.Directory directory = this.HarvestUniqueDirectory(Path.GetDirectoryName(webFilter.Path), false); Wix.Component component = new Wix.Component(); directory.AddChild(component); Wix.File file = this.fileHarvester.HarvestFile(webFilter.Path); component.AddChild(file); } }
/// <summary> /// Returns a ComponentRef for each Component in the Directory tree. /// </summary> /// <param name="directory">The root Directory of the components.</param> /// <returns>All Components in directory.</returns> private Wix.ComponentRef[] GetComponentRefs(Wix.Directory directory) { ArrayList componentRefs = new ArrayList(); foreach (Wix.ISchemaElement element in directory.Children) { if (element is Wix.Component) { Wix.Component component = (Wix.Component)element; Wix.ComponentRef componentRef = new Wix.ComponentRef(); componentRef.Id = component.Id; componentRefs.Add(componentRef); } else if (element is Wix.Directory) { componentRefs.AddRange(this.GetComponentRefs((Wix.Directory)element)); } } return((Wix.ComponentRef[])componentRefs.ToArray(typeof(Wix.ComponentRef))); }
/// <summary> /// Harvest a performance category. /// </summary> /// <param name="argument">The name of the performance category.</param> /// <returns>A harvested performance category.</returns> public override Wix.Fragment[] Harvest(string argument) { if (null == argument) { throw new ArgumentNullException("argument"); } Util.PerformanceCategory perf = this.HarvestPerformanceCategory(argument); Wix.Component component = new Wix.Component(); component.Id = this.Core.CreateIdentifierFromFilename(argument); component.KeyPath = Wix.YesNoType.yes; component.AddChild(perf); Wix.Directory directory = new Wix.Directory(); directory.Id = "TARGETDIR"; //directory.Name = directory.Id; directory.AddChild(component); Wix.Fragment fragment = new Wix.Fragment(); fragment.AddChild(directory); return(new Wix.Fragment[] { fragment }); }
/// <summary> /// Mutate the components. /// </summary> private void MutateComponents() { IdentifierGenerator identifierGenerator = new IdentifierGenerator("Component"); if (TemplateType.Module == this.templateType) { identifierGenerator.MaxIdentifierLength = IdentifierGenerator.MaxModuleIdentifierLength; } foreach (Wix.Component component in this.components) { if (null == component.Id) { string firstFileId = string.Empty; // attempt to create a possible identifier from the first file identifier in the component foreach (Wix.File file in component[typeof(Wix.File)]) { firstFileId = file.Id; break; } if (string.IsNullOrEmpty(firstFileId)) { firstFileId = GetGuid(); } component.Id = identifierGenerator.GetIdentifier(firstFileId); } if (null == component.Guid) { if (this.AutogenerateGuids) { component.Guid = "*"; } else { component.Guid = this.GetGuid(); } } if (this.createFragments && component.ParentElement is Wix.Directory) { Wix.Directory directory = (Wix.Directory)component.ParentElement; // parent directory must have an identifier to create a reference to it if (null == directory.Id) { break; } if (this.rootElement is Wix.Module) { // add a ComponentRef for the Component Wix.ComponentRef componentRef = new Wix.ComponentRef(); componentRef.Id = component.Id; this.rootElement.AddChild(componentRef); } // create a new Fragment Wix.Fragment fragment = new Wix.Fragment(); this.fragments.Add(String.Concat("Component:", (null != component.Id ? component.Id : this.fragments.Count.ToString())), fragment); // create a new DirectoryRef Wix.DirectoryRef directoryRef = new Wix.DirectoryRef(); directoryRef.Id = directory.Id; fragment.AddChild(directoryRef); // move the Component from the the Directory to the DirectoryRef directory.RemoveChild(component); directoryRef.AddChild(component); } } }
/// <summary> /// Creates a component group with a given name. /// </summary> /// <param name="wix">The Wix document element.</param> private void CreateComponentGroup(Wix.Wix wix) { Wix.ComponentGroup componentGroup = new Wix.ComponentGroup(); componentGroup.Id = this.componentGroupName; this.componentGroups.Add(componentGroup); Wix.Fragment cgFragment = new Wix.Fragment(); cgFragment.AddChild(componentGroup); wix.AddChild(cgFragment); int componentCount = 0; for (; componentCount < this.components.Count; componentCount++) { Wix.Component c = this.components[componentCount] as Wix.Component; if (this.createFragments) { if (c.ParentElement is Wix.Directory) { Wix.Directory parentDirectory = c.ParentElement as Wix.Directory; componentGroup.AddChild(c); c.Directory = parentDirectory.Id; parentDirectory.RemoveChild(c); } else if (c.ParentElement is Wix.DirectoryRef) { Wix.DirectoryRef parentDirectory = c.ParentElement as Wix.DirectoryRef; componentGroup.AddChild(c); c.Directory = parentDirectory.Id; parentDirectory.RemoveChild(c); // Remove whole fragment if moving the component to the component group just leaves an empty DirectoryRef if (0 < fragments.Count && parentDirectory.ParentElement is Wix.Fragment) { Wix.Fragment parentFragment = parentDirectory.ParentElement as Wix.Fragment; int childCount = 0; foreach (Wix.ISchemaElement element in parentFragment.Children) { childCount++; } // Component should always have an Id but the SortedList creation allows for null and bases the name on the fragment count which we cannot reverse engineer here. if (1 == childCount && !String.IsNullOrEmpty(c.Id)) { int removeIndex = fragments.IndexOfKey(String.Concat("Component:", c.Id)); if (0 <= removeIndex) { fragments.RemoveAt(removeIndex); } } } } } else { Wix.ComponentRef componentRef = new Wix.ComponentRef(); componentRef.Id = c.Id; componentGroup.AddChild(componentRef); } } }
/// <summary> /// Builds a setup package to the specified output path. /// </summary> /// <param name="outputPath">Location to build the setup package to.</param> /// <param name="outputSourcePath">Optional path where the package's .wxs file will be written.</param> public bool Build(string outputPath, string outputSourcePath) { this.buildError = null; // clear out any previous errors int currentProgress = 0; int totalProgress = 7; // calculate the upper progress if (outputSourcePath != null) { ++totalProgress; } if (this.previousPackagePath != null) { ++totalProgress; } this.VerifyRequiredInformation(); if (!this.OnProgress(currentProgress++, totalProgress, "Initialized package builder...")) { return(false); } // Calculate where everything is going string localSetupExe = outputPath; string localSetupFeed = Path.Combine(Path.GetDirectoryName(outputPath), Path.GetFileName(this.updateUrl.AbsolutePath)); Uri urlSetupExe = new Uri(this.updateUrl, Path.GetFileName(localSetupExe)); Uri urlSetupFeed = new Uri(this.updateUrl, Path.GetFileName(localSetupFeed)); Guid previousUpgradeCode = Guid.Empty; Version previousVersion = null; Uri previousSetupFeed = null; // if a previous package was provided, go read the key information out of it now if (this.previousPackagePath != null) { if (!this.OnProgress(currentProgress++, totalProgress, "Reading previous package...")) { return(false); } this.ReadPreviousPackage(this.previousPackagePath, out previousUpgradeCode, out previousVersion, out previousSetupFeed); } // // if a upgrade code and/or version has not been specified use one // from the previous package or create new. // if (this.upgradeCode == Guid.Empty) { if (previousUpgradeCode == Guid.Empty) { this.upgradeCode = Guid.NewGuid(); } else { this.upgradeCode = previousUpgradeCode; } } if (this.version == null) { if (previousVersion == null) { FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(Path.Combine(this.applicationRoot.Content, this.applicationEntry.Content)); this.version = new Version(fileVersionInfo.FileVersion); } else { this.version = previousVersion; } } // verify that new data is okay when compared to previous package if (previousUpgradeCode != Guid.Empty && previousUpgradeCode != this.upgradeCode) { this.OnMessage(ClickThroughErrors.UpgradeCodeChanged(previousUpgradeCode, this.upgradeCode)); } if (previousVersion != null && previousVersion >= this.version) { this.OnMessage(ClickThroughErrors.NewVersionIsNotGreater(previousVersion, this.version)); } if (this.buildError != null) { throw new InvalidOperationException(String.Format(this.buildError.ResourceManager.GetString(this.buildError.ResourceName), this.buildError.MessageArgs)); } else if (!this.OnProgress(currentProgress++, totalProgress, "Processing package information...")) { return(false); } // Product information Application application = new Application(); application.Product.Id = Guid.NewGuid().ToString(); application.Product.Language = "1033"; application.Product.Manufacturer = this.manufacturerName.Content; application.Product.Name = this.applicationName.Content; application.Package.Description = this.description.Content; application.Product.UpgradeCode = this.upgradeCode.ToString(); application.Product.Version = this.version.ToString(); Wix.WixVariable variable = new Wix.WixVariable(); variable = new Wix.WixVariable(); variable.Id = "ProductName"; variable.Value = application.Product.Name; application.Product.AddChild(variable); variable = new Wix.WixVariable(); variable.Id = "ProductCode"; variable.Value = application.Product.Id; application.Product.AddChild(variable); variable = new Wix.WixVariable(); variable.Id = "ProductVersion"; variable.Value = application.Product.Version; application.Product.AddChild(variable); variable = new Wix.WixVariable(); variable.Id = "ShortcutFileId"; variable.Value = "todoFileIdHere"; application.Product.AddChild(variable); // Upgrade logic Wix.Upgrade upgrade = new Wix.Upgrade(); upgrade.Id = application.Product.UpgradeCode; application.Product.AddChild(upgrade); Wix.UpgradeVersion minUpgrade = new Wix.UpgradeVersion(); minUpgrade.Minimum = application.Product.Version; minUpgrade.OnlyDetect = Wix.YesNoType.yes; minUpgrade.Property = "NEWERVERSIONDETECTED"; upgrade.AddChild(minUpgrade); Wix.UpgradeVersion maxUpgrade = new Wix.UpgradeVersion(); maxUpgrade.Maximum = application.Product.Version; maxUpgrade.IncludeMaximum = Wix.YesNoType.no; maxUpgrade.Property = "OLDERVERSIONBEINGUPGRADED"; upgrade.AddChild(maxUpgrade); // Update Feed Wix.Property property = new Wix.Property(); property.Id = "ARPURLUPDATEINFO"; property.Value = urlSetupFeed.AbsoluteUri; application.Product.AddChild(property); #if false // Directory tree Wix.DirectoryRef applicationCacheRef = new Wix.DirectoryRef(); applicationCacheRef.Id = "ApplicationsCacheFolder"; application.Product.AddChild(applicationCacheRef); #endif Wix.DirectoryRef directoryRef = new Wix.DirectoryRef(); directoryRef.Id = "ApplicationsFolder"; application.Product.AddChild(directoryRef); this.applicationRootDirectory.Name = String.Concat(application.Product.UpgradeCode, "v", application.Product.Version); directoryRef.AddChild(this.applicationRootDirectory); #if false // System registry keys Wix.Component registryComponent = new Wix.Component(); registryComponent.Id = "SystemVersionRegistryKeyComponent"; registryComponent.Guid = Guid.NewGuid().ToString(); directoryRef.AddChild(registryComponent); Wix.Registry productRegKey = new Wix.Registry(); productRegKey.Root = Wix.RegistryRootType.HKCU; productRegKey.Key = @"Software\WiX\ClickThrough\Applications\[UpgradeCode]"; productRegKey.Action = Wix.Registry.ActionType.createKeyAndRemoveKeyOnUninstall; registryComponent.AddChild(productRegKey); Wix.Registry versionRegKey = new Wix.Registry(); versionRegKey.Name = "Version"; versionRegKey.Type = Wix.Registry.TypeType.@string; versionRegKey.Value = "[ProductVersion]"; productRegKey.AddChild(versionRegKey); Wix.Registry sourceRegKey = new Wix.Registry(); sourceRegKey.Name = "UpdateInfoSource"; sourceRegKey.Type = Wix.Registry.TypeType.@string; sourceRegKey.Value = "[ARPURLUPDATEINFO]"; productRegKey.AddChild(sourceRegKey); // Shortcut Wix.DirectoryRef programMenuRef = new Wix.DirectoryRef(); programMenuRef.Id = "ProgramMenuFolder"; Wix.Directory shortcutsDirectory = new Wix.Directory(); shortcutsDirectory.Id = "ThisAppShortcuts"; shortcutsDirectory.LongName = application.Product.Name; shortcutsDirectory.Name = "AppSCDir"; programMenuRef.AddChild(shortcutsDirectory); application.Product.AddChild(programMenuRef); Wix.Component shortcutsComponent = new Wix.Component(); shortcutsComponent.Id = "ThisApplicationShortcutComponent"; shortcutsComponent.Guid = Guid.NewGuid().ToString(); shortcutsComponent.KeyPath = Wix.YesNoType.yes; shortcutsDirectory.AddChild(shortcutsComponent); Wix.CreateFolder shortcutsCreateFolder = new Wix.CreateFolder(); shortcutsComponent.AddChild(shortcutsCreateFolder); Wix.Shortcut shortcut = this.GetShortcut(this.applicationEntry.Content, rootDirectory, shortcutsDirectory); shortcutsComponent.AddChild(shortcut); // Remove cached MSI file. Wix.Component removeComponent = new Wix.Component(); removeComponent.Id = "ThisApplicationRemoveComponent"; removeComponent.Guid = Guid.NewGuid().ToString(); removeComponent.KeyPath = Wix.YesNoType.yes; applicationCacheRef.AddChild(removeComponent); Wix.RemoveFile cacheRemoveFile = new Wix.RemoveFile(); cacheRemoveFile.Id = "ThisApplicationRemoveCachedMsi"; cacheRemoveFile.Directory = "ApplicationsCacheFolder"; cacheRemoveFile.Name = "unknown.msi"; cacheRemoveFile.LongName = String.Concat("{", application.Product.Id.ToUpper(CultureInfo.InvariantCulture), "}v", application.Version.ToString(), ".msi"); cacheRemoveFile.On = Wix.RemoveFile.OnType.uninstall; removeComponent.AddChild(cacheRemoveFile); Wix.RemoveFile cacheRemoveFolder = new Wix.RemoveFile(); cacheRemoveFolder.Id = "ThisApplicationRemoveCacheFolder"; cacheRemoveFolder.Directory = "ApplicationsCacheFolder"; cacheRemoveFolder.On = Wix.RemoveFile.OnType.uninstall; removeComponent.AddChild(cacheRemoveFolder); Wix.RemoveFile applicationRemoveFolder = new Wix.RemoveFile(); applicationRemoveFolder.Id = "ThisApplicationRemoveApplicationsFolder"; applicationRemoveFolder.Directory = "ApplicationsFolder"; applicationRemoveFolder.On = Wix.RemoveFile.OnType.uninstall; removeComponent.AddChild(applicationRemoveFolder); #endif // Feature tree Wix.FeatureRef applicationFeatureRef = new Wix.FeatureRef(); applicationFeatureRef.Id = "ApplicationFeature"; application.Product.AddChild(applicationFeatureRef); #if false Wix.Feature applicationFeature = new Wix.Feature(); applicationFeature.Id = "ApplicationFeature"; applicationFeature.Display = "expand"; applicationFeature.Level = 1; applicationFeature.Absent = Wix.Feature.AbsentType.disallow; applicationFeature.AllowAdvertise = Wix.Feature.AllowAdvertiseType.yes; applicationFeature.InstallDefault = Wix.Feature.InstallDefaultType.local; applicationFeature.TypicalDefault = Wix.Feature.TypicalDefaultType.install; application.Product.AddChild(applicationFeature); Wix.ComponentRef shortcutsComponentRef = new Wix.ComponentRef(); shortcutsComponentRef.Id = shortcutsComponent.Id; applicationFeature.AddChild(shortcutsComponentRef); Wix.ComponentRef removeComponentRef = new Wix.ComponentRef(); removeComponentRef.Id = removeComponent.Id; applicationFeature.AddChild(removeComponentRef); #endif Wix.ComponentRef[] componentRefs = this.GetComponentRefs(this.applicationRootDirectory); foreach (Wix.ComponentRef componentRef in componentRefs) { applicationFeatureRef.AddChild(componentRef); } if (!this.OnProgress(currentProgress++, totalProgress, "Serializing package information into XML...")) { return(false); } // serialize to an xml string string xml; using (StringWriter sw = new StringWriter()) { XmlTextWriter writer = null; try { writer = new XmlTextWriter(sw); application.WixRoot.OutputXml(writer); xml = sw.ToString(); } finally { if (writer != null) { writer.Close(); } } } // load the xml into a document XmlDocument sourceDoc = new XmlDocument(); sourceDoc.LoadXml(xml); if (outputSourcePath != null) { if (!this.OnProgress(currentProgress++, totalProgress, "Saving .wxs file...")) { return(false); } sourceDoc.Save(outputSourcePath); } // generate the MSI, create the setup.exe, and generate the RSS feed. string outputMsi = null; try { outputMsi = Path.GetTempFileName(); if (!this.OnProgress(currentProgress++, totalProgress, "Generating .msi file...")) { return(false); } this.GenerateMsi(sourceDoc, outputMsi); if (this.buildError != null) { throw new InvalidOperationException(String.Format(this.buildError.ResourceManager.GetString(this.buildError.ResourceName), this.buildError.MessageArgs)); } string assemblyPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); if (!this.OnProgress(currentProgress++, totalProgress, "Generating setup bootstrapper...")) { return(false); } /* * NativeMethods.CREATE_SETUP_PACKAGE[] createSetup = new WixToolset.ClickThrough.NativeMethods.CREATE_SETUP_PACKAGE[1]; * createSetup[0].fPrivileged = false; * createSetup[0].fCache = true; * createSetup[0].wzSourcePath = outputMsi; * * int hr = NativeMethods.CreateSetup(Path.Combine(assemblyPath, "setup.exe"), createSetup, createSetup.Length, localSetupExe); */ int hr = NativeMethods.CreateSimpleSetup(Path.Combine(assemblyPath, "setup.exe"), outputMsi, localSetupExe); if (hr != 0) { this.OnMessage(ClickThroughErrors.FailedSetupExeCreation(Path.Combine(assemblyPath, "setup.exe"), localSetupExe)); } if (!this.OnProgress(currentProgress++, totalProgress, "Generating update feed...")) { return(false); } this.GenerateRssFeed(localSetupFeed, localSetupExe, urlSetupExe, application.Product.Id, application.Product.UpgradeCode, application.Product.Version); } finally { this.OnProgress(currentProgress++, totalProgress, "Cleaning up..."); if (outputMsi != null) { File.Delete(outputMsi); } } if (this.buildError != null) { throw new InvalidOperationException(String.Format(this.buildError.ResourceManager.GetString(this.buildError.ResourceName), this.buildError.MessageArgs)); } else if (!this.OnProgress(currentProgress++, totalProgress, "Package build complete.")) { return(false); } return(true); }
/// <summary> /// Mutate the directories. /// </summary> private void MutateDirectories() { if (!this.setUniqueIdentifiers) { // assign all identifiers before fragmenting (because fragmenting requires them all to be present) IdentifierGenerator identifierGenerator = new IdentifierGenerator("Directory"); if (TemplateType.Module == this.templateType) { identifierGenerator.MaxIdentifierLength = IdentifierGenerator.MaxModuleIdentifierLength; } foreach (Wix.Directory directory in this.directories) { if (null == directory.Id) { directory.Id = identifierGenerator.GetIdentifier(directory.Name); } } } if (this.createFragments) { foreach (Wix.Directory directory in this.directories) { if (directory.ParentElement is Wix.Directory) { Wix.Directory parentDirectory = (Wix.Directory)directory.ParentElement; // parent directory must have an identifier to create a reference to it if (null == parentDirectory.Id) { return; } // create a new Fragment Wix.Fragment fragment = new Wix.Fragment(); this.fragments.Add(String.Concat("Directory:", ("TARGETDIR" == directory.Id ? null : (null != directory.Id ? directory.Id : this.fragments.Count.ToString()))), fragment); // create a new DirectoryRef Wix.DirectoryRef directoryRef = new Wix.DirectoryRef(); directoryRef.Id = parentDirectory.Id; fragment.AddChild(directoryRef); // move the Directory from the parent Directory to DirectoryRef parentDirectory.RemoveChild(directory); directoryRef.AddChild(directory); } else if (directory.ParentElement is Wix.Fragment) { // When creating fragments, remove any top-level Directory elements; // the fragments should be pulled in by their DirectoryRefs instead. Wix.Fragment parent = (Wix.Fragment)directory.ParentElement; parent.RemoveChild(directory); // Remove the fragment if it is empty. if (parent.Children.GetEnumerator().Current == null && parent.ParentElement != null) { ((Wix.IParentElement)parent.ParentElement).RemoveChild(parent); } } else if (directory.ParentElement == this.rootElement) { // create a new Fragment Wix.Fragment fragment = new Wix.Fragment(); this.fragments.Add(String.Concat("Directory:", ("TARGETDIR" == directory.Id ? null : (null != directory.Id ? directory.Id : this.fragments.Count.ToString()))), fragment); // move the Directory from the root element to the Fragment this.rootElement.RemoveChild(directory); fragment.AddChild(directory); } } } }
/// <summary> /// Harvest a directory. /// </summary> /// <param name="path">The path of the directory.</param> /// <param name="relativePath">The relative path that will be used when harvesting.</param> /// <param name="directory">The directory for this path.</param> /// <returns>The number of files harvested.</returns> private int HarvestDirectory(string path, string relativePath, Wix.Directory directory) { int fileCount = 0; // harvest the child directories foreach (string childDirectoryPath in Directory.GetDirectories(path)) { Wix.Directory childDirectory = new Wix.Directory(); childDirectory.Name = Path.GetFileName(childDirectoryPath); childDirectory.FileSource = childDirectoryPath; if (this.setUniqueIdentifiers) { childDirectory.Id = this.Core.GenerateIdentifier(DirectoryPrefix, directory.Id, childDirectory.Name); } int childFileCount = this.HarvestDirectory(childDirectoryPath, String.Concat(relativePath, childDirectory.Name, "\\"), childDirectory); // keep the directory if it contained any files (or empty directories are being kept) if (0 < childFileCount || this.keepEmptyDirectories) { directory.AddChild(childDirectory); } fileCount += childFileCount; } // harvest the files string[] files = Directory.GetFiles(path); if (0 < files.Length) { foreach (string filePath in Directory.GetFiles(path)) { string fileName = Path.GetFileName(filePath); Wix.Component component = new Wix.Component(); Wix.File file = this.fileHarvester.HarvestFile(filePath); file.Source = String.Concat(relativePath, fileName); if (this.setUniqueIdentifiers) { file.Id = this.Core.GenerateIdentifier(FilePrefix, directory.Id, fileName); component.Id = this.Core.GenerateIdentifier(ComponentPrefix, directory.Id, file.Id); } component.AddChild(file); directory.AddChild(component); } } else if (0 == fileCount && this.keepEmptyDirectories) { Wix.Component component = new Wix.Component(); component.KeyPath = Wix.YesNoType.yes; if (this.setUniqueIdentifiers) { component.Id = this.Core.GenerateIdentifier(ComponentPrefix, directory.Id); } Wix.CreateFolder createFolder = new Wix.CreateFolder(); component.AddChild(createFolder); directory.AddChild(component); } return(fileCount + files.Length); }
/// <summary> /// Converts a Module to a ComponentGroup and adds all of its relevant elements to the main fragment. /// </summary> /// <param name="wix">The output object representing an unbound merge module.</param> private void ConvertModule(Wix.Wix wix) { Wix.Product product = Melter.GetProduct(wix); List <string> customActionsRemoved = new List <string>(); Dictionary <Wix.Custom, Wix.InstallExecuteSequence> customsToRemove = new Dictionary <Wix.Custom, Wix.InstallExecuteSequence>(); foreach (Wix.ISchemaElement child in product.Children) { Wix.Directory childDir = child as Wix.Directory; if (null != childDir) { bool isTargetDir = this.WalkDirectory(childDir); if (isTargetDir) { continue; } } else { Wix.Dependency childDep = child as Wix.Dependency; if (null != childDep) { this.AddPropertyRef(childDep.RequiredId); continue; } else if (child is Wix.Package) { continue; } else if (child is Wix.CustomAction) { Wix.CustomAction customAction = child as Wix.CustomAction; string directoryId; if (StartsWithStandardDirectoryId(customAction.Id, out directoryId) && customAction.Property == customAction.Id) { customActionsRemoved.Add(customAction.Id); continue; } } else if (child is Wix.InstallExecuteSequence) { Wix.InstallExecuteSequence installExecuteSequence = child as Wix.InstallExecuteSequence; foreach (Wix.ISchemaElement sequenceChild in installExecuteSequence.Children) { Wix.Custom custom = sequenceChild as Wix.Custom; string directoryId; if (custom != null && StartsWithStandardDirectoryId(custom.Action, out directoryId)) { customsToRemove.Add(custom, installExecuteSequence); } } } } this.fragment.AddChild(child); } // For any customaction that we removed, also remove the scheduling of that action. foreach (Wix.Custom custom in customsToRemove.Keys) { if (customActionsRemoved.Contains(custom.Action)) { ((Wix.InstallExecuteSequence)customsToRemove[custom]).RemoveChild(custom); } } AddProperty(this.moduleId, this.id); wix.RemoveChild(product); wix.AddChild(this.fragment); this.fragment.AddChild(this.componentGroup); this.fragment.AddChild(this.primaryDirectoryRef); }
/// <summary> /// Mutate a Wix element. /// </summary> /// <param name="wix">The Wix element to mutate.</param> private void MutateWix(Wix.Wix wix) { if (TemplateType.Fragment != this.templateType) { if (null != this.rootElement || 0 != this.features.Count) { throw new Exception("The template option cannot be used with Feature, Product, or Module elements present."); } // create a package element although it won't always be used Wix.Package package = new Wix.Package(); if (TemplateType.Module == this.templateType) { package.Id = this.GetGuid(); } else { package.Compressed = Wix.YesNoType.yes; } package.InstallerVersion = 200; Wix.Directory targetDir = new Wix.Directory(); targetDir.Id = "TARGETDIR"; targetDir.Name = "SourceDir"; foreach (Wix.DirectoryRef directoryRef in this.directoryRefs) { if (String.Equals(directoryRef.Id, "TARGETDIR", StringComparison.OrdinalIgnoreCase)) { Wix.IParentElement parent = directoryRef.ParentElement as Wix.IParentElement; foreach (Wix.ISchemaElement element in directoryRef.Children) { targetDir.AddChild(element); } parent.RemoveChild(directoryRef); if (null != ((Wix.ISchemaElement)parent).ParentElement) { int i = 0; foreach (Wix.ISchemaElement element in parent.Children) { i++; } if (0 == i) { Wix.IParentElement supParent = (Wix.IParentElement)((Wix.ISchemaElement)parent).ParentElement; supParent.RemoveChild((Wix.ISchemaElement)parent); } } break; } } if (TemplateType.Module == this.templateType) { Wix.Module module = new Wix.Module(); module.Id = "PUT-MODULE-NAME-HERE"; module.Language = "1033"; module.Version = "1.0.0.0"; package.Manufacturer = "PUT-COMPANY-NAME-HERE"; module.AddChild(package); module.AddChild(targetDir); wix.AddChild(module); this.rootElement = module; } else // product { Wix.Product product = new Wix.Product(); product.Id = this.GetGuid(); product.Language = "1033"; product.Manufacturer = "PUT-COMPANY-NAME-HERE"; product.Name = "PUT-PRODUCT-NAME-HERE"; product.UpgradeCode = this.GetGuid(); product.Version = "1.0.0.0"; product.AddChild(package); product.AddChild(targetDir); Wix.Media media = new Wix.Media(); media.Id = "1"; media.Cabinet = "product.cab"; media.EmbedCab = Wix.YesNoType.yes; product.AddChild(media); Wix.Feature feature = new Wix.Feature(); feature.Id = "ProductFeature"; feature.Title = "PUT-FEATURE-TITLE-HERE"; feature.Level = 1; product.AddChild(feature); this.features.Add(feature); wix.AddChild(product); this.rootElement = product; } } }
/// <summary> /// Returns a Shortcut for each Component in the Directory tree. /// </summary> /// <param name="">The root Directory of the components.</param> private Wix.Shortcut GetShortcut(string relativePath, Wix.Directory directory, Wix.Directory shortcutDirectory) { Wix.Shortcut shortcut = null; IEnumerable enumerable = directory.Children; string[] dir = relativePath.Split(Path.DirectorySeparatorChar); for (int i = 0; i < dir.Length; ++i) { bool found = false; if (i < dir.Length - 1) { foreach (Wix.ISchemaElement element in enumerable) { if (element is Wix.Directory) { Wix.Directory dirx = (Wix.Directory)element; if (dir[i] == dirx.LongName) { enumerable = dirx.Children; found = true; break; } } } } else { foreach (Wix.ISchemaElement element in enumerable) { if (element is Wix.Component) { enumerable = ((Wix.Component)element).Children; foreach (Wix.ISchemaElement elementx in enumerable) { if (elementx is Wix.File) { Wix.File fil = (Wix.File)elementx; if (dir[i] == fil.LongName) { shortcut = new Wix.Shortcut(); shortcut.Id = String.Concat(fil.Id, "Shortcut"); shortcut.Directory = shortcutDirectory.Id; shortcut.Target = "[!SystemApplicationUpdateExeFile]"; shortcut.Name = "shortcu1"; shortcut.LongName = Path.GetFileNameWithoutExtension(fil.LongName); shortcut.Arguments = String.Format(CultureInfo.InvariantCulture, "-ac [UpgradeCode] -cl \"[#{0}]\"", fil.Id); found = true; break; } } } } if (found) { break; } } } if (!found) { throw new ApplicationException("did not find file name"); } } return(shortcut); }