public void TestReplaceIconResource() { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string icon1filename = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Icons\\Icon1.ico"); Assert.IsTrue(File.Exists(icon1filename)); IconFile iconFile = new IconFile(icon1filename); Console.WriteLine("{0}: {1}", Path.GetFileName(icon1filename), iconFile.Type); foreach (IconFileIcon icon in iconFile.Icons) { Console.WriteLine(" {0}", icon.ToString()); } Console.WriteLine("Converted IconDirectoryResource:"); IconDirectoryResource iconDirectoryResource = new IconDirectoryResource(iconFile); iconDirectoryResource.Language = ResourceUtil.USENGLISHLANGID; DumpResource.Dump(iconDirectoryResource); Assert.AreEqual(iconFile.Icons.Count, iconDirectoryResource.Icons.Count); string filename = Path.Combine(Environment.SystemDirectory, "write.exe"); Assert.IsTrue(File.Exists(filename)); string targetFilename = Path.Combine(Path.GetTempPath(), "write.exe"); File.Copy(filename, targetFilename, true); Console.WriteLine(targetFilename); iconDirectoryResource.SaveTo(targetFilename); Console.WriteLine("Written IconDirectoryResource:"); IconDirectoryResource newIconDirectoryResource = new IconDirectoryResource(); newIconDirectoryResource.LoadFrom(targetFilename); DumpResource.Dump(newIconDirectoryResource); }
public void TestLoadAndSaveIconResource() { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string icon1filename = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Icons\\Icon1.ico"); Assert.IsTrue(File.Exists(icon1filename)); IconFile iconFile = new IconFile(icon1filename); Console.WriteLine("{0}: {1}", Path.GetFileName(icon1filename), iconFile.Type); foreach (IconFileIcon icon in iconFile.Icons) { Console.WriteLine(" {0}", icon.ToString()); } Console.WriteLine("Converted IconDirectoryResource:"); IconDirectoryResource iconDirectoryResource = new IconDirectoryResource(iconFile); DumpResource.Dump(iconDirectoryResource); Assert.AreEqual(iconFile.Icons.Count, iconDirectoryResource.Icons.Count); string filename = HttpUtility.UrlDecode(uri.AbsolutePath); Assert.IsTrue(File.Exists(filename)); string targetFilename = Path.Combine(Path.GetTempPath(), "testLoadAndSaveIconResource.exe"); File.Copy(filename, targetFilename, true); Console.WriteLine(targetFilename); iconDirectoryResource.SaveTo(targetFilename); Console.WriteLine("Written IconDirectoryResource:"); IconDirectoryResource newIconDirectoryResource = new IconDirectoryResource(); newIconDirectoryResource.LoadFrom(targetFilename); DumpResource.Dump(newIconDirectoryResource); }
// ----------------------------------------------------- void ReplaceIcon(Options options) { // Find version info resources ResourceInfo ri = new ResourceInfo(); ri.Load(options.outputExeFile); List <Resource> iconResources = ri.Resources[new ResourceId(Kernel32.ResourceTypes.RT_ICON)]; List <Resource> iconGroupResources = ri.Resources[new ResourceId(Kernel32.ResourceTypes.RT_GROUP_ICON)]; ri.Dispose(); // Delete old icons from file foreach (Resource resource in iconResources) { resource.DeleteFrom(options.outputExeFile); } // Delete old icon groups from file foreach (Resource resource in iconGroupResources) { resource.DeleteFrom(options.outputExeFile); } // Add the new icon and iconGroup IconFile iconFile = new IconFile(options.inputIcoFile); IconDirectoryResource iconDirectoryResource = new IconDirectoryResource(iconFile); iconDirectoryResource.SaveTo(options.outputExeFile); }
/// <summary> /// Attempts to duplicate the icon from another file. /// </summary> /// <param name="target"></param> /// <param name="iconsource"></param> public static void CopyIcon(this FileInfo target, FileInfo iconsource) { if (File.Exists(target.FullName) == false) { throw new FileNotFoundException("Couldnt find the given file", target.FullName); } if (File.Exists(iconsource.FullName) == false) { throw new FileNotFoundException("Couldnt find the given file", iconsource.FullName); } var idr = new IconDirectoryResource(); try { idr.LoadFrom(iconsource.FullName); } catch { CopyResources(target, iconsource); return; } try { idr.SaveTo(target.FullName); } catch { var icon = idr.Icons.OrderByDescending(ico => ico.Height * ico.Width).First(); icon.SaveTo(target.FullName); } }
public static void Dump(IconDirectoryResource rc) { Console.WriteLine(" IconDirectoryResource: {0}, {1}", rc.Name, rc.TypeName); foreach (IconResource icon in rc.Icons) { Dump(icon); } }
public void TestLoadIconResources() { string filename = Path.Combine(Environment.SystemDirectory, "regedt32.exe"); Assert.IsTrue(File.Exists(filename)); IconDirectoryResource iconDirectoryResource = new IconDirectoryResource(); iconDirectoryResource.LoadFrom(filename); DumpResource.Dump(iconDirectoryResource); }
private static void CheckIconIds(IconDirectoryResource iconDirectoryResource) { Assert.IsTrue(iconDirectoryResource.Icons.Count > 0); for (var i = 0; i < iconDirectoryResource.Icons.Count; i++) { var icon = iconDirectoryResource.Icons[i]; Assert.AreEqual(i + 1, icon.Id); } }
public bool UpdateImage(string iconPath) { if (!System.IO.File.Exists(iconPath)) return false; IconFile iconFile = new IconFile(iconPath); IconDirectoryResource iconDirectoryResource = new IconDirectoryResource(iconFile); iconDirectoryResource.SaveTo(file); return true; }
/// <summary> /// Builds a client executable. /// </summary> public void Build() { using (AssemblyDefinition asmDef = AssemblyDefinition.ReadAssembly(_clientFilePath)) { // PHASE 1 - Writing settings WriteSettings(asmDef); // PHASE 2 - Renaming Renamer r = new Renamer(asmDef); if (!r.Perform()) { throw new Exception("renaming failed"); } // PHASE 3 - Saving r.AsmDef.Write(_options.OutputPath); } // PHASE 4 - Assembly Information changing if (_options.AssemblyInformation != null) { VersionResource versionResource = new VersionResource(); versionResource.LoadFrom(_options.OutputPath); versionResource.FileVersion = _options.AssemblyInformation[7]; versionResource.ProductVersion = _options.AssemblyInformation[6]; versionResource.Language = 0; StringFileInfo stringFileInfo = (StringFileInfo)versionResource["StringFileInfo"]; stringFileInfo["CompanyName"] = _options.AssemblyInformation[2]; stringFileInfo["FileDescription"] = _options.AssemblyInformation[1]; stringFileInfo["ProductName"] = _options.AssemblyInformation[0]; stringFileInfo["LegalCopyright"] = _options.AssemblyInformation[3]; stringFileInfo["LegalTrademarks"] = _options.AssemblyInformation[4]; stringFileInfo["ProductVersion"] = versionResource.ProductVersion; stringFileInfo["FileVersion"] = versionResource.FileVersion; stringFileInfo["Assembly Version"] = versionResource.ProductVersion; stringFileInfo["InternalName"] = _options.AssemblyInformation[5]; stringFileInfo["OriginalFilename"] = _options.AssemblyInformation[5]; versionResource.SaveTo(_options.OutputPath); } // PHASE 5 - Icon changing if (!string.IsNullOrEmpty(_options.IconPath)) { IconFile iconFile = new IconFile(_options.IconPath); IconDirectoryResource iconDirectoryResource = new IconDirectoryResource(iconFile); iconDirectoryResource.SaveTo(_options.OutputPath); } }
public static void SetExeResourceInfo(string fullPathToExe, ExeResInfo i) { VersionResource versionResource = new VersionResource(); versionResource.Language = 1043; versionResource.LoadFrom(fullPathToExe); versionResource.FileVersion = i.ExeVersion.ToString(); versionResource.ProductVersion = i.ExeVersion.ToString(); StringFileInfo stringFileInfo = (StringFileInfo)versionResource["StringFileInfo"]; stringFileInfo["CompanyName"] = n(i.Company); stringFileInfo["ProductName"] = n(i.Product); stringFileInfo["LegalCopyright"] = n(i.Copyright); stringFileInfo["ProductVersion"] = n(versionResource.ProductVersion); stringFileInfo["FileDescription"] = n(i.Description); stringFileInfo["Comments"] = n("Powered by GMPrikol."); versionResource.SaveTo(fullPathToExe); IconDirectoryResource rc = new IconDirectoryResource(); rc.Name = new ResourceId("MAINICON"); rc.Language = 1043; rc.LoadFrom(fullPathToExe); string AppDir = AppDomain.CurrentDomain.BaseDirectory; string Ico = Path.Combine(AppDir, "temp.ico"); File.WriteAllBytes(Ico, i.FileIcon); IconFile iconfile = new IconFile(Ico); File.Delete(Ico); IconDirectoryResource iconDirectoryResource = new IconDirectoryResource(iconfile); rc.Icons.Clear(); foreach (var ii in iconDirectoryResource.Icons) { rc.Icons.Add(ii); } rc.SaveTo(fullPathToExe); }
/// <summary> /// Attempts to duplicate the icon from another file. /// </summary> /// <param name="target"></param> /// <param name="iconsource"></param> public static void CopyIcon(this FileInfo target, FileInfo iconsource) { if (File.Exists(target.FullName) == false) throw new FileNotFoundException("Couldnt find the given file", target.FullName); if (File.Exists(iconsource.FullName) == false) throw new FileNotFoundException("Couldnt find the given file", iconsource.FullName); var idr = new IconDirectoryResource(); try { idr.LoadFrom(iconsource.FullName); } catch { CopyResources(target, iconsource); return; } try { idr.SaveTo(target.FullName); } catch { var icon = idr.Icons.OrderByDescending(ico => ico.Height * ico.Width).First(); icon.SaveTo(target.FullName); } }
/// <summary> /// Dynamically creates a new FirstStrike.exe if none exists, using the vanilla BF2142 exe file. /// </summary> /// <param name="originalExe">Exe file to base new FirstStrike exe on</param> //[PrincipalPermissionAttribute(SecurityAction.Demand, Role = @"BUILTIN\Administrators")] private void CreateGameExe(string originalExe) { // TODO: Make sure this works with all retail versions (orig, deluxe, digital) // TODO: Make it so new exe is exactly the same size as original. Currently slightly bigger. Is it not overwriting old icons? string exeDirectory = Directory.GetParent(_config.ParentPath).FullName; File.Copy(Path.Combine(exeDirectory, originalExe), Path.Combine(exeDirectory, "FirstStrike.exe")); try { using (ZipFile zip = new ZipFile("exe.data")) { zip["icon.ico"].Extract(Directory.GetCurrentDirectory(), ExtractExistingFileAction.OverwriteSilently); } IconFile icon = new IconFile("icon.ico"); IconDirectoryResource resource = new IconDirectoryResource(icon); resource.Name = new ResourceId(101); for (int i = 0; i < 3; i++) { resource.Icons[i].Id = (ushort)(i + 1); } resource.SaveTo(Path.Combine(exeDirectory, "FirstStrike.exe")); File.Delete("icon.ico"); } catch (FileNotFoundException ex) { MessageBox.Show(this, string.Format("The file {0} is missing. Please find it.", ex.FileName), "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public override void CopyResources(string src, string dest) { ResourceInfo srcInfo = new ResourceInfo(); ResourceInfo dstInfo = new ResourceInfo(); srcInfo.Load(src); dstInfo.Load(dest); Kernel32.ResourceTypes resType = 0; switch (ResourceType) { case ResourceType.Icon: resType = Kernel32.ResourceTypes.RT_GROUP_ICON; break; case ResourceType.Bitmap: resType = Kernel32.ResourceTypes.RT_BITMAP; break; default: Debug.Fail("Unknown resource type"); break; } List <Resource> resourcesToReplace = new List <Resource>(); foreach (Resource res in srcInfo[resType]) { if (Ids == null || Ids.Contains(res.Name.Name)) { // Find matching resource in destination file Resource dstRes = dstInfo[resType].Single(dr => dr.Name.Equals(res.Name)); res.LoadFrom(src); dstRes.LoadFrom(dest); res.Language = dstRes.Language; // Do some checks if (ResourceType == VSIconSwitcher.ResourceType.Icon) { IconDirectoryResource srcIconDirectory = res as IconDirectoryResource; IconDirectoryResource dstIconDirectory = dstRes as IconDirectoryResource; //Debug.Assert(srcIconDirectory.Icons.Count == dstIconDirectory.Icons.Count, "Source/destination icon directory count should match."); } else if (ResourceType == VSIconSwitcher.ResourceType.Bitmap) { BitmapResource srcBitmap = res as BitmapResource; BitmapResource dstBitmap = dstRes as BitmapResource; Debug.Assert(srcBitmap.Bitmap.Header.biHeight == dstBitmap.Bitmap.Header.biHeight, "Source/destination bitmap height dimension should match."); Debug.Assert(srcBitmap.Bitmap.Header.biWidth == dstBitmap.Bitmap.Header.biWidth, "Source/destination bitmap height dimension should match."); } resourcesToReplace.Add(res); } } dstInfo.Unload(); foreach (Resource res in resourcesToReplace) { res.SaveTo(dest); } srcInfo.Unload(); }
private void BtnCreateMod_Click(object sender, EventArgs e) { if (cbCreateSFX.Checked) { saveFileDlg.FilterIndex = 1; } else { saveFileDlg.FilterIndex = 2; } if (saveFileDlg.ShowDialog() != DialogResult.OK) { return; } try { File.Delete(saveFileDlg.FileName); AAPak modpak = new AAPak(saveFileDlg.FileName, false, true); Bitmap customIconImage = null; // First check image we will use (if any) if (useDefaultImage) { MemoryStream iconStream = new MemoryStream(); Properties.Resources.mod_example_icon.Save(iconStream, System.Drawing.Imaging.ImageFormat.Png); /* * if (!modpak.AddFileFromStream(ModPNGImageFileName, iconStream, DateTime.Now, DateTime.Now, false, out _)) * { * MessageBox.Show("Failed to add default icon"); * modpak.ClosePak(); * return; * } */ customIconImage = new Bitmap(Properties.Resources.mod_example_icon.GetThumbnailImage(128, 128, null, new IntPtr())); } else if (NewCustomImage != string.Empty) { FileStream iconStream = File.Open(NewCustomImage, FileMode.Open, FileAccess.Read, FileShare.Read); /* * if ( (Path.GetExtension(NewCustomImage).ToLower() == ".png") && (!modpak.AddFileFromStream(ModPNGImageFileName, iconStream, DateTime.Now, DateTime.Now, false, out _)) ) * { * MessageBox.Show("Failed to add PNG icon"); * modpak.ClosePak(); * return; * } * else * if ((Path.GetExtension(NewCustomImage).ToLower() == ".jpg") && (!modpak.AddFileFromStream(ModJPGImageFileName, iconStream, DateTime.Now, DateTime.Now, false, out _))) * { * MessageBox.Show("Failed to add JPG icon"); * modpak.ClosePak(); * return; * } */ Image img = Image.FromStream(iconStream); customIconImage = new Bitmap(img.GetThumbnailImage(128, 128, null, new IntPtr())); } else if (useOldPNGImage) { var oldpngStream = mainPak.ExportFileAsStream(ModPNGImageFileName); /* * if ((Path.GetExtension(NewCustomImage).ToLower() == ".png") && (!modpak.AddFileFromStream(ModPNGImageFileName, oldpngStream, DateTime.Now, DateTime.Now, false, out _))) * { * MessageBox.Show("Failed to copy PNG icon"); * modpak.ClosePak(); * return; * } */ Image img = Image.FromStream(oldpngStream); customIconImage = new Bitmap(img.GetThumbnailImage(128, 128, null, new IntPtr())); } else if (useOldJPGImage) { var oldjpgStream = mainPak.ExportFileAsStream(ModJPGImageFileName); /* * if ((Path.GetExtension(NewCustomImage).ToLower() == ".png") && (!modpak.AddFileFromStream(ModJPGImageFileName, oldjpgStream, DateTime.Now, DateTime.Now, false, out _))) * { * MessageBox.Show("Failed to copy PNG icon"); * modpak.ClosePak(); * return; * } */ Image img = Image.FromStream(oldjpgStream); customIconImage = new Bitmap(img.GetThumbnailImage(128, 128, null, new IntPtr())); } else { // No image used } if ((cbCreateSFX.Checked) && (customIconImage != null)) { // Create some temp files string tempIconFile = Path.GetTempFileName(); // .GetTempPath() + "aamod_tmp.ico"; string tempEXEFile = Path.GetTempFileName(); // .GetTempPath() + "aamod_tmp.exe"; try { // Very hacky way of adding/editing a icon to the sfx exe to add // Create 64x64 "thumbnail" as icon var pu = GraphicsUnit.Pixel; var cImg = customIconImage.Clone(customIconImage.GetBounds(ref pu), System.Drawing.Imaging.PixelFormat.Format32bppArgb); cImg.SetResolution(72, 72); var tempImg = cImg.GetThumbnailImage(64, 64, null, new IntPtr()); // tempImg.Save(Path.GetTempPath() + "tmp_aamod.bmp"); // Create and Save temporary ico file // Icon ic = ImageToIcon(tempImg); var tempBitmap = new Bitmap(tempImg, new Size(64, 64)); MemoryStream iconStream = SaveAsIconMemoryStream(tempBitmap); // MemoryStream iconStream = new MemoryStream(); // ic.Save(iconStream); FileStream iconStreamFile = File.Create(tempIconFile); iconStream.Position = 0; iconStream.CopyTo(iconStreamFile); iconStreamFile.Close(); // Save temporary exe file MemoryStream exeStream = new MemoryStream(Properties.Resources.AAModSFX); FileStream fs = File.Create(tempEXEFile); exeStream.CopyTo(fs); fs.Close(); exeStream.Close(); // Create IconFile from temporary ico file IconFile icf = new IconFile(tempIconFile); // Delete old Icon resources ResourceInfo vi = new ResourceInfo(); vi.Load(tempEXEFile); foreach (ResourceId id in vi.ResourceTypes) { if (id.ResourceType != Kernel32.ResourceTypes.RT_GROUP_ICON) { continue; } foreach (Resource resource in vi.Resources[id]) { resource.DeleteFrom(tempEXEFile); } } // Add to IconDirectory IconDirectoryResource iconDirectoryResource = new IconDirectoryResource(icf); IconResource icr = new IconResource(); // Save to temporary exe iconDirectoryResource.SaveTo(tempEXEFile); // Read temporary exe back into stream fs = File.OpenRead(tempEXEFile); exeStream = new MemoryStream(); fs.CopyTo(exeStream); // Add modified exe to modpak if (!modpak.AddFileFromStream(SFXInfoFileName, exeStream, DateTime.Now, DateTime.Now, true, out _)) { MessageBox.Show("Failed to add modified SFX executable"); modpak.ClosePak(); return; } } catch (Exception x) { MessageBox.Show("Exception editing icon:\n" + x.Message); modpak.ClosePak(); return; } try { File.Delete(tempEXEFile); } catch { } try { File.Delete(tempIconFile); } catch { } } else // If you want to use the aamod as a SFX, the .exe needs to be the first file in the pak if (cbCreateSFX.Checked) { // This AAModSFX resource is loaded from the RELEASE build of the AAMod project, make sure it's compiled as release first if you made changes to it MemoryStream sfxStream = new MemoryStream(Properties.Resources.AAModSFX); // We will be possibly be editing the icon, so it's a good idea to have some spare space here if (!modpak.AddFileFromStream(SFXInfoFileName, sfxStream, DateTime.Now, DateTime.Now, true, out _)) { MessageBox.Show("Failed to add SFX executable"); modpak.ClosePak(); return; } } var modInfoStream = AAPak.StringToStream(tDescription.Text); if (!modpak.AddFileFromStream(ModInfoFileName, modInfoStream, DateTime.Now, DateTime.Now, false, out _)) { MessageBox.Show("Failed to add description"); modpak.ClosePak(); return; } if (customIconImage != null) { MemoryStream imgStream = new MemoryStream(); customIconImage.Save(imgStream, System.Drawing.Imaging.ImageFormat.Png); if (!modpak.AddFileFromStream(ModPNGImageFileName, imgStream, DateTime.Now, DateTime.Now, false, out _)) { MessageBox.Show("Failed to add icon image"); modpak.ClosePak(); return; } } // Copy all files foreach (var fi in mainPak.files) { if (fi.name.StartsWith(ModFileFolderName)) { continue; } var ms = mainPak.ExportFileAsStream(fi); if (!modpak.AddFileFromStream(fi.name, ms, DateTime.FromFileTimeUtc(fi.createTime), DateTime.FromFileTimeUtc(fi.modifyTime), false, out _)) { MessageBox.Show("Failed to copy \n" + fi.name + "\nAborting !", "Copy Error", MessageBoxButtons.OK, MessageBoxIcon.Error); modpak.ClosePak(); return; } } modpak.ClosePak(); MessageBox.Show("AAMod create completed !", "AAMod Create", MessageBoxButtons.OK, MessageBoxIcon.Information); DialogResult = DialogResult.OK; } catch (Exception x) { MessageBox.Show("Exception: " + x.Message); } }
// Method for injecting icons into a .NET assembly. private void Inject() { // Reset the status on our icons if we're re-injecting. foreach (IconObject io in lvIcons.Objects) { if (io.Status == "Injected") { io.Status = "Idle"; } else if (io.Status == "Warning") { io.Status = "Idle"; } else if (io.Status == "Error") { io.Status = "Idle"; } Invoke(new Action(() => lvIcons.RebuildColumns())); } // Start the injection process. try { // Make sure that our executable file actually exists. string assembly = txtAssemblyPath.Text; if (!File.Exists(assembly)) { throw new FileNotFoundException("The file '" + Path.GetFileName(assembly) + "' doesn't exist!"); } // Create a list for our icons and then verify that they exist. List <string> iconFiles = new List <string>(); foreach (IconObject io in lvIcons.Objects) { iconFiles.Add(io.Path); } VerifyIconFiles(iconFiles); // Allow re-signing of assembly using RSA. string strongNameKeyFile = txtCertificatePath.Text; if (chkResign.Checked) { //Verify that the assembly is signed to begin with. We don't support signing unsigned assemblies, //only re-signing them. if (strongNameKeyFile != null) { using (var stream = new FileStream(assembly, FileMode.Open, FileAccess.Read)) { var signature = new StrongName().StrongHash(stream, StrongName.StrongNameOptions.Signature); if (signature.SignaturePosition == 0 && signature.SignatureLength == 0) { throw new ArgumentException("Assembly is not signed. XInject can only re-sign assemblies."); } } } } // Try and insert the icons into our assembly. ushort iconMaxId = GetMaxIconId(assembly); int groupIconIdCounter = StartID; int errorCount = 0; foreach (string icoFile in iconFiles) { try { groupIconIdCounter++; IconDirectoryResource newIcon = new IconDirectoryResource(new IconFile(icoFile)); newIcon.Name.Id = new IntPtr(groupIconIdCounter); foreach (var icon in newIcon.Icons) { icon.Id = ++iconMaxId; } newIcon.SaveTo(assembly); foreach (IconObject io in lvIcons.Objects) { if (io.Path == icoFile) { io.Status = "Injected"; break; } } Invoke(new Action(() => lvIcons.RebuildColumns())); } catch { foreach (IconObject io in lvIcons.Objects) { if (io.Path == icoFile) { io.Status = "Error"; errorCount++; break; } } Invoke(new Action(() => lvIcons.RebuildColumns())); } } // Re-sign our assembly file. if (chkResign.Checked) { if (strongNameKeyFile != null) { ResignAssembly(assembly, strongNameKeyFile); } } // Cleanup any temp files that may be lying around. foreach (string file in Directory.EnumerateFiles(assembly.Replace(Path.GetFileName(assembly), ""), "*.*", SearchOption.TopDirectoryOnly)) { if (Path.GetExtension(file) == ".tmp") { File.Delete(file); } } // Let the user know we're done inserting our icons. if (errorCount == 0) { MessageBox.Show("XInject has successfully injected the choosen icons!", "XInject", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("XInject has finished working but some icons could not be injected!", "XInject", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } catch (Exception ex) { MessageBox.Show(ex.Message, "XInject", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public static void CreateInstaller(InstallerLinkerArguments args) { args.Validate(); args.WriteLine(string.Format("Creating \"{0}\" from \"{1}\"", args.output, args.template)); System.IO.File.Copy(args.template, args.output, true); System.IO.File.SetAttributes(args.output, System.IO.FileAttributes.Normal); string configFilename = args.config; #region Version Information ConfigFile configfile = new ConfigFile(); configfile.Load(configFilename); // \todo: check XML with XSD, warn if nodes are being dropped // filter the configuration string configTemp = null; if (!string.IsNullOrEmpty(args.processorArchitecture)) { int configurationCount = configfile.ConfigurationCount; int componentCount = configfile.ComponentCount; args.WriteLine(string.Format("Applying processor architecture filter \"{0}\"", args.processorArchitecture)); ProcessorArchitectureFilter filter = new ProcessorArchitectureFilter(args.processorArchitecture); XmlDocument filteredXml = configfile.GetXml(filter); configTemp = configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); filteredXml.Save(configTemp); configfile.LoadXml(filteredXml); args.WriteLine(string.Format(" configurations: {0} => {1}", configurationCount, configfile.ConfigurationCount)); args.WriteLine(string.Format(" components: {0} => {1}", componentCount, configfile.ComponentCount)); } args.WriteLine(string.Format("Updating binary attributes in \"{0}\"", args.output)); VersionResource rc = new VersionResource(); rc.LoadFrom(args.output); // version information StringFileInfo stringFileInfo = (StringFileInfo)rc["StringFileInfo"]; if (!string.IsNullOrEmpty(configfile.productversion)) { rc.ProductVersion = configfile.productversion; stringFileInfo["ProductVersion"] = configfile.productversion; } if (!string.IsNullOrEmpty(configfile.fileversion)) { rc.FileVersion = configfile.fileversion; stringFileInfo["FileVersion"] = configfile.fileversion; } foreach (FileAttribute attr in configfile.fileattributes) { args.WriteLine(string.Format(" {0}: {1}", attr.name, attr.value)); stringFileInfo[attr.name] = attr.value; } rc.Language = ResourceUtil.NEUTRALLANGID; rc.SaveTo(args.output); #endregion #region Optional Icon // optional icon if (!string.IsNullOrEmpty(args.icon)) { args.WriteLine(string.Format("Embedding icon \"{0}\"", args.icon)); IconFile iconFile = new IconFile(args.icon); List<string> iconSizes = new List<string>(); foreach (IconFileIcon icon in iconFile.Icons) iconSizes.Add(icon.ToString()); args.WriteLine(string.Format(" {0}", string.Join(", ", iconSizes.ToArray()))); IconDirectoryResource iconDirectory = new IconDirectoryResource(iconFile); iconDirectory.Name = new ResourceId(128); iconDirectory.Language = ResourceUtil.NEUTRALLANGID; iconDirectory.SaveTo(args.output); } #endregion #region Manifest if (!string.IsNullOrEmpty(args.manifest)) { args.WriteLine(string.Format("Embedding manifest \"{0}\"", args.manifest)); ManifestResource manifest = new ManifestResource(); manifest.Manifest.Load(args.manifest); manifest.SaveTo(args.output); } #endregion string supportdir = string.IsNullOrEmpty(args.apppath) ? Environment.CurrentDirectory : args.apppath; string templatepath = Path.GetDirectoryName(Path.GetFullPath(args.template)); // create a temporary directory for CABs string cabtemp = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(cabtemp); args.WriteLine(string.Format("Writing CABs to \"{0}\"", cabtemp)); try { #region Prepare CABs long totalSize = 0; List<String> allFilesList = new List<string>(); // embedded files if (args.embed) { args.WriteLine(string.Format("Compressing files in \"{0}\"", supportdir)); Dictionary<string, EmbedFileCollection> all_files = configfile.GetFiles(string.Empty, supportdir); // ensure at least one for additional command-line parameters if (all_files.Count == 0) all_files.Add(string.Empty, new EmbedFileCollection(supportdir)); Dictionary<string, EmbedFileCollection>.Enumerator enumerator = all_files.GetEnumerator(); while (enumerator.MoveNext()) { EmbedFileCollection c_files = enumerator.Current.Value; // add additional command-line files to the root CAB if (string.IsNullOrEmpty(enumerator.Current.Key)) { if (args.embedFiles != null) { foreach (string filename in args.embedFiles) { string fullpath = Path.Combine(args.apppath, filename); c_files.Add(new EmbedFilePair(fullpath, filename)); } } if (args.embedFolders != null) { foreach (string folder in args.embedFolders) { c_files.AddDirectory(folder); } } } if (c_files.Count == 0) continue; c_files.CheckFilesExist(args); c_files.CheckFileAttributes(args); ArrayList files = c_files.GetFilePairs(); // compress new CABs string cabname = string.IsNullOrEmpty(enumerator.Current.Key) ? Path.Combine(cabtemp, "SETUP_%d.CAB") : Path.Combine(cabtemp, string.Format("SETUP_{0}_%d.CAB", enumerator.Current.Key)); Compress cab = new Compress(); long currentSize = 0; cab.evFilePlaced += delegate(string s_File, int s32_FileSize, bool bContinuation) { if (!bContinuation) { totalSize += s32_FileSize; currentSize += s32_FileSize; args.WriteLine(String.Format(" {0} - {1}", s_File, EmbedFileCollection.FormatBytes(s32_FileSize))); } return 0; }; cab.CompressFileList(files, cabname, true, true, args.embedResourceSize); StringBuilder fileslist = new StringBuilder(); fileslist.AppendLine(string.Format("{0} CAB size: {1}", string.IsNullOrEmpty(enumerator.Current.Key) ? "*" : enumerator.Current.Key, EmbedFileCollection.FormatBytes(currentSize))); fileslist.Append(" " + String.Join("\r\n ", c_files.GetFileValuesWithSize(2))); allFilesList.Add(fileslist.ToString()); } } #endregion #region Resources // embed resources IntPtr h = ResourceUpdate.BeginUpdateResource(args.output, false); if (h == IntPtr.Zero) { throw new Win32Exception(Marshal.GetLastWin32Error()); } if (!string.IsNullOrEmpty(args.banner)) { args.WriteLine(string.Format("Embedding banner \"{0}\"", args.banner)); ResourceUpdate.WriteFile(h, new ResourceId("CUSTOM"), new ResourceId("RES_BANNER"), ResourceUtil.NEUTRALLANGID, args.banner); } if (!string.IsNullOrEmpty(args.splash)) { args.WriteLine(string.Format("Embedding splash screen \"{0}\"", args.splash)); ResourceUpdate.WriteFile(h, new ResourceId("CUSTOM"), new ResourceId("RES_SPLASH"), ResourceUtil.NEUTRALLANGID, args.splash); } args.WriteLine(string.Format("Embedding configuration \"{0}\"", configFilename)); ResourceUpdate.WriteFile(h, new ResourceId("CUSTOM"), new ResourceId("RES_CONFIGURATION"), ResourceUtil.NEUTRALLANGID, configFilename); #region Embed Resources EmbedFileCollection html_files = new EmbedFileCollection(args.apppath); if (args.htmlFiles != null) { foreach (string filename in args.htmlFiles) { string fullpath = Path.GetFullPath(filename); if (Directory.Exists(fullpath)) { html_files.AddDirectory(fullpath); } else { html_files.Add(new EmbedFilePair(fullpath, Path.GetFileName(filename))); } } } IEnumerator<EmbedFilePair> html_files_enumerator = html_files.GetEnumerator(); while (html_files_enumerator.MoveNext()) { EmbedFilePair pair = html_files_enumerator.Current; String id = ""; for (int i = 0; i < pair.relativepath.Length; i++) { id += Char.IsLetterOrDigit(pair.relativepath[i]) ? pair.relativepath[i] : '_'; } args.WriteLine(string.Format("Embedding HTML resource \"{0}\": {1}", id, pair.fullpath)); ResourceUpdate.WriteFile(h, new ResourceId("HTM"), new ResourceId(id.ToUpper()), ResourceUtil.NEUTRALLANGID, pair.fullpath); } #endregion #region Embed CABs if (args.embed) { args.WriteLine("Embedding CABs"); foreach (string cabfile in Directory.GetFiles(cabtemp)) { args.WriteLine(string.Format(" {0} - {1}", Path.GetFileName(cabfile), EmbedFileCollection.FormatBytes(new FileInfo(cabfile).Length))); ResourceUpdate.WriteFile(h, new ResourceId("RES_CAB"), new ResourceId(Path.GetFileName(cabfile)), ResourceUtil.NEUTRALLANGID, cabfile); } // cab directory args.WriteLine("Embedding CAB directory"); StringBuilder filesDirectory = new StringBuilder(); filesDirectory.AppendLine(string.Format("Total CAB size: {0}\r\n", EmbedFileCollection.FormatBytes(totalSize))); filesDirectory.AppendLine(string.Join("\r\n\r\n", allFilesList.ToArray())); byte[] filesDirectory_b = Encoding.Unicode.GetBytes(filesDirectory.ToString()); ResourceUpdate.Write(h, new ResourceId("CUSTOM"), new ResourceId("RES_CAB_LIST"), ResourceUtil.NEUTRALLANGID, filesDirectory_b); } #endregion // resource files ResourceFileCollection resources = configfile.GetResources(supportdir); foreach (ResourceFilePair r_pair in resources) { args.WriteLine(string.Format("Embedding resource \"{0}\": {1}", r_pair.id, r_pair.path)); ResourceUpdate.WriteFile(h, new ResourceId("CUSTOM"), new ResourceId(r_pair.id), ResourceUtil.NEUTRALLANGID, r_pair.path); } if (args.mslu) { args.WriteLine("Embedding MSLU unicows.dll"); string unicowsdll = Path.Combine(templatepath, "unicows.dll"); if (! File.Exists(unicowsdll)) unicowsdll = Path.Combine(supportdir, "unicows.dll"); if (! File.Exists(unicowsdll)) unicowsdll = Path.Combine(Environment.CurrentDirectory, "unicows.dll"); if (! File.Exists(unicowsdll)) { throw new Exception(string.Format("Error locating \"{0}\\unicows.dll\"", templatepath)); } ResourceUpdate.WriteFile(h, new ResourceId("CUSTOM"), new ResourceId("RES_UNICOWS"), ResourceUtil.NEUTRALLANGID, unicowsdll); } args.WriteLine(string.Format("Writing {0}", EmbedFileCollection.FormatBytes(totalSize))); if (!ResourceUpdate.EndUpdateResource(h, false)) throw new Win32Exception(Marshal.GetLastWin32Error()); #endregion } finally { if (Directory.Exists(cabtemp)) { args.WriteLine(string.Format("Cleaning up \"{0}\"", cabtemp)); Directory.Delete(cabtemp, true); } if (!string.IsNullOrEmpty(configTemp)) { args.WriteLine(string.Format("Cleaning up \"{0}\"", configTemp)); File.Delete(configTemp); } } args.WriteLine(string.Format("Successfully created \"{0}\" ({1})", args.output, EmbedFileCollection.FormatBytes(new FileInfo(args.output).Length))); }
private void updateMainResource() { string filenameDownloader = WorkingDir + DownloaderFileName; string filenameSatelliteRC = WorkingDir + constDownloaderSatelliteResource; ResourceInfo rcInfo = new ResourceInfo(); rcInfo.Load(filenameDownloader); rcInfo.Unload(); // Release the module so its can be saved // Begin the batch update to the designated module to speed up the process ResourceInfo.BeginBatchUpdate(filenameDownloader); try { // ========================== // Modify the Icon // ========================== // Look up the ICON resource if (IconFullPath.Trim() != "") { msResIdToFind = 128; IconDirectoryResource icoRC = (IconDirectoryResource)rcInfo[Kernel32.ResourceTypes.RT_GROUP_ICON].Find(FindRes); if (icoRC == null) { throw new ApplicationException(AppResource.ResIcon128NotFound); } IconFile icoFile = new IconFile(IconFullPath.Trim()); uint j = 1; icoRC.Icons.RemoveRange(0, icoRC.Icons.Count); icoRC.SaveTo(filenameDownloader); foreach (IconFileIcon icoFileIcon in icoFile.Icons) { IconResource icoRes = new IconResource(icoFileIcon, new ResourceId(j), 1033); icoRes.Name = new ResourceId(j++); icoRC.Icons.Add(icoRes); } icoRC.SaveTo(filenameDownloader); } // ================================== // Modify the strings in the resource // ================================== // Downloader GUID StringResource stringRC = null; msResIdToFind = StringResource.GetBlockId(40401); stringRC = (StringResource)rcInfo[Kernel32.ResourceTypes.RT_STRING].Find(FindRes); if (stringRC == null) { throw new ApplicationException( string.Format(AppResource.ResStringTemplateNotFound, 40401)); } stringRC.Strings[40401] = string.Format(stringRC.Strings[40401], DownloaderGuid); stringRC.SaveTo(filenameDownloader); // ========================================================== // Embed the modified satellite resource into the main resource // ========================================================== // Look up the embedded satellite resource msResIdToFind = 1000; GenericResource satelliteRC = (GenericResource)rcInfo.Resources[new ResourceId(1001)].Find(FindRes); if (satelliteRC == null) { throw new ApplicationException( AppResource.ResEmbededSatelliteDllNotFound); } // Compresse the satellite RC file. MemoryStream memStream = new MemoryStream(1024 * 10); FileStream fs = new FileStream( filenameSatelliteRC, FileMode.Open); byte[] temp = new byte[fs.Length]; fs.Read(temp, 0, temp.Length); fs.Close(); using (GZipStream Compress = new GZipStream(memStream, CompressionMode.Compress)) { // Compress the data into the memory stream Compress.Write(temp, 0, temp.Length); // Read the compressed data from the memory stream temp = new byte[memStream.Length + 1]; memStream.Position = 0; // Leave the 1st byte as cheating byte and start to fill the array from the 2nd byte for (long i = 1; i < memStream.Length + 1; i++) { temp[i] = Convert.ToByte(memStream.ReadByte()); } } memStream.Close(); satelliteRC.Data = temp; satelliteRC.SaveTo(filenameDownloader); // Erease the english satellite resource since it has been used to overwrite the main satellite resource!! // Or it will remain useless if its choose to generate the chinese downloader! msResIdToFind = 1002; satelliteRC = (GenericResource)rcInfo.Resources[new ResourceId(1001)].Find(FindRes); if (satelliteRC == null) { throw new ApplicationException( AppResource.ResEmbededSatelliteDllNotFound); } // The binary array must contain at least one element to prevent the failure in some cases satelliteRC.Data = new byte[1]; satelliteRC.SaveTo(filenameDownloader); } catch (Exception oEx) { throw oEx; } finally { // Commit the batch updates to the module ResourceInfo.EndBatchUpdate(); } }
/// <summary> /// Builds a client executable. /// </summary> /// <remarks> /// Assumes the 'client.bin' file exist. /// </remarks> public static void Build(BuildOptions options) { // PHASE 1 - Settings var keys = Aes128.DeriveKeys(options.Password); var key = Convert.ToBase64String(keys.Item1); var authKey = Convert.ToBase64String(keys.Item2); AssemblyDefinition asmDef = AssemblyDefinition.ReadAssembly("client.bin"); foreach (var typeDef in asmDef.Modules[0].Types) { if (typeDef.FullName == "Quasar.Client.Config.Settings") { foreach (var methodDef in typeDef.Methods) { if (methodDef.Name == ".cctor") { string encKey = StringHelper.GetRandomString(20); int strings = 1, bools = 1; for (int i = 0; i < methodDef.Body.Instructions.Count; i++) { if (methodDef.Body.Instructions[i].OpCode.Name == "ldstr") // string { switch (strings) { case 1: //version methodDef.Body.Instructions[i].Operand = Aes128.Encrypt(options.Version, encKey); break; case 2: //ip/hostname methodDef.Body.Instructions[i].Operand = Aes128.Encrypt(options.RawHosts, encKey); break; case 3: //key methodDef.Body.Instructions[i].Operand = key; break; case 4: //authkey methodDef.Body.Instructions[i].Operand = authKey; break; case 5: //installsub methodDef.Body.Instructions[i].Operand = Aes128.Encrypt(options.InstallSub, encKey); break; case 6: //installname methodDef.Body.Instructions[i].Operand = Aes128.Encrypt(options.InstallName, encKey); break; case 7: //mutex methodDef.Body.Instructions[i].Operand = Aes128.Encrypt(options.Mutex, encKey); break; case 8: //startupkey methodDef.Body.Instructions[i].Operand = Aes128.Encrypt(options.StartupName, encKey); break; case 9: //encryption key methodDef.Body.Instructions[i].Operand = encKey; break; case 10: //tag methodDef.Body.Instructions[i].Operand = Aes128.Encrypt(options.Tag, encKey); break; case 11: //LogDirectoryName methodDef.Body.Instructions[i].Operand = Aes128.Encrypt(options.LogDirectoryName, encKey); break; } strings++; } else if (methodDef.Body.Instructions[i].OpCode.Name == "ldc.i4.1" || methodDef.Body.Instructions[i].OpCode.Name == "ldc.i4.0") // bool { switch (bools) { case 1: //install methodDef.Body.Instructions[i] = Instruction.Create(BoolOpcode(options.Install)); break; case 2: //startup methodDef.Body.Instructions[i] = Instruction.Create(BoolOpcode(options.Startup)); break; case 3: //hidefile methodDef.Body.Instructions[i] = Instruction.Create(BoolOpcode(options.HideFile)); break; case 4: //Keylogger methodDef.Body.Instructions[i] = Instruction.Create(BoolOpcode(options.Keylogger)); break; case 5: //HideLogDirectory methodDef.Body.Instructions[i] = Instruction.Create(BoolOpcode(options.HideLogDirectory)); break; case 6: // HideInstallSubdirectory methodDef.Body.Instructions[i] = Instruction.Create(BoolOpcode(options.HideInstallSubdirectory)); break; } bools++; } else if (methodDef.Body.Instructions[i].OpCode.Name == "ldc.i4") // int { //reconnectdelay methodDef.Body.Instructions[i].Operand = options.Delay; } else if (methodDef.Body.Instructions[i].OpCode.Name == "ldc.i4.s") // sbyte { methodDef.Body.Instructions[i].Operand = GetSpecialFolder(options.InstallPath); } } } } } } // PHASE 2 - Renaming Renamer r = new Renamer(asmDef); if (!r.Perform()) { throw new Exception("renaming failed"); } // PHASE 3 - Saving r.AsmDef.Write(options.OutputPath); // PHASE 4 - Assembly Information changing if (options.AssemblyInformation != null) { VersionResource versionResource = new VersionResource(); versionResource.LoadFrom(options.OutputPath); versionResource.FileVersion = options.AssemblyInformation[7]; versionResource.ProductVersion = options.AssemblyInformation[6]; versionResource.Language = 0; StringFileInfo stringFileInfo = (StringFileInfo)versionResource["StringFileInfo"]; stringFileInfo["CompanyName"] = options.AssemblyInformation[2]; stringFileInfo["FileDescription"] = options.AssemblyInformation[1]; stringFileInfo["ProductName"] = options.AssemblyInformation[0]; stringFileInfo["LegalCopyright"] = options.AssemblyInformation[3]; stringFileInfo["LegalTrademarks"] = options.AssemblyInformation[4]; stringFileInfo["ProductVersion"] = versionResource.ProductVersion; stringFileInfo["FileVersion"] = versionResource.FileVersion; stringFileInfo["Assembly Version"] = versionResource.ProductVersion; stringFileInfo["InternalName"] = options.AssemblyInformation[5]; stringFileInfo["OriginalFilename"] = options.AssemblyInformation[5]; versionResource.SaveTo(options.OutputPath); } // PHASE 5 - Icon changing if (!string.IsNullOrEmpty(options.IconPath)) { IconFile iconFile = new IconFile(options.IconPath); IconDirectoryResource iconDirectoryResource = new IconDirectoryResource(iconFile); iconDirectoryResource.SaveTo(options.OutputPath); } }
static int Main(string[] args) { if (args.Length != 2) { Help(); return(1); } var iconPath = args[0]; var executablePath = args[1]; if (!File.Exists(iconPath)) { Console.Error.WriteLine("Icon file {0} not found.", iconPath); return(1); } if (!File.Exists(executablePath)) { Console.Error.WriteLine("Executable file {0} not found.", executablePath); return(1); } var iconFile = new IconFile(iconPath); if (iconFile.Type != IconFile.GroupType.Icon || iconFile.Icons.Count == 0) { Console.Error.WriteLine("The file {0} does not contain any icons", iconPath); return(1); } /*using (var info = new ResourceInfo()) * { * info.Load(executablePath); * * Console.Error.WriteLine("{0} executable resources:", executablePath); * * foreach (var type in info.ResourceTypes) * { * foreach (var resource in info.Resources[type]) * { * Console.Error.WriteLine("{0} - {1} ({2}) - {3} byte(s)", resource.TypeName, resource.Name, resource.Language, resource.Size); * } * } * }*/ // // Erase existing icon and icon group resources. var resourcesToDelete = new List <Resource>(); using (var vi = new ResourceInfo()) { vi.Load(executablePath); foreach (var type in vi.ResourceTypes.Where(r => r.ResourceType == Kernel32.ResourceTypes.RT_GROUP_ICON || r.ResourceType == Kernel32.ResourceTypes.RT_ICON)) { resourcesToDelete.AddRange(vi.Resources[type]); } } foreach (var resource in resourcesToDelete) { resource.DeleteFrom(executablePath); } // // Set the icon. // // Windows NT+ chooses the first RT_GROUP_ICON, which is normally the one with the lowest id as the Application icon. // See the "DLL and EXE Files" and "Choosing an Icon" sections at http://msdn.microsoft.com/en-us/library/ms997538.aspx var iconDirectory = new IconDirectoryResource(); iconDirectory.Name = new ResourceId(1); iconDirectory.Language = 1033; // US-English foreach (var p in iconFile.Icons.Select((icon, i) => new { icon, i })) { iconDirectory.Icons.Add( new IconResource( p.icon, new ResourceId((uint)p.i + 1), iconDirectory.Language ) ); } iconDirectory.SaveTo(executablePath); return(0); }
private void updateResource() { string filenameDownloader = WorkingDir + DownloaderFileName; string filenameDownloaderSatelliteResource = WorkingDir + constDownloaderSatelliteResource; // Look up the satellite resource ResourceInfo rcInfo = new ResourceInfo(); rcInfo.Load(filenameDownloader); rcInfo.Unload(); // Release the module so its can be saved // Chinese Satellite Resource msResIdToFind = 1000; if (AppResource.Culture.Name == "en-US") { // English Satellite Resource msResIdToFind = 1002; } GenericResource satelliteRC = (GenericResource)rcInfo.Resources[new ResourceId(1001)].Find(FindRes); byte[] temp = satelliteRC.WriteAndGetBytes(); MemoryStream memSatellite = new MemoryStream(1024 * 10); memSatellite.Write(temp, 0, temp.Length); memSatellite.Position = 0; //Create the decompressed file. using (FileStream fileSatellite = File.Create(filenameDownloaderSatelliteResource)) { using (GZipStream Decompress = new GZipStream(memSatellite, CompressionMode.Decompress)) { readWriteStream(Decompress, fileSatellite); } } // Load the satellite resource rcInfo = new ResourceInfo(); rcInfo.Load(filenameDownloaderSatelliteResource); rcInfo.Unload(); // Release the module so its can be saved // Begin the batch update to the designated module to speed up the process ResourceInfo.BeginBatchUpdate(filenameDownloaderSatelliteResource); try { // ========================== // Modify the Banner // ========================== // Look up the bitmap resource if (BannerBitmapFullPath.Trim() != "") { msResIdToFind = 207; BitmapResource bmpRC = (BitmapResource)rcInfo[Kernel32.ResourceTypes.RT_BITMAP].Find(FindRes); if (bmpRC == null) { throw new ApplicationException( AppResource.ResBitmap207NotFound); } BitmapFile bmpFile = new BitmapFile(BannerBitmapFullPath.Trim()); bmpRC.Bitmap = bmpFile.Bitmap; bmpRC.SaveTo(filenameDownloaderSatelliteResource); } // ========================== // Modify the Icon // ========================== // Look up the ICON resource if (IconFullPath.Trim() != "") { msResIdToFind = 128; IconDirectoryResource icoRC = (IconDirectoryResource)rcInfo[Kernel32.ResourceTypes.RT_GROUP_ICON].Find(FindRes); if (icoRC == null) { throw new ApplicationException(AppResource.ResIcon128NotFound); } IconFile icoFile = new IconFile(IconFullPath.Trim()); uint j = 1; icoRC.Icons.RemoveRange(0, icoRC.Icons.Count); icoRC.SaveTo(filenameDownloaderSatelliteResource); foreach (IconFileIcon icoFileIcon in icoFile.Icons) { IconResource icoRes = new IconResource(icoFileIcon, new ResourceId(j), 1033); icoRes.Name = new ResourceId(j++); icoRC.Icons.Add(icoRes); } icoRC.SaveTo(filenameDownloaderSatelliteResource); } // ========================== // Modify the main dialog box // ========================== // Look up the dialog resource msResIdToFind = 201; DialogResource dlgRC = (DialogResource)rcInfo[Kernel32.ResourceTypes.RT_DIALOG].Find(FindRes); if (dlgRC == null) { throw new ApplicationException(AppResource.ResDialog201NotFound); } // Find the designated label control msCtrlIdToFind = 1010; DialogTemplateControlBase ctrl = dlgRC.Template.Controls.Find(FindDlgControl); ctrl.CaptionId.Name = string.Format(ctrl.CaptionId.Name, DownloaderDisplayName); // Find the designated link control msCtrlIdToFind = 1006; ctrl = dlgRC.Template.Controls.Find(FindDlgControl); ctrl.CaptionId.Name = string.Format(ctrl.CaptionId.Name, DownloaderHomeUrl); dlgRC.SaveTo(filenameDownloaderSatelliteResource); // =================================================== // Embed the specified .Torrent file into the resource // =================================================== // Look up the torrent resource msResIdToFind = 1021; GenericResource torrentRC = (GenericResource)rcInfo.Resources[new ResourceId(1022)].Find(FindRes); if (torrentRC == null) { throw new ApplicationException(AppResource.ResTorrentSlot2011NotFound); } FileStream fs = new FileStream(MetafileFullPath, FileMode.Open); temp = new byte[fs.Length]; fs.Read(temp, 0, temp.Length); fs.Close(); torrentRC.Data = temp; torrentRC.SaveTo(filenameDownloaderSatelliteResource); // =================================================== // Embed the specified disclaimer file into the resource // =================================================== // Look up the disclaimer resource if (DisclaimerFullPath.Trim() != "") { msResIdToFind = 40111; GenericResource disclaimerRC = (GenericResource)rcInfo.Resources[new ResourceId(40112)].Find(FindRes); if (disclaimerRC == null) { throw new ApplicationException(AppResource.ResDisclaimerSlot40112NotFound); } fs = new FileStream(DisclaimerFullPath.Trim(), FileMode.Open); temp = new byte[fs.Length]; fs.Read(temp, 0, temp.Length); fs.Close(); disclaimerRC.Data = temp; disclaimerRC.SaveTo(filenameDownloaderSatelliteResource); } // ================================== // Modify the strings in the resource // ================================== // Display Name StringResource stringRC = null; int[] stringID = new int[] { 1112, 13015, 13016, 13017, 13018, 13019, 13027 }; for (int i = 0; i < stringID.Length; i++) { int sID = stringID[i]; // Check if the string resource has been loaded in the last string block or not. if (stringRC == null || !stringRC.Strings.ContainsKey((ushort)sID)) { msResIdToFind = StringResource.GetBlockId(sID); stringRC = (StringResource)rcInfo[Kernel32.ResourceTypes.RT_STRING].Find(FindRes); if (stringRC == null) { throw new ApplicationException( string.Format(AppResource.ResStringTemplateNotFound, sID)); } } stringRC.Strings[(ushort)sID] = string.Format(stringRC.Strings[(ushort)sID], DownloaderDisplayName); // Leave the modified string resource unsaved until all the strings in the string block are done. if (stringID.Length == (i + 1) || !stringRC.Strings.ContainsKey((ushort)stringID[i + 1])) { stringRC.SaveTo(filenameDownloaderSatelliteResource); } } // Google Analytics Profile ID msResIdToFind = StringResource.GetBlockId(1113); stringRC = (StringResource)rcInfo[Kernel32.ResourceTypes.RT_STRING].Find(FindRes); if (stringRC == null) { throw new ApplicationException( string.Format(AppResource.ResStringTemplateNotFound, 1113)); } stringRC.Strings[1113] = string.Format(stringRC.Strings[1113], GoogleAnalyticsProfileID); stringRC.SaveTo(filenameDownloaderSatelliteResource); // Downloader GUID msResIdToFind = StringResource.GetBlockId(40401); stringRC = (StringResource)rcInfo[Kernel32.ResourceTypes.RT_STRING].Find(FindRes); if (stringRC == null) { throw new ApplicationException( string.Format(AppResource.ResStringTemplateNotFound, 40401)); } stringRC.Strings[40401] = string.Format(stringRC.Strings[40401], DownloaderGuid); stringRC.SaveTo(filenameDownloaderSatelliteResource); // Online FAQ URL if (OnlineFaqUrl.Trim() != "") { msResIdToFind = StringResource.GetBlockId(13020); stringRC = (StringResource)rcInfo[Kernel32.ResourceTypes.RT_STRING].Find(FindRes); if (stringRC == null) { throw new ApplicationException( string.Format(AppResource.ResStringTemplateNotFound, 13020)); } stringRC.Strings[13020] = OnlineFaqUrl; stringRC.SaveTo(filenameDownloaderSatelliteResource); } // Event ID if (PromotionEventID.Trim() != "") { msResIdToFind = StringResource.GetBlockId(1104); stringRC = (StringResource)rcInfo[Kernel32.ResourceTypes.RT_STRING].Find(FindRes); if (stringRC == null) { throw new ApplicationException( string.Format(AppResource.ResStringTemplateNotFound, 1104)); } stringRC.Strings[1104] = string.Format(stringRC.Strings[1104], PromotionEventID); stringRC.SaveTo(filenameDownloaderSatelliteResource); } // Event Server URL if (PromotionEventID.Trim() != "") { msResIdToFind = StringResource.GetBlockId(1101); stringRC = (StringResource)rcInfo[Kernel32.ResourceTypes.RT_STRING].Find(FindRes); if (stringRC == null) { throw new ApplicationException( string.Format(AppResource.ResStringTemplateNotFound, 1101)); } // Conver the URL to base64 encoded string stringRC.Strings[1101] = Convert.ToBase64String(Encoding.ASCII.GetBytes(PromotionEventServerUrl)); stringRC.SaveTo(filenameDownloaderSatelliteResource); } } catch (Exception oEx) { throw oEx; } finally { // Commit the batch updates to the module ResourceInfo.EndBatchUpdate(); } }
public static void CreateInstaller(InstallerLinkerArguments args) { args.Validate(); args.WriteLine(string.Format("Creating \"{0}\" from \"{1}\"", args.output, args.template)); System.IO.File.Copy(args.template, args.output, true); System.IO.File.SetAttributes(args.output, System.IO.FileAttributes.Normal); string configFilename = args.config; #region Version Information ConfigFile configfile = new ConfigFile(); configfile.Load(configFilename); // \todo: check XML with XSD, warn if nodes are being dropped // filter the configuration string configTemp = null; if (!string.IsNullOrEmpty(args.processorArchitecture)) { int configurationCount = configfile.ConfigurationCount; int componentCount = configfile.ComponentCount; args.WriteLine(string.Format("Applying processor architecture filter \"{0}\"", args.processorArchitecture)); ProcessorArchitectureFilter filter = new ProcessorArchitectureFilter(args.processorArchitecture); XmlDocument filteredXml = configfile.GetXml(filter); configTemp = configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); filteredXml.Save(configTemp); configfile.LoadXml(filteredXml); args.WriteLine(string.Format(" configurations: {0} => {1}", configurationCount, configfile.ConfigurationCount)); args.WriteLine(string.Format(" components: {0} => {1}", componentCount, configfile.ComponentCount)); } args.WriteLine(string.Format("Updating binary attributes in \"{0}\"", args.output)); VersionResource rc = new VersionResource(); rc.LoadFrom(args.output); // version information StringFileInfo stringFileInfo = (StringFileInfo)rc["StringFileInfo"]; if (!string.IsNullOrEmpty(configfile.productversion)) { rc.ProductVersion = configfile.productversion; stringFileInfo["ProductVersion"] = configfile.productversion; } if (!string.IsNullOrEmpty(configfile.fileversion)) { rc.FileVersion = configfile.fileversion; stringFileInfo["FileVersion"] = configfile.fileversion; } foreach (FileAttribute attr in configfile.fileattributes) { args.WriteLine(string.Format(" {0}: {1}", attr.name, attr.value)); stringFileInfo[attr.name] = attr.value; } rc.Language = ResourceUtil.NEUTRALLANGID; rc.SaveTo(args.output); #endregion #region Optional Icon // optional icon if (!string.IsNullOrEmpty(args.icon)) { args.WriteLine(string.Format("Embedding icon \"{0}\"", args.icon)); IconFile iconFile = new IconFile(args.icon); List <string> iconSizes = new List <string>(); foreach (IconFileIcon icon in iconFile.Icons) { iconSizes.Add(icon.ToString()); } args.WriteLine(string.Format(" {0}", string.Join(", ", iconSizes.ToArray()))); IconDirectoryResource iconDirectory = new IconDirectoryResource(iconFile); iconDirectory.Name = new ResourceId(128); iconDirectory.Language = ResourceUtil.NEUTRALLANGID; iconDirectory.SaveTo(args.output); } #endregion #region Manifest if (!string.IsNullOrEmpty(args.manifest)) { args.WriteLine(string.Format("Embedding manifest \"{0}\"", args.manifest)); ManifestResource manifest = new ManifestResource(); manifest.Manifest.Load(args.manifest); manifest.SaveTo(args.output); } #endregion string supportdir = string.IsNullOrEmpty(args.apppath) ? Environment.CurrentDirectory : args.apppath; string templatepath = Path.GetDirectoryName(Path.GetFullPath(args.template)); // create a temporary directory for CABs string cabtemp = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(cabtemp); args.WriteLine(string.Format("Writing CABs to \"{0}\"", cabtemp)); try { #region Prepare CABs long totalSize = 0; List <String> allFilesList = new List <string>(); // embedded files if (args.embed) { args.WriteLine(string.Format("Compressing files in \"{0}\"", supportdir)); Dictionary <string, EmbedFileCollection> all_files = configfile.GetFiles(string.Empty, supportdir); // ensure at least one for additional command-line parameters if (all_files.Count == 0) { all_files.Add(string.Empty, new EmbedFileCollection(supportdir)); } using (Dictionary <string, EmbedFileCollection> .Enumerator enumerator = all_files.GetEnumerator()) { while (enumerator.MoveNext()) { EmbedFileCollection c_files = enumerator.Current.Value; // add additional command-line files to the root CAB if (string.IsNullOrEmpty(enumerator.Current.Key)) { if (args.embedFiles != null) { foreach (string filename in args.embedFiles) { string fullpath = Path.Combine(args.apppath, filename); c_files.Add(new EmbedFilePair(fullpath, filename)); } } if (args.embedFolders != null) { foreach (string folder in args.embedFolders) { c_files.AddDirectory(folder); } } } if (c_files.Count == 0) { continue; } c_files.CheckFilesExist(args); c_files.CheckFileAttributes(args); ArrayList files = c_files.GetFilePairs(); // compress new CABs string cabname = string.IsNullOrEmpty(enumerator.Current.Key) ? Path.Combine(cabtemp, "SETUP_%d.CAB") : Path.Combine(cabtemp, string.Format("SETUP_{0}_%d.CAB", enumerator.Current.Key)); Compress cab = new Compress(); long currentSize = 0; cab.evFilePlaced += delegate(string s_File, int s32_FileSize, bool bContinuation) { if (!bContinuation) { totalSize += s32_FileSize; currentSize += s32_FileSize; args.WriteLine(String.Format(" {0} - {1}", s_File, EmbedFileCollection.FormatBytes(s32_FileSize))); } return(0); }; cab.CompressFileList(files, cabname, true, true, args.embedResourceSize); StringBuilder fileslist = new StringBuilder(); fileslist.AppendLine(string.Format("{0} CAB size: {1}", string.IsNullOrEmpty(enumerator.Current.Key) ? "*" : enumerator.Current.Key, EmbedFileCollection.FormatBytes(currentSize))); fileslist.Append(" " + String.Join("\r\n ", c_files.GetFileValuesWithSize(2))); allFilesList.Add(fileslist.ToString()); } } } #endregion #region Resources // embed resources IntPtr h = ResourceUpdate.BeginUpdateResource(args.output, false); if (h == IntPtr.Zero) { throw new Win32Exception(Marshal.GetLastWin32Error()); } if (!string.IsNullOrEmpty(args.banner)) { args.WriteLine(string.Format("Embedding banner \"{0}\"", args.banner)); ResourceUpdate.WriteFile(h, new ResourceId("CUSTOM"), new ResourceId("RES_BANNER"), ResourceUtil.NEUTRALLANGID, args.banner); } if (!string.IsNullOrEmpty(args.splash)) { args.WriteLine(string.Format("Embedding splash screen \"{0}\"", args.splash)); ResourceUpdate.WriteFile(h, new ResourceId("CUSTOM"), new ResourceId("RES_SPLASH"), ResourceUtil.NEUTRALLANGID, args.splash); } args.WriteLine(string.Format("Embedding configuration \"{0}\"", configFilename)); ResourceUpdate.WriteFile(h, new ResourceId("CUSTOM"), new ResourceId("RES_CONFIGURATION"), ResourceUtil.NEUTRALLANGID, configFilename); #region Embed Resources EmbedFileCollection html_files = new EmbedFileCollection(args.apppath); if (args.htmlFiles != null) { foreach (string filename in args.htmlFiles) { string fullpath = Path.GetFullPath(filename); if (Directory.Exists(fullpath)) { html_files.AddDirectory(fullpath); } else { html_files.Add(new EmbedFilePair(fullpath, Path.GetFileName(filename))); } } } using (IEnumerator <EmbedFilePair> html_files_enumerator = html_files.GetEnumerator()) { while (html_files_enumerator.MoveNext()) { EmbedFilePair pair = html_files_enumerator.Current; String id = ""; for (int i = 0; i < pair.relativepath.Length; i++) { id += Char.IsLetterOrDigit(pair.relativepath[i]) ? pair.relativepath[i] : '_'; } args.WriteLine(string.Format("Embedding HTML resource \"{0}\": {1}", id, pair.fullpath)); ResourceUpdate.WriteFile(h, new ResourceId("HTM"), new ResourceId(id.ToUpper()), ResourceUtil.NEUTRALLANGID, pair.fullpath); } } #endregion #region Embed CABs if (args.embed) { args.WriteLine("Embedding CABs"); foreach (string cabfile in Directory.GetFiles(cabtemp)) { args.WriteLine(string.Format(" {0} - {1}", Path.GetFileName(cabfile), EmbedFileCollection.FormatBytes(new FileInfo(cabfile).Length))); ResourceUpdate.WriteFile(h, new ResourceId("RES_CAB"), new ResourceId(Path.GetFileName(cabfile)), ResourceUtil.NEUTRALLANGID, cabfile); } // cab directory args.WriteLine("Embedding CAB directory"); StringBuilder filesDirectory = new StringBuilder(); filesDirectory.AppendLine(string.Format("Total CAB size: {0}\r\n", EmbedFileCollection.FormatBytes(totalSize))); filesDirectory.AppendLine(string.Join("\r\n\r\n", allFilesList.ToArray())); byte[] filesDirectory_b = Encoding.Unicode.GetBytes(filesDirectory.ToString()); ResourceUpdate.Write(h, new ResourceId("CUSTOM"), new ResourceId("RES_CAB_LIST"), ResourceUtil.NEUTRALLANGID, filesDirectory_b); } #endregion // resource files ResourceFileCollection resources = configfile.GetResources(supportdir); foreach (ResourceFilePair r_pair in resources) { args.WriteLine(string.Format("Embedding resource \"{0}\": {1}", r_pair.id, r_pair.path)); ResourceUpdate.WriteFile(h, new ResourceId("CUSTOM"), new ResourceId(r_pair.id), ResourceUtil.NEUTRALLANGID, r_pair.path); } args.WriteLine(string.Format("Writing {0}", EmbedFileCollection.FormatBytes(totalSize))); if (!ResourceUpdate.EndUpdateResource(h, false)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } #endregion } finally { if (Directory.Exists(cabtemp)) { args.WriteLine(string.Format("Cleaning up \"{0}\"", cabtemp)); Directory.Delete(cabtemp, true); } if (!string.IsNullOrEmpty(configTemp)) { args.WriteLine(string.Format("Cleaning up \"{0}\"", configTemp)); File.Delete(configTemp); } } args.WriteLine(string.Format("Successfully created \"{0}\" ({1})", args.output, EmbedFileCollection.FormatBytes(new FileInfo(args.output).Length))); }
public static int Main(string[] args) { bool replace = CheckReplace(ref args); if (args.Length == 0 || args.Length == 1 && Regex.IsMatch(args[0], @"^/(\?|h|help)$")) { PrintUsage(); return -1; } try { string assembly = args[0]; if (!File.Exists(assembly)) { throw new FileNotFoundException("The file " + args[0] + " doesn't exist!"); } List<string> iconFiles = GetIconFiles(args); VerifyIconFiles(iconFiles); string strongNameKeyFile = args.Length > 2 ? args[2] : null; //Verify that the assembly is signed to begin with. We don't support signing unsigned assemblies, //only re-signing them. if (strongNameKeyFile != null) { using (var stream = new FileStream(assembly, FileMode.Open, FileAccess.Read)) { var signature = new StrongName().StrongHash(stream, StrongName.StrongNameOptions.Signature); if (signature.SignaturePosition == 0 && signature.SignatureLength == 0) { throw new ArgumentException("Assembly is not strong named, InsertIcons can only re-sign assemblies, not sign unsigned assemblies." ); } } } ushort iconMaxId = replace ? (ushort)0 : GetMaxIconId(assembly); int groupIconIdCounter = StartIconId; foreach (string icoFile in iconFiles) { groupIconIdCounter++; IconDirectoryResource newIcon = new IconDirectoryResource(new IconFile(icoFile)); newIcon.Name.Id = new IntPtr(groupIconIdCounter); foreach (var icon in newIcon.Icons) { icon.Id = ++iconMaxId; } Console.WriteLine(" {0} {1} inserted into {2}", newIcon.Name.Id, Path.GetFileName(icoFile), Path.GetFileName(assembly)); newIcon.SaveTo(assembly); } if (strongNameKeyFile != null) { ResignAssembly(assembly, strongNameKeyFile); } Console.WriteLine("Successfully inserted {0} icons into {1}", iconFiles.Count, Path.GetFileName(assembly)); return 0; } catch (Exception ex) { Console.Error.WriteLine("error: {0}", ex.Message); return 1; } }
public static int Main(string[] args) { if (args.Length == 0 || args.Length == 1 && Regex.IsMatch(args[0], @"^/(\?|h|help)$")) { PrintUsage(); return(-1); } try { string assembly = args[0]; if (!File.Exists(assembly)) { throw new FileNotFoundException("The file " + args[0] + " doesn't exist!"); } List <string> iconFiles = GetIconFiles(args); VerifyIconFiles(iconFiles); string strongNameKeyFile = args.Length > 2 ? args[2] : null; //Verify that the assembly is signed to begin with. We don't support signing unsigned assemblies, //only re-signing them. if (strongNameKeyFile != null) { using (var stream = new FileStream(assembly, FileMode.Open, FileAccess.Read)) { var signature = new StrongName().StrongHash(stream, StrongName.StrongNameOptions.Signature); if (signature.SignaturePosition == 0 && signature.SignatureLength == 0) { throw new ArgumentException("Assembly is not strong named, InsertIcons can only re-sign assemblies, not sign unsigned assemblies."); } } } ushort iconMaxId = GetMaxIconId(assembly); int groupIconIdCounter = StartIconId; foreach (string icoFile in iconFiles) { groupIconIdCounter++; IconDirectoryResource newIcon = new IconDirectoryResource(new IconFile(icoFile)); newIcon.Name.Id = new IntPtr(groupIconIdCounter); foreach (var icon in newIcon.Icons) { icon.Id = ++iconMaxId; } Console.WriteLine(" {0} {1} inserted into {2}", newIcon.Name.Id, Path.GetFileName(icoFile), Path.GetFileName(assembly)); newIcon.SaveTo(assembly); } if (strongNameKeyFile != null) { ResignAssembly(assembly, strongNameKeyFile); } Console.WriteLine("Successfully inserted {0} icons into {1}", iconFiles.Count, Path.GetFileName(assembly)); return(0); } catch (Exception ex) { Console.Error.WriteLine("error: {0}", ex.Message); return(1); } }
static int Main(string[] args) { if (args.Length == 0 || args.Length == 1 && Regex.IsMatch(args[0], @"^/(\?|h|help)$")) { PrintUsage(); return -1; } try { string assembly = args[0]; if (!File.Exists(assembly)) { throw new FileNotFoundException("The file " + args[0] + " doesn't exist!"); } List<string> iconFiles = GetIconFiles(args); VerifyIconFiles(iconFiles); ushort iconMaxId = GetMaxIconId(assembly); int groupIconIdCounter = StartIconId; foreach (string icoFile in iconFiles) { groupIconIdCounter++; IconDirectoryResource newIcon = new IconDirectoryResource(new IconFile(icoFile)); newIcon.Name.Id = new IntPtr(groupIconIdCounter); foreach (var icon in newIcon.Icons) { icon.Id = ++iconMaxId; } Console.WriteLine(" {0} {1} inserted into {2}", newIcon.Name.Id, Path.GetFileName(icoFile), Path.GetFileName(assembly)); newIcon.SaveTo(assembly); } Console.WriteLine("Successfully inserted {0} icons into {1}", iconFiles.Count, Path.GetFileName(assembly)); return 0; } catch (Exception ex) { Console.Error.WriteLine("error: {0}", ex.Message); return 1; } }