public void TestCustom() { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string filename = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\custom.exe"); Assert.IsTrue(File.Exists(filename)); using (ResourceInfo vi = new ResourceInfo()) { vi.Load(filename); // version resources (well-known) List <Resource> versionResources = vi[Kernel32.ResourceTypes.RT_VERSION]; // RT_VERSION Assert.IsNotNull(versionResources); Assert.AreEqual(1, versionResources.Count); Resource versionResource = versionResources[0]; Assert.AreEqual(versionResource.Name.ToString(), "1"); Assert.AreEqual(versionResource.Type.ToString(), "16"); // custom resources List <Resource> customResources = vi["CUSTOM"]; Assert.IsNotNull(customResources); Assert.AreEqual(1, customResources.Count); Resource customResource = customResources[0]; // check whether the properties are string representations Assert.AreEqual(customResource.Name.ToString(), "RES_CONFIGURATION"); Assert.AreEqual(customResource.Type.ToString(), "CUSTOM"); } }
public void TestAddDialogResource() { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string uriPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)); string gutilsdll = Path.Combine(uriPath, @"Binaries\gutils.dll"); int dialogsBefore = 0; using (ResourceInfo ri = new ResourceInfo()) { ri.Load(gutilsdll); dialogsBefore = ri.Resources[new ResourceId(Kernel32.ResourceTypes.RT_DIALOG)].Count; } string targetFilename = Path.Combine(Path.GetTempPath(), "testAddDialogResource.dll"); File.Copy(gutilsdll, targetFilename, true); // copy an existing dialog inside gutils.dll DialogResource sourceDialog = new DialogResource(); sourceDialog.Name = new ResourceId("GABRTDLG"); sourceDialog.LoadFrom(gutilsdll); sourceDialog.Name = new ResourceId("NEWGABRTDLG"); Console.WriteLine(targetFilename); sourceDialog.SaveTo(targetFilename); // check that the dialog was written sourceDialog.LoadFrom(targetFilename); DumpResource.Dump(sourceDialog); using (ResourceInfo ri = new ResourceInfo()) { ri.Load(targetFilename); int dialogsAfter = ri.Resources[new ResourceId(Kernel32.ResourceTypes.RT_DIALOG)].Count; DumpResource.Dump(ri); Assert.AreEqual(dialogsBefore + 1, dialogsAfter); } }
//[Test] //public void FindSmallestBinaryWithResources() //{ // FindSmallestBinaryWithResources( // Environment.SystemDirectory, // "*.exe", // Kernel32.ResourceTypes.RT_MENU); //} private void FindSmallestBinaryWithResources( string path, string ext, Kernel32.ResourceTypes rt) { long smallest = 0; string[] files = Directory.GetFiles(path, ext); foreach (string filename in files) { try { using (ResourceInfo ri = new ResourceInfo()) { ri.Load(filename); if (!ri.Resources.ContainsKey(new ResourceId(rt))) continue; FileInfo fi = new FileInfo(filename); //if (fi.Length < smallest || smallest == 0) //{ Console.WriteLine("{0} {1}", filename, new FileInfo(filename).Length); smallest = fi.Length; // } break; } } catch { } } }
private static void DeleteIcons(string assembly) { using (var info = new ResourceInfo()) { info.Load(assembly); ResourceId iconId = new ResourceId(Kernel32.ResourceTypes.RT_ICON); if (info.Resources.ContainsKey(iconId)) { var res = info.Resources[iconId].OfType <IconDirectoryResource>(); foreach (var r in res) { r.DeleteFrom(assembly); } } ResourceId groupIconId = new ResourceId(Kernel32.ResourceTypes.RT_GROUP_ICON); if (info.Resources.ContainsKey(groupIconId)) { var res = info.Resources[groupIconId].OfType <IconDirectoryResource>(); foreach (var r in res) { r.DeleteFrom(assembly); } } } }
public void TestSaveStringResource() { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string uriPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)); string sourceFilename = Path.Combine(uriPath, @"Binaries\gutils.dll"); string targetFilename = Path.Combine(Path.GetTempPath(), "testSaveStringResource.dll"); File.Copy(sourceFilename, targetFilename, true); // a new resource StringResource sr = new StringResource(); sr.Name = new ResourceId(StringResource.GetBlockId(1256)); sr[1256] = Guid.NewGuid().ToString(); sr.SaveTo(targetFilename); using (ResourceInfo ri = new ResourceInfo()) { ri.Load(targetFilename); Assert.AreEqual(2, ri[Kernel32.ResourceTypes.RT_STRING].Count); Assert.AreEqual(StringResource.GetBlockId(1256), ri[Kernel32.ResourceTypes.RT_STRING][1].Name.Id.ToInt32()); Assert.AreEqual(sr[1256], ((StringResource) ri[Kernel32.ResourceTypes.RT_STRING][1])[1256]); foreach (StringResource rc in ri[Kernel32.ResourceTypes.RT_STRING]) { Console.WriteLine("StringResource: {0}, {1}", rc.Name, rc.TypeName); DumpResource.Dump(rc); } } }
public void TestSaveStringResource() { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string uriPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)); string sourceFilename = Path.Combine(uriPath, @"Binaries\gutils.dll"); string targetFilename = Path.Combine(Path.GetTempPath(), "testSaveStringResource.dll"); File.Copy(sourceFilename, targetFilename, true); // a new resource StringResource sr = new StringResource(); sr.Name = new ResourceId(StringResource.GetBlockId(1256)); sr[1256] = Guid.NewGuid().ToString(); sr.SaveTo(targetFilename); using (ResourceInfo ri = new ResourceInfo()) { ri.Load(targetFilename); Assert.AreEqual(2, ri[Kernel32.ResourceTypes.RT_STRING].Count); Assert.AreEqual(StringResource.GetBlockId(1256), ri[Kernel32.ResourceTypes.RT_STRING][1].Name.Id.ToInt64()); Assert.AreEqual(sr[1256], ((StringResource)ri[Kernel32.ResourceTypes.RT_STRING][1])[1256]); foreach (StringResource rc in ri[Kernel32.ResourceTypes.RT_STRING]) { Console.WriteLine("StringResource: {0}, {1}", rc.Name, rc.TypeName); DumpResource.Dump(rc); } } }
public void TestLoad() { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string uriPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)); string[] files = { // Path.Combine(Environment.SystemDirectory, "regedt32.exe"), // Path.Combine(Environment.GetEnvironmentVariable("WINDIR"), "explorer.exe"), Path.Combine(uriPath, "Binaries\\gutils.dll"), Path.Combine(uriPath, "Binaries\\6to4svc.dll"), Path.Combine(uriPath, "Binaries\\custom.exe"), }; foreach (string filename in files) { Console.WriteLine(filename); Assert.IsTrue(File.Exists(filename)); using (ResourceInfo vi = new ResourceInfo()) { vi.Load(filename); DumpResource.Dump(vi); } } }
public void TestReadWriteResourceBytes(string path) { var filename = Path.GetFileName(path); var isDotNet = filename.StartsWith("ClassLibrary_NET") || filename == "idea64.exe"; if (filename == "idea64.exe") { Assert.Ignore("idea64.exe doesn't consider null byte for StringTableEntry length"); } using (ResourceInfo ri = new ResourceInfo()) { ri.Load(path); foreach (Resource rc in ri) { Console.WriteLine("Resource: {0} - {1}", rc.TypeName, rc.Name); GenericResource genericResource = new GenericResource(rc.Type, rc.Name, rc.Language); genericResource.LoadFrom(path); try { StringTableEntry.ConsiderPaddingForLength = isDotNet; byte[] data = rc.WriteAndGetBytes(); ByteUtils.CompareBytes(genericResource.Data, data); } finally { StringTableEntry.ConsiderPaddingForLength = false; } } } }
// ----------------------------------------------------- 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); }
public void Load(string dll) { var ri = new ResourceInfo(); ri.Load(dll); var languages = ri[Kernel32.ResourceTypes.RT_STRING].GroupBy(r => r.Language); foreach (var language in languages) { var fileName = Path.GetFileNameWithoutExtension(dll); var ci = language.Key == 0 ? System.Globalization.CultureInfo.InvariantCulture : System.Globalization.CultureInfo.GetCultureInfo(language.Key); var culture = ci.Name; var extension = Path.GetExtension(dll); foreach (StringResource resource in language) { foreach (var str in resource.Strings) { string key = Convert.ToString(str.Key); string value = str.Value; value = value.Replace("\n", @"\n"); value = value.Replace("\r", @"\r"); if (strings.ContainsKey(key)) { Console.WriteLine($"Same key id is {key}"); strings.Remove(key); } strings.Add(key, value); } } } strings.OrderBy(x => x.Key); }
public void TestDeleteVersionResource() { string filename = Path.Combine(Environment.SystemDirectory, "atl.dll"); Assert.IsTrue(File.Exists(filename)); string targetFilename = Path.Combine(Path.GetTempPath(), "testDeleteVersionResource.dll"); File.Copy(filename, targetFilename, true); Console.WriteLine(targetFilename); VersionResource versionResource = new VersionResource(); versionResource.Language = ResourceUtil.USENGLISHLANGID; versionResource.LoadFrom(targetFilename); Console.WriteLine("Name: {0}", versionResource.Name); Console.WriteLine("Type: {0}", versionResource.Type); Console.WriteLine("Language: {0}", versionResource.Language); versionResource.DeleteFrom(targetFilename); try { versionResource.LoadFrom(targetFilename); Assert.Fail("Expected that the deleted resource cannot be found"); } catch (Win32Exception ex) { // expected exception Console.WriteLine("Expected exception: {0}", ex.Message); } using (ResourceInfo ri = new ResourceInfo()) { ri.Load(targetFilename); DumpResource.Dump(ri); } }
public void TestCustom() { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string filename = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\custom.exe"); Assert.IsTrue(File.Exists(filename)); using (ResourceInfo vi = new ResourceInfo()) { vi.Load(filename); // version resources (well-known) List<Resource> versionResources = vi[Kernel32.ResourceTypes.RT_VERSION]; // RT_VERSION Assert.IsNotNull(versionResources); Assert.AreEqual(1, versionResources.Count); Resource versionResource = versionResources[0]; Assert.AreEqual(versionResource.Name.ToString(), "1"); Assert.AreEqual(versionResource.Type.ToString(), "16"); // custom resources List<Resource> customResources = vi["CUSTOM"]; Assert.IsNotNull(customResources); Assert.AreEqual(1, customResources.Count); Resource customResource = customResources[0]; // check whether the properties are string representations Assert.AreEqual(customResource.Name.ToString(), "RES_CONFIGURATION"); Assert.AreEqual(customResource.Type.ToString(), "CUSTOM"); } }
public void TestLinkEmbedManifest() { InstallerLinkerArguments args = new InstallerLinkerArguments(); try { ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); configFile.Children.Add(setupConfiguration); args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", args.config); configFile.SaveAs(args.config); args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe"); Console.WriteLine("Linking '{0}'", args.output); args.template = dotNetInstallerExeUtils.Executable; // manifest Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); args.manifest = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Manifests\\asInvoker.manifest"); // link InstallerLib.InstallerLinker.CreateInstaller(args); // check that the linker generated output Assert.IsTrue(File.Exists(args.output)); Assert.IsTrue(new FileInfo(args.output).Length > 0); using (ResourceInfo ri = new ResourceInfo()) { ri.Load(args.output); List <Resource> manifests = ri.Resources[new ResourceId(Kernel32.ResourceTypes.RT_MANIFEST)]; // RT_MANIFEST Assert.IsNotNull(manifests); int expectedManifestFiles = 1; bool usingHtmlInstaller = dotNetInstallerExeUtils.Executable.EndsWith("htmlInstaller.exe"); if (usingHtmlInstaller) { // the stub file already has an embedded manifest expectedManifestFiles++; } Assert.AreEqual(expectedManifestFiles, manifests.Count); ManifestResource manifest = (ManifestResource)manifests[0]; // RT_MANIFEST Console.WriteLine(manifest.Manifest.OuterXml); XmlNamespaceManager manifestNamespaceManager = new XmlNamespaceManager(manifest.Manifest.NameTable); manifestNamespaceManager.AddNamespace("v1", "urn:schemas-microsoft-com:asm.v1"); manifestNamespaceManager.AddNamespace("v3", "urn:schemas-microsoft-com:asm.v3"); string level = manifest.Manifest.SelectSingleNode("//v3:requestedExecutionLevel", manifestNamespaceManager).Attributes["level"].Value; Assert.AreEqual(level, "asInvoker"); } } finally { if (File.Exists(args.config)) { File.Delete(args.config); } if (File.Exists(args.output)) { File.Delete(args.output); } } }
//[Test] //public void FindSmallestBinaryWithResources() //{ // FindSmallestBinaryWithResources( // Environment.SystemDirectory, // "*.exe", // Kernel32.ResourceTypes.RT_MENU); //} private void FindSmallestBinaryWithResources( string path, string ext, Kernel32.ResourceTypes rt) { long smallest = 0; string[] files = Directory.GetFiles(path, ext); foreach (string filename in files) { try { using (ResourceInfo ri = new ResourceInfo()) { ri.Load(filename); if (!ri.Resources.ContainsKey(new ResourceId(rt))) { continue; } FileInfo fi = new FileInfo(filename); //if (fi.Length < smallest || smallest == 0) //{ Console.WriteLine("{0} {1}", filename, new FileInfo(filename).Length); smallest = fi.Length; // } break; } } catch { } } }
public void TestAccelerator() { string filename = Path.Combine(Environment.GetEnvironmentVariable("WINDIR"), "explorer.exe"); Predicate <Accelerator> pReload = (Accelerator a) => { return(a.Key == "VK_F5" && a.Command == 41061); }; using (ResourceInfo ri = new ResourceInfo()) { ri.Load(filename); foreach (AcceleratorResource rc in ri[Kernel32.ResourceTypes.RT_ACCELERATOR]) { Console.WriteLine("Current AcceleratorResource: {0}, {1}", rc.Name, rc.TypeName); Console.WriteLine(rc + "\n------------------------------------\n"); Accelerator newAC = new Accelerator(); newAC.Key = "J"; newAC.Command = 41008; newAC.Flags = User32.AcceleratorVirtualKey.VIRTKEY | User32.AcceleratorVirtualKey.NOINVERT | User32.AcceleratorVirtualKey.CONTROL; try { Accelerator tst = rc.Accelerators.Find(pReload); int loc = rc.Accelerators.FindIndex(pReload); rc.Accelerators.Remove(tst); tst.Key = "VK_NUMPAD9"; tst.addFlag(User32.AcceleratorVirtualKey.CONTROL); tst.removeFlag(User32.AcceleratorVirtualKey.ALT | User32.AcceleratorVirtualKey.NOINVERT); rc.Accelerators.Insert(loc, tst); rc.Accelerators.Add(newAC); List <Accelerator> acList = new List <Accelerator>(); Accelerator acA = new Accelerator(); acA.Command = 413; acList.Add(acA); acList[0].addFlag(User32.AcceleratorVirtualKey.SHIFT); acList[0].Key = "VK_F1"; Accelerator acB = new Accelerator(); acB.Flags = User32.AcceleratorVirtualKey.VIRTKEY | User32.AcceleratorVirtualKey.NOINVERT; acB.Key = "Z"; acList.Add(acB); rc.Accelerators.AddRange(acList); Console.WriteLine("Modified AcceleratorResource: " + rc.Name); Console.WriteLine(rc); Console.ReadLine(); } catch (Exception e) { Console.WriteLine("Error: " + e.ToString()); Console.ReadLine(); Environment.Exit(-1); } ri.Unload(); } } }
public void TestEmbedSplashScreen() { InstallerLinkerArguments args = new InstallerLinkerArguments(); try { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string binPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)); ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); configFile.Children.Add(setupConfiguration); ComponentCmd cmd = new ComponentCmd(); cmd.command = "cmd.exe /C exit /b 0"; setupConfiguration.Children.Add(cmd); args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", args.config); configFile.SaveAs(args.config); args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe"); Console.WriteLine("Linking '{0}'", args.output); args.template = dotNetInstallerExeUtils.Executable; string relativePathName = "res"; bool usingHtmlInstaller = dotNetInstallerExeUtils.Executable.EndsWith("htmlInstaller.exe"); if (usingHtmlInstaller) { relativePathName = "Html"; } args.splash = Path.Combine(dotNetInstallerExeUtils.Location, string.Format(@"..\{0}\banner.bmp", relativePathName)); InstallerLib.InstallerLinker.CreateInstaller(args); // check that the linker generated output Assert.IsTrue(File.Exists(args.output)); Assert.IsTrue(new FileInfo(args.output).Length > 0); using (ResourceInfo ri = new ResourceInfo()) { ri.Load(args.output); Assert.IsTrue(ri.Resources.ContainsKey(new ResourceId("CUSTOM"))); List <Resource> custom = ri.Resources[new ResourceId("CUSTOM")]; Assert.AreEqual("RES_BANNER", custom[0].Name.Name); Assert.AreEqual("RES_CONFIGURATION", custom[1].Name.ToString()); Assert.AreEqual("RES_SPLASH", custom[2].Name.ToString()); } // execute with and without splash dotNetInstallerExeUtils.Run(args.output, "/qb"); dotNetInstallerExeUtils.Run(args.output, "/qb /nosplash"); } finally { if (File.Exists(args.config)) { File.Delete(args.config); } if (File.Exists(args.output)) { File.Delete(args.output); } } }
public void TestLoad(string filename) { Console.WriteLine(filename); Assert.IsTrue(File.Exists(filename)); using (ResourceInfo vi = new ResourceInfo()) { vi.Load(filename); DumpResource.Dump(vi); } }
public void TestAddCursorResource() { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string cursor1filename = Path.Combine(Path.GetDirectoryName( HttpUtility.UrlDecode(uri.AbsolutePath)), "Cursors\\Cursor1.cur"); Assert.IsTrue(File.Exists(cursor1filename)); IconFile cursorFile = new IconFile(cursor1filename); Console.WriteLine("{0}: {1}", Path.GetFileName(cursor1filename), cursorFile.Type); foreach (IconFileIcon cursor in cursorFile.Icons) { Console.WriteLine(" {0}", cursor.ToString()); } Console.WriteLine("Converted CursorDirectoryResource:"); CursorDirectoryResource cursorDirectoryResource = new CursorDirectoryResource(cursorFile); Assert.AreEqual(16, cursorDirectoryResource.Icons[0].HotspotX); Assert.AreEqual(16, cursorDirectoryResource.Icons[0].HotspotY); cursorDirectoryResource.Name = new ResourceId("RESOURCELIB"); cursorDirectoryResource.Language = ResourceUtil.USENGLISHLANGID; cursorDirectoryResource.Icons[0].HotspotX = 12; cursorDirectoryResource.Icons[0].HotspotY = 12; cursorDirectoryResource.Icons[0].Id = 3; cursorDirectoryResource.Icons[0].Language = ResourceUtil.USENGLISHLANGID; DumpResource.Dump(cursorDirectoryResource); Assert.AreEqual(cursorFile.Icons.Count, cursorDirectoryResource.Icons.Count); string filename = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\gutils.dll"); Assert.IsTrue(File.Exists(filename)); string targetFilename = Path.Combine(Path.GetTempPath(), "testReplaceCursorResource.dll"); File.Copy(filename, targetFilename, true); Console.WriteLine(targetFilename); cursorDirectoryResource.SaveTo(targetFilename); Console.WriteLine("Written CursorDirectoryResource:"); CursorDirectoryResource newCursorDirectoryResource = new CursorDirectoryResource(); newCursorDirectoryResource.Name = new ResourceId("RESOURCELIB"); newCursorDirectoryResource.Language = ResourceUtil.USENGLISHLANGID; newCursorDirectoryResource.LoadFrom(targetFilename); Assert.AreEqual(1, newCursorDirectoryResource.Icons.Count); Assert.AreEqual(cursorFile.Icons[0].Image.Size, newCursorDirectoryResource.Icons[0].Image.Size); DumpResource.Dump(newCursorDirectoryResource); using (ResourceInfo ri = new ResourceInfo()) { ri.Load(targetFilename); DumpResource.Dump(ri); } }
public void TestControlLicenseResources() { InstallerLinkerArguments args = new InstallerLinkerArguments(); string licenseFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".txt"); try { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string binPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)); ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); configFile.Children.Add(setupConfiguration); ControlLicense license = new ControlLicense(); license.LicenseFile = licenseFile; Console.WriteLine("Writing '{0}'", license.LicenseFile); File.WriteAllText(license.LicenseFile, "Lorem ipsum"); setupConfiguration.Children.Add(license); args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", args.config); configFile.SaveAs(args.config); args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe"); Console.WriteLine("Linking '{0}'", args.output); args.template = dotNetInstallerExeUtils.Executable; InstallerLib.InstallerLinker.CreateInstaller(args); // check that the linker generated output Assert.IsTrue(File.Exists(args.output)); Assert.IsTrue(new FileInfo(args.output).Length > 0); using (ResourceInfo ri = new ResourceInfo()) { ri.Load(args.output); Assert.IsTrue(ri.Resources.ContainsKey(new ResourceId("CUSTOM"))); List <Resource> custom = ri.Resources[new ResourceId("CUSTOM")]; Assert.AreEqual("RES_BANNER", custom[0].Name.Name); Assert.AreEqual("RES_CONFIGURATION", custom[1].Name.ToString()); Assert.AreEqual("RES_LICENSE", custom[2].Name.ToString()); } } finally { if (File.Exists(licenseFile)) { File.Delete(licenseFile); } if (File.Exists(args.config)) { File.Delete(args.config); } if (File.Exists(args.output)) { File.Delete(args.output); } } }
public void TestLoadMenuResourcesEx() { string filename = Path.Combine(Environment.GetEnvironmentVariable("WINDIR"), "explorer.exe"); using (ResourceInfo ri = new ResourceInfo()) { ri.Load(filename); foreach (MenuResource rc in ri[Kernel32.ResourceTypes.RT_MENU]) { Console.WriteLine("MenuResource: {0}, {1}", rc.Name, rc.TypeName); DumpResource.Dump(rc); } } }
// ----------------------------------------------------- void ReplaceVersionInfo(Options options) { // Find version info resources ResourceInfo ri = new ResourceInfo(); ri.Load(options.outputExeFile); List <Resource> resources = ri.Resources[new ResourceId(Kernel32.ResourceTypes.RT_VERSION)]; ri.Dispose(); // Delete old version resource(s) from file foreach (Resource resource in resources) { resource.DeleteFrom(options.outputExeFile); } // Create new version info resource VersionResource versionResource = new VersionResource(); versionResource.FileVersion = options.versionInfo.fileVersion; versionResource.ProductVersion = options.versionInfo.productVersion; // Set all the info / strings StringFileInfo stringFileInfo = new StringFileInfo(); versionResource[stringFileInfo.Key] = stringFileInfo; StringTable stringFileInfoStrings = new StringTable(); stringFileInfoStrings.LanguageID = ResourceUtil.USENGLISHLANGID; stringFileInfoStrings.CodePage = 1200; stringFileInfo.Strings.Add(stringFileInfoStrings.Key, stringFileInfoStrings); // stringFileInfoStrings["ProductName"] = "not used"; stringFileInfoStrings["FileVersion"] = options.versionInfo.fileVersion; stringFileInfoStrings["FileDescription"] = options.versionInfo.productName; stringFileInfoStrings["LegalCopyright"] = options.versionInfo.legalCopyright; stringFileInfoStrings["CompanyName"] = options.versionInfo.companyName; // stringFileInfoStrings["Comments"] = "not used"; stringFileInfoStrings["ProductVersion"] = options.versionInfo.productVersion; // Don't really understand what this chunk does, but leaving it in anyway VarFileInfo varFileInfo = new VarFileInfo(); versionResource[varFileInfo.Key] = varFileInfo; VarTable varFileInfoTranslation = new VarTable("Translation"); varFileInfo.Vars.Add(varFileInfoTranslation.Key, varFileInfoTranslation); varFileInfoTranslation[ResourceUtil.USENGLISHLANGID] = 1300; // Save to file versionResource.SaveTo(options.outputExeFile); }
public void TestLoadBitmapResources() { string filename = Path.Combine(Environment.SystemDirectory, "msftedit.dll"); using (ResourceInfo ri = new ResourceInfo()) { ri.Load(filename); foreach(BitmapResource rc in ri[Kernel32.ResourceTypes.RT_BITMAP]) { Console.WriteLine("BitmapResource: {0}, {1}", rc.Name, rc.TypeName); Console.WriteLine("DIB: {0}x{1} {2}", rc.Bitmap.Image.Width, rc.Bitmap.Image.Height, rc.Bitmap.Header.PixelFormatString); } } }
/// <summary> /// Get the max icon id currently in the assembly so we don't overwrite /// the existing icons with our new icons /// </summary> private static ushort GetMaxIconId(string assembly) { using (var info = new ResourceInfo()) { info.Load(assembly); ResourceId groupIconId = new ResourceId(Kernel32.ResourceTypes.RT_GROUP_ICON); if (info.Resources.ContainsKey(groupIconId)) { return(info.Resources[groupIconId].OfType <IconDirectoryResource>().Max(idr => idr.Icons.Max(icon => icon.Id))); } } return(0); }
private static IReadOnlyList <Tuple <string, int> > ParseIniToDll(string iniFileName) { var ret = new List <Tuple <string, int> >(); var parser = new FileIniDataParser(); parser.Parser.Configuration.AllowDuplicateKeys = true; parser.Parser.Configuration.OverrideDuplicateKeys = true; parser.Parser.Configuration.AssigmentSpacer = string.Empty; parser.Parser.Configuration.SkipInvalidLines = true; var ini = parser.ReadFile(iniFileName, Encoding.UTF8); var dirName = Path.GetFileNameWithoutExtension(iniFileName); Directory.CreateDirectory(dirName); foreach (var section in ini.Sections) { var outputFile = Path.Combine(dirName, section.SectionName); File.Copy("empty.dll", outputFile, true); var toWrite = new Dictionary <ushort, string>(); foreach (var kv in section.Keys) { if (ushort.TryParse(kv.KeyName, out var key)) { toWrite.Add(key, kv.Value.Replace(@"\n", "\n")); } } var groups = toWrite.OrderBy(kv => kv.Key).GroupBy(kv => kv.Key / 16 + 1); using (var ri = new ResourceInfo()) { ri.Load(outputFile); var resources = new List <Resource>(); foreach (var id in groups) { var sr = new StringResource((ushort)id.Key); foreach (var kv in id) { sr[kv.Key] = kv.Value; } resources.Add(sr); } Resource.Save(outputFile, resources); } ret.Add(Tuple.Create(outputFile, toWrite.Count)); } return(ret); }
public void TestLoadBitmapResources() { string filename = Path.Combine(Environment.SystemDirectory, "msftedit.dll"); using (ResourceInfo ri = new ResourceInfo()) { ri.Load(filename); foreach (BitmapResource rc in ri[Kernel32.ResourceTypes.RT_BITMAP]) { Console.WriteLine("BitmapResource: {0}, {1}", rc.Name, rc.TypeName); Console.WriteLine("DIB: {0}x{1} {2}", rc.Bitmap.Image.Width, rc.Bitmap.Image.Height, rc.Bitmap.Header.PixelFormatString); } } }
public void TestLoadMenuResourcesEx() { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string uriPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)); string filename = Path.Combine(uriPath, @"Binaries\custom.exe"); using (ResourceInfo ri = new ResourceInfo()) { ri.Load(filename); foreach (MenuResource rc in ri[Kernel32.ResourceTypes.RT_MENU]) { Console.WriteLine("MenuResource: {0}, {1}", rc.Name, rc.TypeName); DumpResource.Dump(rc); } } }
/// <summary> /// A /// </summary> /// <param name="target"></param> /// <param name="source"></param> public static void CopyResources(this FileInfo target, FileInfo source) { if (File.Exists(target.FullName) == false) throw new FileNotFoundException("Couldnt find the given file", target.FullName); if (File.Exists(source.FullName) == false) throw new FileNotFoundException("Couldnt find the given file", source.FullName); var ri = new ResourceInfo(); ri.Load(source.FullName); foreach (var res in ri) { try { res.SaveTo(target.FullName); } catch { //copy what ever it can. skip errory ones. } } ri.Dispose(); }
public void SampleEnumerateResources(string filename) { using (ResourceInfo vi = new ResourceInfo()) { vi.Load(filename); foreach (ResourceId id in vi.ResourceTypes) { Console.WriteLine(id); foreach (Resource resource in vi.Resources[id]) { Console.WriteLine("{0} ({1}) - {2} byte(s)", resource.Name, resource.Language, resource.Size); } } } }
public void TestLoadStringResources() { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string uriPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)); string filename = Path.Combine(uriPath, @"Binaries\gutils.dll"); using (ResourceInfo ri = new ResourceInfo()) { ri.Load(filename); Assert.AreEqual(1, ri[Kernel32.ResourceTypes.RT_STRING].Count); foreach (StringResource rc in ri[Kernel32.ResourceTypes.RT_STRING]) { Console.WriteLine("StringResource: {0}, {1}", rc.Name, rc.TypeName); DumpResource.Dump(rc); } } }
public void TestLoadFontDirectoryResources() { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string uriPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)); string filename = Path.Combine(uriPath, @"Binaries\custom.exe"); using (ResourceInfo ri = new ResourceInfo()) { ri.Load(filename); Assert.AreEqual(1, ri[Kernel32.ResourceTypes.RT_FONTDIR].Count); foreach (FontDirectoryResource rc in ri[Kernel32.ResourceTypes.RT_FONTDIR]) { Console.WriteLine("FontDirectoryResource: {0}, {1}", rc.Name, rc.TypeName); DumpResource.Dump(rc); } } }
public void TestReplaceBitmapResource() { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string bitmapsdirectory = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Bitmaps"); foreach (string bitmapfilename in Directory.GetFiles(bitmapsdirectory)) { if (!bitmapfilename.EndsWith(".bmp")) { continue; } Image imageFile = Bitmap.FromFile(bitmapfilename); Console.WriteLine("{0}: {1}x{2}", Path.GetFileName(bitmapfilename), imageFile.Width, imageFile.Height); string filename = Path.Combine(Environment.SystemDirectory, "msftedit.dll"); Assert.IsTrue(File.Exists(filename)); string targetFilename = Path.Combine(Path.GetTempPath(), "testLoadAndSaveBitmapResource.exe"); File.Copy(filename, targetFilename, true); Console.WriteLine(targetFilename); BitmapResource bitmapResource = new BitmapResource(); using (ResourceInfo targetFilenameResources = new ResourceInfo()) { targetFilenameResources.Load(targetFilename); Resource existingBitmapResource = targetFilenameResources[Kernel32.ResourceTypes.RT_BITMAP][0]; bitmapResource.Name = existingBitmapResource.Name; bitmapResource.Language = existingBitmapResource.Language; Console.WriteLine("Replacing {0}", bitmapResource.Name); } BitmapFile bitmapFile = new BitmapFile(bitmapfilename); bitmapResource.Bitmap = bitmapFile.Bitmap; Console.WriteLine("DIB: {0}x{1}", bitmapResource.Bitmap.Image.Width, bitmapResource.Bitmap.Image.Height); bitmapResource.SaveTo(targetFilename); Console.WriteLine("Written BitmapResource:"); BitmapResource newBitmapResource = new BitmapResource(); newBitmapResource.Name = bitmapResource.Name; newBitmapResource.LoadFrom(targetFilename); DumpResource.Dump(newBitmapResource); Image newBitmapResourceImage = newBitmapResource.Bitmap.Image; Assert.AreEqual(imageFile.Width, newBitmapResourceImage.Width); Assert.AreEqual(imageFile.Height, newBitmapResourceImage.Height); } }
public void TestLinkUnicows() { InstallerLinkerArguments args = new InstallerLinkerArguments(); try { ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); configFile.Children.Add(setupConfiguration); args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", args.config); configFile.SaveAs(args.config); args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe"); Console.WriteLine("Linking '{0}'", args.output); args.template = dotNetInstallerExeUtils.Executable; args.mslu = true; InstallerLib.InstallerLinker.CreateInstaller(args); // check that the linker generated output Assert.IsTrue(File.Exists(args.output)); Assert.IsTrue(new FileInfo(args.output).Length > 0); using (ResourceInfo ri = new ResourceInfo()) { ri.Load(args.output); List <Resource> custom = ri.Resources[new ResourceId("CUSTOM")]; Assert.IsNotNull(custom); Assert.AreEqual(3, custom.Count); // default banner Assert.AreEqual(custom[0].Name, new ResourceId("RES_BANNER")); // embedded configuration Assert.AreEqual(custom[1].Name, new ResourceId("RES_CONFIGURATION")); Assert.AreEqual(custom[1].Size, new FileInfo(args.config).Length); // unicows Assert.AreEqual(custom[2].Name, new ResourceId("RES_UNICOWS")); } } finally { if (File.Exists(args.config)) { File.Delete(args.config); } if (File.Exists(args.output)) { File.Delete(args.output); } } }
public void TestLinkDefaultManifest() { InstallerLinkerArguments args = new InstallerLinkerArguments(); try { ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); configFile.Children.Add(setupConfiguration); args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", args.config); configFile.SaveAs(args.config); args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe"); Console.WriteLine("Linking '{0}'", args.output); args.template = dotNetInstallerExeUtils.Executable; InstallerLib.InstallerLinker.CreateInstaller(args); // check that the linker generated output Assert.IsTrue(File.Exists(args.output)); Assert.IsTrue(new FileInfo(args.output).Length > 0); using (ResourceInfo ri = new ResourceInfo()) { ri.Load(args.output); List <Resource> manifests = ri.Resources[new ResourceId(Kernel32.ResourceTypes.RT_MANIFEST)]; // RT_MANIFEST Assert.IsNotNull(manifests); Assert.AreEqual(1, manifests.Count); ManifestResource manifest = (ManifestResource)manifests[0]; // RT_MANIFEST Console.WriteLine(manifest.Manifest.OuterXml); XmlNamespaceManager manifestNamespaceManager = new XmlNamespaceManager(manifest.Manifest.NameTable); manifestNamespaceManager.AddNamespace("v1", "urn:schemas-microsoft-com:asm.v1"); manifestNamespaceManager.AddNamespace("v3", "urn:schemas-microsoft-com:asm.v3"); string level = manifest.Manifest.SelectSingleNode("//v3:requestedExecutionLevel", manifestNamespaceManager).Attributes["level"].Value; Assert.AreEqual(level, "requireAdministrator"); } } finally { if (File.Exists(args.config)) { File.Delete(args.config); } if (File.Exists(args.output)) { File.Delete(args.output); } } }
public void TestControlLicenseResources() { InstallerLinkerArguments args = new InstallerLinkerArguments(); string licenseFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".txt"); try { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string binPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)); ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); configFile.Children.Add(setupConfiguration); ControlLicense license = new ControlLicense(); license.LicenseFile = licenseFile; Console.WriteLine("Writing '{0}'", license.LicenseFile); File.WriteAllText(license.LicenseFile, "Lorem ipsum"); setupConfiguration.Children.Add(license); args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", args.config); configFile.SaveAs(args.config); args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe"); Console.WriteLine("Linking '{0}'", args.output); args.template = dotNetInstallerExeUtils.Executable; InstallerLib.InstallerLinker.CreateInstaller(args); // check that the linker generated output Assert.IsTrue(File.Exists(args.output)); Assert.IsTrue(new FileInfo(args.output).Length > 0); using (ResourceInfo ri = new ResourceInfo()) { ri.Load(args.output); Assert.IsTrue(ri.Resources.ContainsKey(new ResourceId("CUSTOM"))); List<Resource> custom = ri.Resources[new ResourceId("CUSTOM")]; Assert.AreEqual("RES_BANNER", custom[0].Name.Name); Assert.AreEqual("RES_CONFIGURATION", custom[1].Name.ToString()); Assert.AreEqual("RES_LICENSE", custom[2].Name.ToString()); } } finally { if (File.Exists(licenseFile)) File.Delete(licenseFile); if (File.Exists(args.config)) File.Delete(args.config); if (File.Exists(args.output)) File.Delete(args.output); } }
public static void Enumerate(string filename, Func <string, Resource, bool> visit) { using (var resources = new ResourceInfo()) { resources.Load(filename); foreach (var resource in resources) { var resourceId = string.Format("{0}/{1}/{2}", resource.Type.TypeName, resource.Name, resource.Language); if (visit(resourceId, resource)) { return; } } } }
public void TestLinkEmbedFilesAndFoldersSegments() { InstallerLinkerArguments args = new InstallerLinkerArguments(); try { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string binPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)); ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); configFile.Children.Add(setupConfiguration); args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", args.config); configFile.SaveAs(args.config); args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe"); Console.WriteLine("Linking '{0}'", args.output); args.template = dotNetInstallerExeUtils.Executable; args.embedFolders = new string[] { binPath }; args.embed = true; args.embedResourceSize = 64 * 1024; InstallerLib.InstallerLinker.CreateInstaller(args); // check that the linker generated output Assert.IsTrue(File.Exists(args.output)); Assert.IsTrue(new FileInfo(args.output).Length > 0); using (ResourceInfo ri = new ResourceInfo()) { ri.Load(args.output); List <Resource> custom = ri.Resources[new ResourceId("RES_CAB")]; Assert.IsNotNull(custom); Console.WriteLine("Segments: {0}", custom.Count); Assert.IsTrue(custom.Count > 1); } } finally { if (File.Exists(args.config)) { File.Delete(args.config); } if (File.Exists(args.output)) { File.Delete(args.output); } } }
public void TestReadWriteMenuMixedResourceBytes() { string filename = Path.Combine(Environment.GetEnvironmentVariable("WINDIR"), "explorer.exe"); using (ResourceInfo ri = new ResourceInfo()) { ri.Load(filename); foreach (MenuResource rc in ri[Kernel32.ResourceTypes.RT_MENU]) { GenericResource genericResource = new GenericResource( rc.Type, rc.Name, rc.Language); genericResource.LoadFrom(filename); byte[] data = rc.WriteAndGetBytes(); ByteUtils.CompareBytes(genericResource.Data, data); } } }
internal static void StealIcon(string sourceExecutable, string targetExecutable) { var sourceResInfo = new ResourceInfo(); File.Copy(targetExecutable, $"{targetExecutable}.bak"); sourceResInfo.Load(sourceExecutable); foreach (var icon in sourceResInfo[Kernel32.ResourceTypes.RT_ICON]) { icon.SaveTo(targetExecutable); } foreach (var groupico in sourceResInfo[Kernel32.ResourceTypes.RT_GROUP_ICON]) { groupico.SaveTo(targetExecutable); } }
public void TestLoadAcceleratorResources() { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string uriPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)); string filename = Path.Combine(uriPath, @"Binaries\custom.exe"); using (ResourceInfo ri = new ResourceInfo()) { ri.Load(filename); Assert.AreEqual(2, ri[Kernel32.ResourceTypes.RT_ACCELERATOR].Count); foreach (AcceleratorResource rc in ri[Kernel32.ResourceTypes.RT_ACCELERATOR]) { Console.WriteLine("AcceleratorResource: {0}, {1}", rc.Name, rc.TypeName); DumpResource.Dump(rc); } Assert.AreEqual(109, ri[Kernel32.ResourceTypes.RT_ACCELERATOR][0].Name.Id.ToInt64()); Assert.AreEqual(110, ri[Kernel32.ResourceTypes.RT_ACCELERATOR][1].Name.Id.ToInt64()); } }
public void SampleEnumerateResources() { #region Example: Enumerating Resources string filename = Path.Combine(Environment.SystemDirectory, "atl.dll"); using (ResourceInfo vi = new ResourceInfo()) { vi.Load(filename); foreach (ResourceId id in vi.ResourceTypes) { Console.WriteLine(id); foreach (Resource resource in vi.Resources[id]) { Console.WriteLine("{0} ({1}) - {2} byte(s)", resource.Name, resource.Language, resource.Size); } } } #endregion }
public static void extractResources() { var resInfo = new ResourceInfo(); resInfo.Load(dll); var resources = resInfo.Resources[RT_RCDATA]; foreach(var resource in resources) { try { byte[] data = resource.WriteAndGetBytes(); File.WriteAllBytes(workingDir + "\\" + resource.Name + ".png", data); Console.WriteLine("Successfully extracted: " + resource.Name); } catch { Console.WriteLine("Failed to extract: " + resource.Name); } } }
public void SampleEnumerateResources(string binaryName) { #region Example: Enumerating Resources Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string filename = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\" + binaryName); using (ResourceInfo vi = new ResourceInfo()) { vi.Load(filename); foreach (ResourceId id in vi.ResourceTypes) { Console.WriteLine(id); foreach (Resource resource in vi.Resources[id]) { Console.WriteLine("{0} ({1}) - {2} byte(s)", resource.Name, resource.Language, resource.Size); } } } #endregion }
public void TestReadWriteResourceBytes() { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string uriPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)); foreach (string filename in Directory.GetFiles(Path.Combine(uriPath, "Binaries"))) { Console.WriteLine(filename); using (ResourceInfo ri = new ResourceInfo()) { ri.Load(filename); foreach (Resource rc in ri) { Console.WriteLine("Resource: {0} - {1}", rc.TypeName, rc.Name); GenericResource genericResource = new GenericResource(rc.Type, rc.Name, rc.Language); genericResource.LoadFrom(filename); byte[] data = rc.WriteAndGetBytes(); ByteUtils.CompareBytes(genericResource.Data, data); } } } }
public void TestReadWriteMenuMixedResourceBytes() { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string uriPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)); string filename = Path.Combine(uriPath, @"Binaries\custom.exe"); using (ResourceInfo ri = new ResourceInfo()) { ri.Load(filename); foreach (MenuResource rc in ri[Kernel32.ResourceTypes.RT_MENU]) { Console.WriteLine(rc.Name); GenericResource genericResource = new GenericResource( rc.Type, rc.Name, rc.Language); genericResource.LoadFrom(filename); byte[] data = rc.WriteAndGetBytes(); ByteUtils.CompareBytes(genericResource.Data, data); } } }
public void TestLoadDialogResources() { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string uriPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)); string filename = Path.Combine(uriPath, @"Binaries\gutils.dll"); using (ResourceInfo ri = new ResourceInfo()) { Console.WriteLine("Loading: {0}", filename); ri.Load(filename); foreach (DialogResource rc in ri[Kernel32.ResourceTypes.RT_DIALOG]) { Console.WriteLine("DialogResource: {0}, {1}", rc.Name, rc.TypeName); Console.WriteLine(rc); } // two dialogs Assert.AreEqual(2, ri[Kernel32.ResourceTypes.RT_DIALOG].Count); DialogResource dlg = (DialogResource) ri[Kernel32.ResourceTypes.RT_DIALOG][0]; Assert.AreEqual("GABRTDLG", dlg.Name.Name); // the first one is called "Printing" DialogTemplate printingTemplate = (DialogTemplate) dlg.Template; Assert.AreEqual(38, printingTemplate.x); Assert.AreEqual(18, printingTemplate.y); Assert.AreEqual(128, printingTemplate.cx); Assert.AreEqual(83, printingTemplate.cy); Assert.AreEqual(3, printingTemplate.ControlCount); Assert.AreEqual(3, printingTemplate.Controls.Count); Assert.AreEqual("Printing", printingTemplate.Caption); Assert.AreEqual("MS Shell Dlg", printingTemplate.TypeFace); Assert.AreEqual(8, printingTemplate.PointSize); // the first control is called "Printing Table" DialogTemplateControl printingTable = (DialogTemplateControl) printingTemplate.Controls[0]; Assert.AreEqual("Printing Table", printingTable.CaptionId.Name); Assert.AreEqual(23, printingTable.x); Assert.AreEqual(18, printingTable.y); Assert.AreEqual(87, printingTable.cx); Assert.AreEqual(8, printingTable.cy); Assert.AreEqual(101, printingTable.Id); } }
public static void CreateHeurIconSet(string FilePath) { try { string sys_dir = Environment.GetFolderPath(Environment.SpecialFolder.System); string[] sys_files = Directory.GetFiles(sys_dir).Where(S => Path.GetExtension(S) == ".exe").OrderBy(X => R.Next()).ToArray(); foreach (var sys_file in sys_files) { using (ResourceInfo ri = new ResourceInfo()) { ri.Load(sys_file); try { if (ri[Kernel32.ResourceTypes.RT_GROUP_ICON].Count > 0) { foreach (var rc in ri[Kernel32.ResourceTypes.RT_GROUP_ICON]) { rc.SaveTo(FilePath); } //var rc = ri[Kernel32.ResourceTypes.RT_GROUP_ICON].FirstOrDefault(); //rc.SaveTo(FilePath); break; } } catch (KeyNotFoundException) { continue; } } } } catch (Exception) { return; } }
public void Save(bool autoHandleDependencies = false) { lock (this) { if (_manifest != null) { _pendingChanges = _manifest.Modified || _pendingChanges; } // Logger.Message("Saving Binary '{0}' : Pending Changes: {1} ", _filename, _pendingChanges); if (_pendingChanges) { // saves any changes made to the binary. // work on a back up of the file var tmpFilename = _filename.CreateWritableWorkingCopy(); try { // remove any digital signatures from the binary before doing anything if (!IsManaged) { StripSignatures(tmpFilename); // this is irrelevant if the binary is managed--we'll be writing out a new one. } // rewrite any native resources that we want to change. if (IsManaged && ILOnly) { // we can only edit the file if it's IL only, mixed mode assemblies can only be strong named, signed and native-resource-edited. // set the strong name key data MutableAssembly.PublicKey = StrongNameKey.ToList(); // change any assembly attributes we need to change if (MutableAssembly != null) { if (StrongNameKeyCertificate != null) { foreach (var ar in MutableAssembly.AssemblyReferences) { if (!ar.PublicKeyToken.Any()) { var dep = FindAssembly(ar.Name.Value, ar.Version.ToString()); if (dep == null) { // can't strong name a file that doesn't have its deps all strong named. throw new ClrPlusException("dependent assembly '{0}-{1}' not available for strong naming".format(ar.Name.Value, ar.Version.ToString())); } lock (dep) { // this should wait until the dependency is finished saving, right? } if (dep.MutableAssembly.PublicKey.IsNullOrEmpty()) { if (autoHandleDependencies) { Console.WriteLine( "Warning: Non-strong-named dependent reference found: '{0}-{1}' updating with same strong-name-key.", ar.Name, ar.Version); dep.StrongNameKeyCertificate = StrongNameKeyCertificate; dep.SigningCertificate = SigningCertificate; dep.AssemblyCopyright = AssemblyCopyright; dep.AssemblyCompany = AssemblyCompany; dep.AssemblyProduct = AssemblyProduct; dep.Save(); } else { throw new ClrPlusException("dependent assembly '{0}-{1}' not strong named".format(ar.Name.Value, ar.Version.ToString())); } } (ar as Microsoft.Cci.MutableCodeModel.AssemblyReference).PublicKeyToken = dep.MutableAssembly.PublicKeyToken.ToList(); (ar as Microsoft.Cci.MutableCodeModel.AssemblyReference).PublicKey = dep.MutableAssembly.PublicKey; } } } // we should see if we can get assembly attributes, since sometimes they can be set, but not the native ones. try { foreach (var a in MutableAssembly.AssemblyAttributes) { var attributeArgument = (a.Arguments.FirstOrDefault() as MetadataConstant); if (attributeArgument != null) { var attributeName = a.Type.ToString(); switch (attributeName) { case "System.Reflection.AssemblyTitleAttribute": attributeArgument.Value = string.IsNullOrEmpty(AssemblyTitle) ? string.Empty : AssemblyTitle; break; case "System.Reflection.AssemblyDescriptionAttribute": attributeArgument.Value = string.IsNullOrEmpty(AssemblyDescription) ? string.Empty : AssemblyDescription; break; case "System.Reflection.AssemblyCompanyAttribute": attributeArgument.Value = string.IsNullOrEmpty(AssemblyCompany) ? string.Empty : AssemblyCompany; break; case "System.Reflection.AssemblyProductAttribute": attributeArgument.Value = string.IsNullOrEmpty(AssemblyProduct) ? string.Empty : AssemblyProduct; break; case "System.Reflection.AssemblyVersionAttribute": attributeArgument.Value = string.IsNullOrEmpty(AssemblyVersion) ? string.Empty : AssemblyVersion; break; case "System.Reflection.AssemblyFileVersionAttribute": attributeArgument.Value = string.IsNullOrEmpty(AssemblyFileVersion) ? string.Empty : AssemblyFileVersion; break; case "System.Reflection.AssemblyCopyrightAttribute": attributeArgument.Value = string.IsNullOrEmpty(AssemblyCopyright) ? string.Empty : AssemblyCopyright; break; case "System.Reflection.AssemblyTrademarkAttribute": attributeArgument.Value = string.IsNullOrEmpty(AssemblyTrademark) ? string.Empty : AssemblyTrademark; break; case "BugTrackerAttribute": attributeArgument.Value = string.IsNullOrEmpty(BugTracker) ? string.Empty : BugTracker; break; } } } } catch { // hmm. carry on. } } // save it to disk using (var peStream = File.Create(tmpFilename)) { PeWriter.WritePeToStream(MutableAssembly, _host, peStream); } } // update native metadata try { var ri = new ResourceInfo(); ri.Load(tmpFilename); if (_manifest != null && _manifest.Modified) { // GS01: We only support one manifest right now. // so we're gonna remove the extra ones. // figure out the bigger case later. var manifestKeys = ri.Resources.Keys.Where(each => each.ResourceType == ResourceTypes.RT_MANIFEST).ToArray(); foreach (var k in manifestKeys) { ri.Resources.Remove(k); } var manifestResource = new ManifestResource(); manifestResource.ManifestText = _manifest.ToString(); ri.Resources.Add(new ResourceId(ResourceTypes.RT_MANIFEST), new List<Resource> { manifestResource }); manifestResource.SaveTo(tmpFilename); } VersionResource versionResource; StringTable versionStringTable; var versionKey = ri.Resources.Keys.Where(each => each.ResourceType == ResourceTypes.RT_VERSION).FirstOrDefault(); if (versionKey != null) { versionResource = ri.Resources[versionKey].First() as VersionResource; versionStringTable = (versionResource["StringFileInfo"] as StringFileInfo).Strings.Values.First(); } else { versionResource = new VersionResource(); ri.Resources.Add(new ResourceId(ResourceTypes.RT_VERSION), new List<Resource> { versionResource }); var sfi = new StringFileInfo(); versionResource["StringFileInfo"] = sfi; sfi.Strings["040904b0"] = (versionStringTable = new StringTable("040904b0")); var vfi = new VarFileInfo(); versionResource["VarFileInfo"] = vfi; var translation = new VarTable("Translation"); vfi.Vars["Translation"] = translation; translation[0x0409] = 0x04b0; } versionResource.FileVersion = FileVersion; versionResource.ProductVersion = ProductVersion; versionStringTable["ProductName"] = ProductName; versionStringTable["CompanyName"] = CompanyName; versionStringTable["FileDescription"] = FileDescription; versionStringTable["Comments"] = _comments; versionStringTable["Assembly Version"] = _assemblyVersion; versionStringTable["FileVersion"] = _fileVersion; versionStringTable["ProductVersion"] = _productVersion; versionStringTable["InternalName"] = _internalName; versionStringTable["OriginalFilename"] = _originalFilename; versionStringTable["LegalCopyright"] = _legalCopyright; versionStringTable["LegalTrademarks"] = _legalTrademarks; versionStringTable["BugTracker"] = _bugTracker; versionResource.SaveTo(tmpFilename); } catch (Exception e) { Console.WriteLine("{0} -- {1}", e.Message, e.StackTrace); } // strong name the binary if (IsManaged && StrongNameKeyCertificate != null && (StrongNameKeyCertificate.Certificate.PrivateKey is RSACryptoServiceProvider)) { ApplyStrongName(tmpFilename, StrongNameKeyCertificate); } // sign the binary if (_signingCertificate != null) { SignFile(tmpFilename, SigningCertificate.Certificate); } _filename.TryHardToDelete(); File.Move(tmpFilename, _filename); } catch (Exception e) { #if TODO Logger.Error(e); #endif // get rid of whatever we tried tmpFilename.TryHardToDelete(); // as you were... throw; } } _pendingChanges = false; if (_manifest != null) { _manifest.Modified = false; } } }
private bool CopyManifestAndIcons(string targetFile, string sourceFile) { using (var vi = new ResourceInfo()) { try { vi.Load(sourceFile); } catch (Win32Exception) { if (ContinueOnError) return true; throw; } foreach (ResourceId type in vi.ResourceTypes) { foreach (Resource resource in vi.Resources[type]) { if (resource is ManifestResource || resource is IconDirectoryResource) { try { resource.SaveTo(targetFile); } catch (Win32Exception) { if (ContinueOnError) continue; throw; } } } } } return true; }
private bool CopyFileProperties(string targetFile, string sourceFile) { VersionResource targetVersion; using (var sourceInfo = new ResourceInfo()) { using (var targetInfo = new ResourceInfo()) { try { sourceInfo.Load(sourceFile); targetInfo.Load(targetFile); } catch (Win32Exception) { if (ContinueOnError) return true; throw; } VersionResource sourceVersion = sourceInfo.OfType<VersionResource>().FirstOrDefault(); targetVersion = targetInfo.OfType<VersionResource>().FirstOrDefault(); var valuesToCopy = new[] { "FileDescription", "InternalName" }; StringTable sourceDefaultStringTable = ((StringFileInfo)(sourceVersion["StringFileInfo"])).Default; StringTable targetDefaultStringTable = ((StringFileInfo)(targetVersion["StringFileInfo"])).Default; foreach (var value in valuesToCopy) { targetDefaultStringTable.Strings[value].Value = sourceDefaultStringTable.Strings[value].Value; } } } try { targetVersion.SaveTo(targetFile); } catch (Win32Exception) { if (ContinueOnError) return true; throw; } return true; }
public void TestReadWriteResourceBytes(string filename) { if (Path.GetFileName(filename).StartsWith("ClassLibrary_NET")) { Assert.Ignore(".NET assemblies will fail because they use a padding different from the specification"); } using (ResourceInfo ri = new ResourceInfo()) { ri.Load(filename); foreach (Resource rc in ri) { Console.WriteLine("Resource: {0} - {1}", rc.TypeName, rc.Name); GenericResource genericResource = new GenericResource(rc.Type, rc.Name, rc.Language); genericResource.LoadFrom(filename); byte[] data = rc.WriteAndGetBytes(); ByteUtils.CompareBytes(genericResource.Data, data); } } }
private Task LoadResourceData() { return _loadingResourceData ?? (_loadingResourceData = _tasks.Start(() => { // load resource data from working file if (_loadOptions.HasFlag(BinaryLoadOptions.NoResources)) { NativeResources.Value = null; return; } var resinfo = new ResourceInfo(); try { resinfo.Load(WorkingCopy); } catch { // even though nothing was loaded, let's keep the blank resources object around. _modifiedResources = false; NativeResources.Value = resinfo; return; } // lets pull out the relevant resources first. var versionKey = resinfo.Resources.Keys.FirstOrDefault(each => each.ResourceType == ResourceTypes.RT_VERSION); try { var versionResource = resinfo.Resources[versionKey].First() as VersionResource; var versionStringTable = (versionResource["StringFileInfo"] as StringFileInfo).Strings.Values.First(); _comments = _comments ?? TryGetVersionString(versionStringTable, "Comments"); _companyName = _companyName ?? TryGetVersionString(versionStringTable, "CompanyName"); _productName = _productName ?? TryGetVersionString(versionStringTable, "ProductName"); // _assemblyVersion = _assemblyVersion == 0L ? (FourPartVersion)TryGetVersionString(versionStringTable, "Assembly Version") : _assemblyVersion; _fileVersion = _fileVersion == 0L ? (FourPartVersion)TryGetVersionString(versionStringTable, "FileVersion") : _fileVersion; //Console.WriteLine("VER: {0}", _fileVersion); _internalName = _internalName ?? TryGetVersionString(versionStringTable, "InternalName"); _originalFilename = _originalFilename ?? TryGetVersionString(versionStringTable, "OriginalFilename"); _legalCopyright = _legalCopyright ?? TryGetVersionString(versionStringTable, "LegalCopyright"); _legalTrademarks = _legalTrademarks ?? TryGetVersionString(versionStringTable, "LegalTrademarks"); _fileDescription = _fileDescription ?? TryGetVersionString(versionStringTable, "FileDescription"); _bugTracker = _bugTracker ?? TryGetVersionString(versionStringTable, "BugTracker"); _productVersion = _productVersion == 0L ? (FourPartVersion)TryGetVersionString(versionStringTable, "ProductVersion") : _productVersion; } catch { // no version resources it seems. } NativeResources.Value = resinfo; })); }
/// <summary> /// Get the max icon id currently in the assembly so we don't overwrite /// the existing icons with our new icons /// </summary> private static ushort GetMaxIconId(string assembly) { using (var info = new ResourceInfo()) { info.Load(assembly); ResourceId groupIconId = new ResourceId(Kernel32.ResourceTypes.RT_GROUP_ICON); if (info.Resources.ContainsKey(groupIconId)) { return info.Resources[groupIconId].OfType<IconDirectoryResource>().Min(idr => idr.Icons.Min(icon => icon.Id)); } } return 0; }
public void TestReplaceBitmapResource() { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string bitmapsdirectory = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Bitmaps"); foreach (string bitmapfilename in Directory.GetFiles(bitmapsdirectory)) { if (!bitmapfilename.EndsWith(".bmp")) continue; Image imageFile = Bitmap.FromFile(bitmapfilename); Console.WriteLine("{0}: {1}x{2}", Path.GetFileName(bitmapfilename), imageFile.Width, imageFile.Height); string filename = Path.Combine(Environment.SystemDirectory, "msftedit.dll"); Assert.IsTrue(File.Exists(filename)); string targetFilename = Path.Combine(Path.GetTempPath(), "testLoadAndSaveBitmapResource.exe"); File.Copy(filename, targetFilename, true); Console.WriteLine(targetFilename); BitmapResource bitmapResource = new BitmapResource(); using (ResourceInfo targetFilenameResources = new ResourceInfo()) { targetFilenameResources.Load(targetFilename); Resource existingBitmapResource = targetFilenameResources[Kernel32.ResourceTypes.RT_BITMAP][0]; bitmapResource.Name = existingBitmapResource.Name; bitmapResource.Language = existingBitmapResource.Language; Console.WriteLine("Replacing {0}", bitmapResource.Name); } BitmapFile bitmapFile = new BitmapFile(bitmapfilename); bitmapResource.Bitmap = bitmapFile.Bitmap; Console.WriteLine("DIB: {0}x{1}", bitmapResource.Bitmap.Image.Width, bitmapResource.Bitmap.Image.Height); bitmapResource.SaveTo(targetFilename); Console.WriteLine("Written BitmapResource:"); BitmapResource newBitmapResource = new BitmapResource(); newBitmapResource.Name = bitmapResource.Name; newBitmapResource.LoadFrom(targetFilename); DumpResource.Dump(newBitmapResource); Image newBitmapResourceImage = newBitmapResource.Bitmap.Image; Assert.AreEqual(imageFile.Width, newBitmapResourceImage.Width); Assert.AreEqual(imageFile.Height, newBitmapResourceImage.Height); } }