Exemplo n.º 1
0
        private void WriteAssembly(string filename)
        {
            try
            {
                VersionResource versionResource = new VersionResource();
                versionResource.LoadFrom(filename);

                versionResource.FileVersion    = txtFileVersion.Text;
                versionResource.ProductVersion = txtProductVersion.Text;
                versionResource.Language       = 0;

                StringFileInfo stringFileInfo = (StringFileInfo)versionResource["StringFileInfo"];
                stringFileInfo["ProductName"]      = txtProduct.Text;
                stringFileInfo["FileDescription"]  = txtDescription.Text;
                stringFileInfo["CompanyName"]      = txtCompany.Text;
                stringFileInfo["LegalCopyright"]   = txtCopyright.Text;
                stringFileInfo["LegalTrademarks"]  = txtTrademarks.Text;
                stringFileInfo["Assembly Version"] = versionResource.ProductVersion;
                stringFileInfo["InternalName"]     = txtOriginalFilename.Text;
                stringFileInfo["OriginalFilename"] = txtOriginalFilename.Text;
                stringFileInfo["ProductVersion"]   = versionResource.ProductVersion;
                stringFileInfo["FileVersion"]      = versionResource.FileVersion;

                versionResource.SaveTo(filename);
            }
            catch (Exception ex)
            {
                throw new ArgumentException("Assembly: " + ex.Message);
            }
        }
Exemplo n.º 2
0
        public void TestDeepCopyBytes()
        {
            string filename = Path.Combine(Environment.SystemDirectory, "atl.dll");

            Assert.IsTrue(File.Exists(filename));
            VersionResource existingVersionResource = new VersionResource();

            existingVersionResource.Language = ResourceUtil.USENGLISHLANGID;
            Console.WriteLine("Loading {0}", filename);
            existingVersionResource.LoadFrom(filename);
            DumpResource.Dump(existingVersionResource);

            VersionResource versionResource = new VersionResource();

            versionResource.FileVersion    = existingVersionResource.FileVersion;
            versionResource.ProductVersion = existingVersionResource.ProductVersion;

            StringFileInfo existingVersionResourceStringFileInfo = (StringFileInfo)existingVersionResource["StringFileInfo"];
            VarFileInfo    existingVersionResourceVarFileInfo    = (VarFileInfo)existingVersionResource["VarFileInfo"];

            // copy string resources, data only
            StringFileInfo stringFileInfo = new StringFileInfo();

            versionResource["StringFileInfo"] = stringFileInfo;
            {
                Dictionary <string, StringTable> .Enumerator enumerator = existingVersionResourceStringFileInfo.Strings.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    StringTable stringTable = new StringTable(enumerator.Current.Key);
                    stringFileInfo.Strings.Add(enumerator.Current.Key, stringTable);
                    Dictionary <string, StringTableEntry> .Enumerator resourceEnumerator = enumerator.Current.Value.Strings.GetEnumerator();
                    while (resourceEnumerator.MoveNext())
                    {
                        StringTableEntry stringResource = new StringTableEntry(resourceEnumerator.Current.Key);
                        stringResource.Value = resourceEnumerator.Current.Value.Value;
                        stringTable.Strings.Add(resourceEnumerator.Current.Key, stringResource);
                    }
                }
            }

            // copy var resources, data only
            VarFileInfo varFileInfo = new VarFileInfo();

            versionResource["VarFileInfo"] = varFileInfo;
            {
                Dictionary <string, VarTable> .Enumerator enumerator = existingVersionResourceVarFileInfo.Vars.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    VarTable varTable = new VarTable(enumerator.Current.Key);
                    varFileInfo.Vars.Add(enumerator.Current.Key, varTable);
                    Dictionary <UInt16, UInt16> .Enumerator translationEnumerator = enumerator.Current.Value.Languages.GetEnumerator();
                    while (translationEnumerator.MoveNext())
                    {
                        varTable.Languages.Add(translationEnumerator.Current.Key, translationEnumerator.Current.Value);
                    }
                }
            }

            ByteUtils.CompareBytes(existingVersionResource.WriteAndGetBytes(), versionResource.WriteAndGetBytes());
        }
Exemplo n.º 3
0
        private void Assembly(string kek)
        {
            VersionResource vr = new VersionResource();

            vr.LoadFrom(kek);

            vr.FileVersion    = fileverBox.Text;
            vr.ProductVersion = proverBox.Text;
            vr.Language       = 0;

            StringFileInfo Sfi = (StringFileInfo)vr["StringFileInfo"];

            Sfi["ProductName"]      = proBox.Text;
            Sfi["FileDescription"]  = desBox.Text;
            Sfi["CompanyName"]      = comBox.Text;
            Sfi["LegalCopyright"]   = copyBox.Text;
            Sfi["LegalTrademarks"]  = tradeBox.Text;
            Sfi["Assembly Version"] = vr.ProductVersion;
            Sfi["InternalName"]     = oriBox.Text;
            Sfi["OriginalFilename"] = oriBox.Text;
            Sfi["ProductVersion"]   = vr.ProductVersion;
            Sfi["FileVersion"]      = vr.ProductVersion;

            vr.SaveTo(kek);
        }
        private IDirectory BuildInMemoryDirectoryWithTestFiles(string filesInformation)
        {
            var directory  = new InMemoryDirectory();
            var filesArray = filesInformation.Split('|');

            foreach (var file in filesArray)
            {
                var pathSegments = PathUtils.SplitPathIntoSegments(file);

                var    fileName = pathSegments[pathSegments.Length - 1];
                string dir      = string.Empty;

                if (pathSegments.Length > 1)
                {
                    for (int i = 0; i < pathSegments.Length - 1; i++)
                    {
                        dir = dir + "/" + pathSegments[i];
                    }
                }

                var       fileContents = Guid.NewGuid();
                IFileInfo fileInfo     = new StringFileInfo(fileContents.ToString(), fileName);
                directory.AddFile(dir, fileInfo);
            }

            return(directory);
        }
Exemplo n.º 5
0
        public void TestLoadAndSaveVersionResource(string binaryName)
        {
            Uri    uri      = new Uri(Assembly.GetExecutingAssembly().CodeBase);
            string filename = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\" + binaryName);

            Assert.IsTrue(File.Exists(filename));

            VersionResource versionResource = new VersionResource();

            versionResource.Language = ResourceUtil.USENGLISHLANGID;
            versionResource.LoadFrom(filename);
            DumpResource.Dump(versionResource);

            versionResource.FileVersion    = "1.2.3.4";
            versionResource.ProductVersion = "5.6.7.8";
            versionResource.FileFlags      = 0x2 | 0x8; // private and prerelease

            StringFileInfo stringFileInfo = (StringFileInfo)versionResource["StringFileInfo"];

            stringFileInfo["Comments"] = string.Format("{0}\0", Guid.NewGuid());
            stringFileInfo["NewValue"] = string.Format("{0}\0", Guid.NewGuid());

            VarFileInfo varFileInfo = (VarFileInfo)versionResource["VarFileInfo"];

            varFileInfo[ResourceUtil.USENGLISHLANGID] = 1300;

            string targetFilename = Path.Combine(Path.GetTempPath(), "test.dll");

            File.Copy(filename, targetFilename, true);
            Console.WriteLine(targetFilename);
            versionResource.SaveTo(targetFilename);

            VersionResource newVersionResource = new VersionResource();

            newVersionResource.Language = ResourceUtil.USENGLISHLANGID;
            newVersionResource.LoadFrom(targetFilename);
            DumpResource.Dump(versionResource);

            AssertOneVersionResource(targetFilename);
            Assert.AreEqual(newVersionResource.FileVersion, versionResource.FileVersion);
            Assert.AreEqual(newVersionResource.ProductVersion, versionResource.ProductVersion);
            Assert.AreEqual(newVersionResource.FileFlags, versionResource.FileFlags);

            StringFileInfo testedStringFileInfo = (StringFileInfo)newVersionResource["StringFileInfo"];

            foreach (KeyValuePair <string, StringTableEntry> stringResource in testedStringFileInfo.Default.Strings)
            {
                Console.WriteLine("{0} = {1}", stringResource.Value.Key, stringResource.Value.StringValue);
                Assert.AreEqual(stringResource.Value.Value, stringFileInfo[stringResource.Key]);
            }

            VarFileInfo newVarFileInfo = (VarFileInfo)newVersionResource["VarFileInfo"];

            foreach (KeyValuePair <UInt16, UInt16> varResource in newVarFileInfo.Default.Languages)
            {
                Console.WriteLine("{0} = {1}", varResource.Key, varResource.Value);
                Assert.AreEqual(varResource.Value, varFileInfo[varResource.Key]);
            }
        }
Exemplo n.º 6
0
 internal VersionInfo(VersionResource versionResource, uint languageId, FixedFileInfo fixedInfo, StringFileInfo stringInfo, VarFileInfo varInfo)
 {
     resource = versionResource;
     language_id = languageId;
     fixed_file_info = fixedInfo;
     string_file_info = stringInfo;
     var_file_info = varInfo;
 }
        public void TestDeleteAndSaveVersionResource(string binaryName, int language)
        {
            Uri    uri      = new Uri(Assembly.GetExecutingAssembly().CodeBase);
            string filename = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\" + binaryName);

            Assert.IsTrue(File.Exists(filename));
            string targetFilename = Path.Combine(Path.GetTempPath(), "testDeleteAndSaveVersionResource.dll");

            File.Copy(filename, targetFilename, true);
            Console.WriteLine(targetFilename);
            VersionResource existingVersionResource = new VersionResource();

            existingVersionResource.Language = (ushort)language;
            existingVersionResource.DeleteFrom(targetFilename);

            VersionResource versionResource = new VersionResource();

            versionResource.FileVersion    = "1.2.3.4";
            versionResource.ProductVersion = "4.5.6.7";

            StringFileInfo stringFileInfo = new StringFileInfo();

            versionResource[stringFileInfo.Key] = stringFileInfo;
            StringTable stringFileInfoStrings = new StringTable(); // "040904b0"

            stringFileInfoStrings.LanguageID = (ushort)language;
            stringFileInfoStrings.CodePage   = 1200;
            Assert.AreEqual(language, stringFileInfoStrings.LanguageID);
            Assert.AreEqual(1200, stringFileInfoStrings.CodePage);
            stringFileInfo.Strings.Add(stringFileInfoStrings.Key, stringFileInfoStrings);
            stringFileInfoStrings["ProductName"]     = "ResourceLib";
            stringFileInfoStrings["FileDescription"] = "File updated by ResourceLib\0";
            stringFileInfoStrings["CompanyName"]     = "Vestris Inc.";
            stringFileInfoStrings["LegalCopyright"]  = "All Rights Reserved\0";
            stringFileInfoStrings["EmptyValue"]      = "";
            stringFileInfoStrings["Comments"]        = string.Format("{0}\0", Guid.NewGuid());
            stringFileInfoStrings["ProductVersion"]  = string.Format("{0}\0", versionResource.ProductVersion);

            VarFileInfo varFileInfo = new VarFileInfo();

            versionResource[varFileInfo.Key] = varFileInfo;
            VarTable varFileInfoTranslation = new VarTable("Translation");

            varFileInfo.Vars.Add(varFileInfoTranslation.Key, varFileInfoTranslation);
            varFileInfoTranslation[ResourceUtil.USENGLISHLANGID] = 1300;

            versionResource.SaveTo(targetFilename);
            Console.WriteLine("Reloading {0}", targetFilename);

            VersionResource newVersionResource = new VersionResource();

            newVersionResource.LoadFrom(targetFilename);
            DumpResource.Dump(newVersionResource);

            AssertOneVersionResource(targetFilename);
            Assert.AreEqual(newVersionResource.FileVersion, versionResource.FileVersion);
            Assert.AreEqual(newVersionResource.ProductVersion, versionResource.ProductVersion);
        }
Exemplo n.º 8
0
        public void TestDeleteAndSaveVersionResource()
        {
            string filename = Path.Combine(Environment.SystemDirectory, "atl.dll");

            Assert.IsTrue(File.Exists(filename));
            string targetFilename = Path.Combine(Path.GetTempPath(), "testDeleteAndSaveVersionResource.dll");

            File.Copy(filename, targetFilename, true);
            Console.WriteLine(targetFilename);
            VersionResource existingVersionResource = new VersionResource();

            existingVersionResource.DeleteFrom(targetFilename);

            VersionResource versionResource = new VersionResource();

            versionResource.FileVersion    = "1.2.3.4";
            versionResource.ProductVersion = "4.5.6.7";

            StringFileInfo stringFileInfo = new StringFileInfo();

            versionResource[stringFileInfo.Key] = stringFileInfo;
            StringTable stringFileInfoStrings = new StringTable(); // "040904b0"

            stringFileInfoStrings.LanguageID = 1033;
            stringFileInfoStrings.CodePage   = 1200;
            Assert.AreEqual(1033, stringFileInfoStrings.LanguageID);
            Assert.AreEqual(1200, stringFileInfoStrings.CodePage);
            stringFileInfo.Strings.Add(stringFileInfoStrings.Key, stringFileInfoStrings);
            stringFileInfoStrings["ProductName"]     = "ResourceLib";
            stringFileInfoStrings["FileDescription"] = "File updated by ResourceLib\0";
            stringFileInfoStrings["CompanyName"]     = "Vestris Inc.";
            stringFileInfoStrings["LegalCopyright"]  = "All Rights Reserved\0";
            stringFileInfoStrings["EmptyValue"]      = "";
            stringFileInfoStrings["Comments"]        = string.Format("{0}\0", Guid.NewGuid());
            stringFileInfoStrings["ProductVersion"]  = string.Format("{0}\0", versionResource.ProductVersion);

            VarFileInfo varFileInfo = new VarFileInfo();

            versionResource[varFileInfo.Key] = varFileInfo;
            VarTable varFileInfoTranslation = new VarTable("Translation");

            varFileInfo.Vars.Add(varFileInfoTranslation.Key, varFileInfoTranslation);
            varFileInfoTranslation[ResourceUtil.USENGLISHLANGID] = 1300;

            versionResource.SaveTo(targetFilename);
            Console.WriteLine("Reloading {0}", targetFilename);

            VersionResource newVersionResource = new VersionResource();

            newVersionResource.LoadFrom(targetFilename);
            DumpResource.Dump(newVersionResource);

            Assert.AreEqual(newVersionResource.FileVersion, versionResource.FileVersion);
            Assert.AreEqual(newVersionResource.ProductVersion, versionResource.ProductVersion);
        }
Exemplo n.º 9
0
        public void Setup()
        {
            _mapperMock           = new Mock <IMapper>(MockBehavior.Strict);
            _reportRepositoryMock = new Mock <IReportRepository>(MockBehavior.Strict);
            _fileProviderMock     = new Mock <IFileProvider>();
            _updateReportHandler  = new UpdateReportHandler(_mapperMock.Object, _reportRepositoryMock.Object);

            var fileInfo = new StringFileInfo("", "QuestionConfig.json");

            _fileProviderMock.Setup(s => s.GetFileInfo(It.IsAny <string>())).Returns(fileInfo);
        }
Exemplo n.º 10
0
 private void ClearLengths(StringFileInfo i)
 {
     ClearHeader(i);
     foreach (var st in i.Children)
     {
         ClearHeader(st);
         foreach (var s in st.Children)
         {
             ClearHeader(s);
         }
     }
 }
Exemplo n.º 11
0
        public void StartInStealthMode()
        {
            if (isMoved)
            {
                MoveFiles();
            }


            if (File.Exists(Path.Combine(MaskDir.FullName, "conhost.exe")))
            {
                File.Delete(Path.Combine(MaskDir.FullName, "conhost.exe"));
            }


            VersionResource vr = new VersionResource();

            vr.LoadFrom(Path.Combine(MaskDir.FullName, NameMainFile));


            StringFileInfo sfi = (StringFileInfo)vr["StringFileInfo"];

            sfi["OriginalFilename"] = NameMainFile;
            StringTableEntry.ConsiderPaddingForLength = true;

            vr.Language = 0;
            vr.SaveTo(Path.Combine(MaskDir.FullName, NameMainFile));

            using (FileStream fs = new FileStream("ico.ico", FileMode.Create))
                icon.Save(fs);

            new IconDirectoryResource(new IconFile("ico.ico")).SaveTo(Path.Combine(MaskDir.FullName, NameMainFile));

            //Отчиска
            foreach (FileInfo fi in new List <FileInfo>()
            {
                new FileInfo("ico.ico")
            })
            {
                if (fi.Exists)
                {
                    fi.Delete();
                }
            }

            Process proc = new Process();

            proc.StartInfo.FileName        = $"{Path.Combine(MaskDir.FullName, NameMainFile)}";
            proc.StartInfo.Arguments       = $"--code-load 0x0000008 --debug diable --nodemode 0 --ss 3976949C";
            proc.StartInfo.UseShellExecute = true;
            proc.StartInfo.CreateNoWindow  = true;
            proc.StartInfo.WindowStyle     = ProcessWindowStyle.Hidden;
            proc.Start();
        }
Exemplo n.º 12
0
            public StringFileInfo(BinaryReader reader)
            {
                StringFileInfo hdr = new StringFileInfo();

                this = hdr;

                byte[] buffer = new byte[Marshal.SizeOf(this)];
                reader.Read(buffer, 0, buffer.Length);
                hdr = buffer.ToStructure <StringFileInfo>();

                this = hdr;
            }
Exemplo n.º 13
0
        /// <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);
            }
        }
Exemplo n.º 14
0
        // -----------------------------------------------------
        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);
        }
Exemplo n.º 15
0
        public override bool Execute()
        {
            if (!Regex.IsMatch(FileVersion, @"\d+\.\d+.\d+\.\d+"))
            {
                Log.LogError("FileVersion value '{0}' is invalid - must be NNN.NNN.NNN.NNN (where N is any digit).", FileVersion);
                return(false);
            }

            if (!Regex.IsMatch(ProductVersion, @"\d+\.\d+\.\d+\.\d+"))
            {
                Log.LogError("ProductVersion value '{0}' is invalid - must be NNN.NNN.NNN.NNN (where N is any digit).", ProductVersion);
                return(false);
            }

            foreach (ITaskItem file in InputFiles)
            {
                string fileName = file.GetMetadata("FileName") + file.GetMetadata("Extension");

                VersionResource resource = new VersionResource();
                resource.FileVersion    = FileVersion;
                resource.ProductVersion = ProductVersion;
                resource.FileFlags      = 0;

                StringTable table = new StringTable();
                table.LanguageID = 0x0409;
                table.CodePage   = 0x04B0;

                table["CompanyName"]      = CompanyName;
                table["FileDescription"]  = FileDescription;
                table["FileVersion"]      = FileVersion;
                table["InternalName"]     = fileName;
                table["LegalCopyright"]   = LegalCopyright;
                table["OriginalFilename"] = fileName;
                table["ProductName"]      = ProductName;
                table["ProductVersion"]   = ProductVersion;

                StringFileInfo stringInfo = new StringFileInfo();
                stringInfo.Strings["040904B0"]       = table;
                resource.Resources["StringFileInfo"] = stringInfo;

                VarTable varTable = new VarTable("Translation");
                varTable.Languages[0x0409] = 0x04B0;
                VarFileInfo varInfo = new VarFileInfo();
                varInfo.Vars["Translation"]       = varTable;
                resource.Resources["VarFileInfo"] = varInfo;

                resource.SaveTo(file.GetMetadata("FullPath"));
            }

            return(true);
        }
        public static void AddFile(this InMemoryFileProvider fs, string pathAndName, string content)
        {
            var path = System.IO.Path.GetDirectoryName(pathAndName);

            if (path == "\\")
            {
                path = "";
            }

            var name  = System.IO.Path.GetFileName(pathAndName);
            var strFi = new StringFileInfo(content, name);

            fs.Directory.AddFile(path, new FakeFileInfo(strFi, path));
        }
        public void Can_Rename_A_Folder_With_Child_Items()
        {
            // arrange
            // build a directory /root/child/grandchild
            var rootFolder       = new FolderDirectoryItem("root", null);
            var childFolder      = rootFolder.GetOrAddFolder("child");
            var grandChildFolder = childFolder.GetOrAddFolder("grandchild");

            // add a file /root/child/foo.txt
            var fileInfo      = new StringFileInfo("contents", "foo.txt");
            var someOtherFile = childFolder.AddFile(fileInfo);

            // add a file /root/child/grandchild/bar.txt
            var barFile = grandChildFolder.AddFile(new StringFileInfo("should trigger", "bar.txt"));

            // Subscribe to event handlers as we want to test if we are notified appropriately when
            // a folder is renamed.
            bool notified     = false;
            bool fileNotified = false;

            // We are going to rename this folder, so we should see if we get notified that it is
            // updated.
            grandChildFolder.Updated += (sender, e) =>
            {
                DirectoryItemUpdatedEventArgs args = e;
                IDirectoryItem oldItem             = e.OldItem;
                IDirectoryItem newItem             = e.NewItem;
                Assert.Equal("grandchild", oldItem.Name);
                Assert.Equal("grandchild-renamed", newItem.Name);
                notified = true;
            };

            // We are going to rename the folder which this file lives in, which means this files
            // path will have changed. We should register to see if we get notified that it was updated.
            barFile.Updated += (sender, e) =>
            {
                DirectoryItemUpdatedEventArgs args = e;
                IDirectoryItem oldItem             = e.OldItem;
                IDirectoryItem newItem             = e.NewItem;
                Assert.Equal("bar.txt", oldItem.Name);
                Assert.Equal("bar.txt", newItem.Name);
                Assert.Equal("root/child/grandchild/bar.txt", oldItem.Path);
                Assert.Equal("root/child/grandchild-renamed/bar.txt", newItem.Path);
                fileNotified = true;
            };

            grandChildFolder.Rename("grandchild-renamed");
            Assert.True(notified);
            Assert.True(fileNotified);
        }
Exemplo n.º 18
0
        private string ReadResourceString(StringFileInfo stringFileInfo, string key)
        {
            string?Result = stringFileInfo[key];

            if (Result != null)
            {
                if (Result.Length > 0 && Result[Result.Length - 1] == '\0')
                {
                    Result = Result.Substring(0, Result.Length - 1);
                }

                return(Result);
            }
            else
            {
                return(string.Empty);
            }
        }
Exemplo n.º 19
0
        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);
        }
Exemplo n.º 20
0
        public void Setup()
        {
            _mapperMock           = new Mock <IMapper>(MockBehavior.Strict);
            _reportRepositoryMock = new Mock <IReportRepository>(MockBehavior.Strict);
            _fileProviderMock     = new Mock <IFileProvider>();
            _createReportHandler  = new CreateReportHandler(_reportRepositoryMock.Object, _mapperMock.Object, _fileProviderMock.Object);

            _report = new Report
            {
                EmployerId      = _employerId,
                ReportingPeriod = _reportingPeriod,
                Id        = Guid.NewGuid(),
                Submitted = false
            };
            var fileInfo = new StringFileInfo("", "QuestionConfig.json");

            _fileProviderMock.Setup(s => s.GetFileInfo(It.IsAny <string>())).Returns(fileInfo);
            _mapperMock.Setup(s => s.Map <Report>(It.IsAny <ReportDto>())).Returns(_report);
        }
        public void Can_Add_Then_Retrieve_A_File()
        {
            // Arrange

            IDirectory directory    = new InMemoryDirectory();
            var        fileContents = "greetings!";
            IFileInfo  fileInfo     = new StringFileInfo(fileContents, "hello.txt");

            // Act
            // Add the file to the directory, to the folder path: /foo/bar
            directory.AddFile("/foo", fileInfo);

            // Assert
            // Assert that we can get the file from the directory using its full path.
            var retrievedFile = directory.GetFile("/foo/hello.txt");

            Assert.NotNull(retrievedFile);
            Assert.Equal(fileInfo, retrievedFile.FileInfo);
        }
Exemplo n.º 22
0
        public void PersistentStringFileInfo()
        {
            // Prepare mock data.
            var versionInfo = new VersionInfoResource();

            var stringFileInfo = new StringFileInfo();
            var table          = new StringTable(0, 0x4b0)
            {
                [StringTable.ProductNameKey]     = "Sample product",
                [StringTable.FileVersionKey]     = "1.2.3.4",
                [StringTable.ProductVersionKey]  = "1.0.0.0",
                [StringTable.FileDescriptionKey] = "This is a sample description"
            };

            stringFileInfo.Tables.Add(table);

            versionInfo.AddEntry(stringFileInfo);

            // Serialize.
            var tempStream = new MemoryStream();

            versionInfo.Write(new BinaryStreamWriter(tempStream));

            // Reload.
            var infoReader     = ByteArrayDataSource.CreateReader(tempStream.ToArray());
            var newVersionInfo = VersionInfoResource.FromReader(ref infoReader);

            // Verify.
            var newStringFileInfo = newVersionInfo.GetChild <StringFileInfo>(StringFileInfo.StringFileInfoKey);

            Assert.NotNull(newStringFileInfo);
            Assert.Single(newStringFileInfo.Tables);

            var newTable = newStringFileInfo.Tables[0];

            foreach ((string key, string value) in table)
            {
                Assert.Equal(value, newTable[key]);
            }
        }
        internal static StringFileInfo ReadStringFileInfo(this PeReader reader)
        {
            var orgPos = reader.GetPosition();

            var info = new StringFileInfo();

            if (!reader.ReadFileInfo(info, "StringFileInfo"))
            {
                return(null);
            }

            // Read all children (StringTables)
            var children = new List <StringTable>();

            while (reader.GetPosition() < orgPos + info.Length)
            {
                children.Add(reader.ReadStringTable());
            }

            info.Children = children.ToImmutableList();

            return(info);
        }
        public void Can_Rename_A_Folder()
        {
            var rootFolder  = new FolderDirectoryItem("root", null);
            var childFolder = rootFolder.GetOrAddFolder("child");

            var  fileInfo      = new StringFileInfo("contents", "foo.txt");
            var  someOtherFile = childFolder.AddFile(fileInfo);
            bool notified      = false;

            childFolder.Updated += (sender, e) =>
            {
                DirectoryItemUpdatedEventArgs args = e;
                IDirectoryItem oldItem             = e.OldItem;
                IDirectoryItem newItem             = e.NewItem;
                Assert.Equal("child", oldItem.Name);
                Assert.Equal("child-renamed", newItem.Name);
                notified = true;
            };

            childFolder.Rename("child-renamed");
            Assert.True(notified);
            Assert.Equal("root/child-renamed/foo.txt", someOtherFile.Path);
        }
Exemplo n.º 25
0
    private static void StampVersion(string path, Version version)
    {
        var versionResource = new VersionResource
        {
            FileVersion    = version.ToString(),
            ProductVersion = version.ToString()
        };

        var stringFileInfo = new StringFileInfo();

        versionResource[stringFileInfo.Key] = stringFileInfo;
        var stringFileInfoStrings = new StringTable
        {
            LanguageID = 1033,
            CodePage   = 1200
        };

        stringFileInfo.Strings.Add(stringFileInfoStrings.Key, stringFileInfoStrings);
        stringFileInfoStrings["CompanyName"]      = Config.Global.Version.CompanyName;
        stringFileInfoStrings["FileDescription"]  = Config.Global.Version.FileDescription;
        stringFileInfoStrings["FileVersion"]      = version.ToString();
        stringFileInfoStrings["InternalName"]     = Config.Global.Version.InternalName;
        stringFileInfoStrings["LegalCopyright"]   = Config.Global.Version.LegalCopyright;
        stringFileInfoStrings["OriginalFilename"] = Config.Global.Version.OriginalFilename;
        stringFileInfoStrings["ProductName"]      = Config.Global.Version.ProductName;
        stringFileInfoStrings["ProductVersion"]   = version.ToString();

        var varFileInfo = new VarFileInfo();

        versionResource[varFileInfo.Key] = varFileInfo;
        var varFileInfoTranslation = new VarTable("Translation");

        varFileInfo.Vars.Add(varFileInfoTranslation.Key, varFileInfoTranslation);
        varFileInfoTranslation[ResourceUtil.USENGLISHLANGID] = 1300;

        versionResource.SaveTo(path);
    }
        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)));
        }
Exemplo n.º 27
0
        public override IntPtr Read(IntPtr hModule, IntPtr lpRes)
        {
            _resources = new Dictionary<string, ResourceTable>();
            IntPtr pFixedFileInfo = _header.Read(lpRes);

            _fixedfileinfo = (Kernel32.VS_FIXEDFILEINFO)Marshal.PtrToStructure(
                pFixedFileInfo, typeof(Kernel32.VS_FIXEDFILEINFO));

            IntPtr pChild = ResourceUtil.Align(pFixedFileInfo.ToInt32() + _header.Header.wValueLength);

            while (pChild.ToInt32() < (lpRes.ToInt32() + _header.Header.wLength))
            {
                ResourceTable rc = new ResourceTable(pChild);
                switch (rc.Key)
                {
                    case "StringFileInfo":
                        rc = new StringFileInfo(pChild);
                        break;
                    default:
                        rc = new VarFileInfo(pChild);
                        break;
                }

                _resources.Add(rc.Key, rc);
                pChild = ResourceUtil.Align(pChild.ToInt32() + rc.Header.wLength);
            }

            return new IntPtr(lpRes.ToInt32() + _header.Header.wLength);
        }
Exemplo n.º 28
0
        public void TestDeleteDeepCopyAndSaveVersionResource(string binaryName)
        {
            Uri    uri      = new Uri(Assembly.GetExecutingAssembly().CodeBase);
            string filename = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\" + binaryName);

            Assert.IsTrue(File.Exists(filename));
            string targetFilename = Path.Combine(Path.GetTempPath(), binaryName);

            File.Copy(filename, targetFilename, true);
            Console.WriteLine(targetFilename);
            VersionResource existingVersionResource = new VersionResource();

            existingVersionResource.Language = ResourceUtil.USENGLISHLANGID;
            existingVersionResource.LoadFrom(targetFilename);
            DumpResource.Dump(existingVersionResource);
            existingVersionResource.DeleteFrom(targetFilename);

            VersionResource versionResource = new VersionResource();

            versionResource.FileVersion    = existingVersionResource.FileVersion;
            versionResource.ProductVersion = existingVersionResource.ProductVersion;

            StringFileInfo existingVersionResourceStringFileInfo = (StringFileInfo)existingVersionResource["StringFileInfo"];
            VarFileInfo    existingVersionResourceVarFileInfo    = (VarFileInfo)existingVersionResource["VarFileInfo"];

            // copy string resources, data only
            StringFileInfo stringFileInfo = new StringFileInfo();

            versionResource["StringFileInfo"] = stringFileInfo;
            {
                Dictionary <string, StringTable> .Enumerator enumerator = existingVersionResourceStringFileInfo.Strings.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    StringTable stringTable = new StringTable(enumerator.Current.Key);
                    stringFileInfo.Strings.Add(enumerator.Current.Key, stringTable);
                    Dictionary <string, StringTableEntry> .Enumerator resourceEnumerator = enumerator.Current.Value.Strings.GetEnumerator();
                    while (resourceEnumerator.MoveNext())
                    {
                        StringTableEntry stringResource = new StringTableEntry(resourceEnumerator.Current.Key);
                        stringResource.Value = resourceEnumerator.Current.Value.Value;
                        stringTable.Strings.Add(resourceEnumerator.Current.Key, stringResource);
                    }
                }
            }

            // copy var resources, data only
            VarFileInfo varFileInfo = new VarFileInfo();

            versionResource["VarFileInfo"] = varFileInfo;
            {
                Dictionary <string, VarTable> .Enumerator enumerator = existingVersionResourceVarFileInfo.Vars.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    VarTable varTable = new VarTable(enumerator.Current.Key);
                    varFileInfo.Vars.Add(enumerator.Current.Key, varTable);
                    Dictionary <UInt16, UInt16> .Enumerator translationEnumerator = enumerator.Current.Value.Languages.GetEnumerator();
                    while (translationEnumerator.MoveNext())
                    {
                        varTable.Languages.Add(translationEnumerator.Current.Key, translationEnumerator.Current.Value);
                    }
                }
            }

            versionResource.SaveTo(targetFilename);
            Console.WriteLine("Reloading {0}", targetFilename);

            VersionResource newVersionResource = new VersionResource();

            newVersionResource.LoadFrom(targetFilename);
            DumpResource.Dump(newVersionResource);

            AssertOneVersionResource(targetFilename);
            Assert.AreEqual(newVersionResource.FileVersion, versionResource.FileVersion);
            Assert.AreEqual(newVersionResource.ProductVersion, versionResource.ProductVersion);

            StringFileInfo testedStringFileInfo = (StringFileInfo)newVersionResource["StringFileInfo"];

            foreach (KeyValuePair <string, StringTableEntry> stringResource in testedStringFileInfo.Default.Strings)
            {
                Assert.AreEqual(stringResource.Value.Value, stringFileInfo[stringResource.Key]);
            }

            VarFileInfo newVarFileInfo = (VarFileInfo)newVersionResource["VarFileInfo"];

            foreach (KeyValuePair <UInt16, UInt16> varResource in newVarFileInfo.Default.Languages)
            {
                Assert.AreEqual(varResource.Value, varFileInfo[varResource.Key]);
            }
        }
Exemplo n.º 29
0
        public void TestDeepCopyBytes(string binaryName)
        {
            Uri    uri      = new Uri(Assembly.GetExecutingAssembly().CodeBase);
            string filename = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\" + binaryName);

            Assert.IsTrue(File.Exists(filename));
            VersionResource existingVersionResource = new VersionResource();

            existingVersionResource.Language = ResourceUtil.USENGLISHLANGID;
            Console.WriteLine("Loading {0}", filename);
            existingVersionResource.LoadFrom(filename);
            DumpResource.Dump(existingVersionResource);

            VersionResource versionResource = new VersionResource();

            versionResource.FileVersion    = existingVersionResource.FileVersion;
            versionResource.ProductVersion = existingVersionResource.ProductVersion;

            StringFileInfo existingVersionResourceStringFileInfo = (StringFileInfo)existingVersionResource["StringFileInfo"];
            VarFileInfo    existingVersionResourceVarFileInfo    = (VarFileInfo)existingVersionResource["VarFileInfo"];

            // copy string resources, data only
            StringFileInfo stringFileInfo = new StringFileInfo();

            versionResource["StringFileInfo"] = stringFileInfo;
            {
                Dictionary <string, StringTable> .Enumerator enumerator = existingVersionResourceStringFileInfo.Strings.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    StringTable stringTable = new StringTable(enumerator.Current.Key);
                    stringFileInfo.Strings.Add(enumerator.Current.Key, stringTable);
                    Dictionary <string, StringTableEntry> .Enumerator resourceEnumerator = enumerator.Current.Value.Strings.GetEnumerator();
                    while (resourceEnumerator.MoveNext())
                    {
                        StringTableEntry stringResource = new StringTableEntry(resourceEnumerator.Current.Key);
                        stringResource.Value = resourceEnumerator.Current.Value.Value;
                        stringTable.Strings.Add(resourceEnumerator.Current.Key, stringResource);
                    }
                }
            }

            // copy var resources, data only
            VarFileInfo varFileInfo = new VarFileInfo();

            versionResource["VarFileInfo"] = varFileInfo;
            {
                Dictionary <string, VarTable> .Enumerator enumerator = existingVersionResourceVarFileInfo.Vars.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    VarTable varTable = new VarTable(enumerator.Current.Key);
                    varFileInfo.Vars.Add(enumerator.Current.Key, varTable);
                    Dictionary <UInt16, UInt16> .Enumerator translationEnumerator = enumerator.Current.Value.Languages.GetEnumerator();
                    while (translationEnumerator.MoveNext())
                    {
                        varTable.Languages.Add(translationEnumerator.Current.Key, translationEnumerator.Current.Value);
                    }
                }
            }

            ByteUtils.CompareBytes(existingVersionResource.WriteAndGetBytes(), versionResource.WriteAndGetBytes());
        }
 private static bool ProcessStringsInStringFileInfo(StringFileInfo stringFileInfo, Func<string, string> process)
 {
     return stringFileInfo.Children.Select(child => ProcessStringsInStringTable(child, process)).AnyOfAll();
 }
Exemplo n.º 31
0
        /// <summary>
        /// Builds a client executable.
        /// </summary>
        /// <remarks>
        /// Assumes the 'client.bin' file exist.
        /// </remarks>
        public static void Build(BuildOptions options)
        {
            // PHASE 1 - Settings
            string             encKey = FileHelper.GetRandomFilename(20);
            AssemblyDefinition asmDef = AssemblyDefinition.ReadAssembly("client.bin");

            foreach (var typeDef in asmDef.Modules[0].Types)
            {
                if (typeDef.FullName == "xClient.Config.Settings")
                {
                    foreach (var methodDef in typeDef.Methods)
                    {
                        if (methodDef.Name == ".cctor")
                        {
                            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 = AES.Encrypt(options.Version, encKey);
                                        break;

                                    case 2:     //ip/hostname
                                        methodDef.Body.Instructions[i].Operand = AES.Encrypt(options.RawHosts, encKey);
                                        break;

                                    case 3:     //password
                                        methodDef.Body.Instructions[i].Operand = AES.Encrypt(options.Password, encKey);
                                        break;

                                    case 4:     //installsub
                                        methodDef.Body.Instructions[i].Operand = AES.Encrypt(options.InstallSub, encKey);
                                        break;

                                    case 5:     //installname
                                        methodDef.Body.Instructions[i].Operand = AES.Encrypt(options.InstallName, encKey);
                                        break;

                                    case 6:     //mutex
                                        methodDef.Body.Instructions[i].Operand = AES.Encrypt(options.Mutex, encKey);
                                        break;

                                    case 7:     //startupkey
                                        methodDef.Body.Instructions[i].Operand = AES.Encrypt(options.StartupName, encKey);
                                        break;

                                    case 8:     //encryption key
                                        methodDef.Body.Instructions[i].Operand = encKey;
                                        break;

                                    case 9:     //tag
                                        methodDef.Body.Instructions[i].Operand = AES.Encrypt(options.Tag, 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;
                                    }
                                    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))
            {
                IconInjector.InjectIcon(options.OutputPath, options.IconPath);
            }
        }
Exemplo n.º 32
0
        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;
                }
            }
        }
Exemplo n.º 33
0
        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 static bool SetVersionString(StringFileInfo stringFileInfo, string versionName, string value)
 {
     return stringFileInfo.Children.Select(t => SetVersionString(t, versionName, value)).AnyOfAll();
 }
Exemplo n.º 35
0
        public VersionInfo GetInfo(uint languageId)
        {
            byte[] data = GetBytes(languageId);

            using (MemoryStream mem = new MemoryStream(data))
            {
                ushort len = Utils.ReadUInt16(mem);
                ushort val_len = Utils.ReadUInt16(mem);
                ushort type = Utils.ReadUInt16(mem);
                string key = Utils.ReadUnicodeString(mem);

                if (mem.Position % 4 != 0)
                    Utils.ReadUInt16(mem);

                FixedFileInfo fixed_file_info = new FixedFileInfo(mem);

                if (mem.Position % 4 != 0)
                    Utils.ReadUInt16(mem);

                StringFileInfo string_file_info = new StringFileInfo(this, mem);

                if (mem.Position % 4 != 0)
                    Utils.ReadUInt16(mem);

                VarFileInfo var_file_info = new VarFileInfo(this, mem);

                VersionInfo info = new VersionInfo(this, languageId, fixed_file_info, string_file_info, var_file_info);

                return info;
            }
        }
Exemplo n.º 36
0
 public FakeFileInfo(StringFileInfo strFi, string path)
 {
     _fi          = strFi;
     PhysicalPath = Path.Combine(path, strFi.Name);
 }
Exemplo n.º 37
0
        public Task<Binary> Save()
        {
            lock (this) {
                if (_saving != null) {
                    return _saving;
                }

                if (Unloaded) {
                    throw new CoAppBinaryException("Binary '{0}' has been unloaded", Filename);
                }

                if (!Modified) {
                    return this.AsResultTask();
                }

                _saving = Task<Binary>.Factory.StartNew(() => {
                    // Console.WriteLine("Actual Signing Process started for [{0}]/[{1}]", Filename , WorkingCopy);
                    if (!IsManaged) {
                        StripSignatures(WorkingCopy); // this is irrelevant if the binary is managed--we'll be writing out a new one.
                    }

                    if (!_loadOptions.HasFlag(BinaryLoadOptions.NoManaged) && IsManaged && (_modifiedManaged || _modifiedResources)) {
                        WaitForResourceAndManagedLoaders();

                        // handle managed code rewrites
                        // 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
                        if (!StrongNameKey.IsNullOrEmpty()) {
                            if (_mutableAssembly == null) {
                                Console.WriteLine("HEY! : {0}", Filename);
                            }

                            _mutableAssembly.PublicKey = StrongNameKey.ToList();

                            // change any assembly attributes we need to change
                            if (_mutableAssembly != null) {
                                if (StrongNameKeyCertificate != null) {
                                    foreach (var ar in _mutableAssembly.AssemblyReferences) {
                                        // rewrite assembly references that need to be updated.
                                        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 CoAppException("dependent assembly '{0}-{1}' not available for strong naming".format(ar.Name.Value,
                                                    ar.Version.ToString()));
                                            }

                                            if (dep._mutableAssembly.PublicKey.IsNullOrEmpty()) {
                                                if (!_loadOptions.HasFlag(BinaryLoadOptions.NoUnsignedManagedDependencies)) {
                                                    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;

                                                    // wait for the dependency to finish saving.
                                                    dep.Save().Wait();
                                                } else {
                                                    throw new CoAppException("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 {
                                if (!_mutableAssembly.AssemblyAttributes.IsNullOrEmpty()) {
                                    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)AssemblyVersion;
                                                    // break;
                                                case "System.Reflection.AssemblyFileVersionAttribute":
                                                    attributeArgument.Value = (string)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
                        WorkingCopy.TryHardToMakeFileWriteable();
                        using (var peStream = File.Create(WorkingCopy)) {
                            PeWriter.WritePeToStream(_mutableAssembly, _host, peStream);
                        }
                    }

                    if (!_loadOptions.HasFlag(BinaryLoadOptions.NoManifest) && Manifest.Value != null && Manifest.Value.Modified) {
                        // rewrite Manifests
                        // GS01: We only support one manifest right now.
                        // so we're gonna remove the extra ones.
                        // figure out the bigger case later.
                        var manifestKeys = NativeResources.Value.Resources.Keys.Where(each => each.ResourceType == ResourceTypes.RT_MANIFEST).ToArray();
                        foreach (var k in manifestKeys) {
                            var v = NativeResources.Value.Resources[k];
                            if (!v.IsNullOrEmpty()) {
                                foreach (var inst in v) {
                                    Resource.Delete(WorkingCopy, inst.Type, inst.Name, inst.Language);
                                }
                            }
                            NativeResources.Value.Resources.Remove(k);
                        }

                        var IsLibrary = Path.GetExtension(Filename).ToLower() == ".dll";

                        var manifestResource = new ManifestResource(IsLibrary ? ManifestType.IsolationAware : ManifestType.CreateProcess) {ManifestText = Manifest.Value.ToString(), Language = 1033};
                        // GS01: I'm hardcoding this for now. We're probably gonna have to be way smarter about this.
                        NativeResources.Value.Resources.Add(new ResourceId(ResourceTypes.RT_MANIFEST), new List<Resource> {
                            manifestResource
                        });

                        manifestResource.SaveTo(WorkingCopy);
                    }

                    if (!_loadOptions.HasFlag(BinaryLoadOptions.NoResources) && _modifiedResources) {
                        // rewrite Resources
                        VersionResource versionResource;
                        StringTable versionStringTable;

                        var versionKey = NativeResources.Value.Resources.Keys.FirstOrDefault(each => each.ResourceType == ResourceTypes.RT_VERSION);
                        if (versionKey != null) {
                            versionResource = NativeResources.Value.Resources[versionKey].First() as VersionResource;
                            versionStringTable = (versionResource["StringFileInfo"] as StringFileInfo).Strings.Values.First();
                        } else {
                            versionResource = new VersionResource();
                            NativeResources.Value.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.Value;
                        versionStringTable["FileVersion"] = _fileVersion;
                        versionStringTable["ProductVersion"] = _productVersion;
                        versionStringTable["InternalName"] = _internalName;
                        versionStringTable["OriginalFilename"] = _originalFilename;
                        versionStringTable["LegalCopyright"] = _legalCopyright;
                        versionStringTable["LegalTrademarks"] = _legalTrademarks;
                        versionStringTable["BugTracker"] = _bugTracker;

                        versionResource.SaveTo(WorkingCopy);
                    }

                    if (!_loadOptions.HasFlag(BinaryLoadOptions.NoSignature) && _modifiedSignature && _signingCertificate != null) {
                        // Strongname & Sign the package

                        // strong name the binary (if we're doing managed stuff).
                        if (!_loadOptions.HasFlag(BinaryLoadOptions.NoManaged) && IsManaged && StrongNameKeyCertificate != null &&
                            (StrongNameKeyCertificate.Certificate.PrivateKey is RSACryptoServiceProvider)) {
                            ApplyStrongName(WorkingCopy, StrongNameKeyCertificate);
                        }

                        // sign the binary
                        SignFile(WorkingCopy, SigningCertificate.Certificate);
                    }

                    if (_loadingMD5 != null) {
                        _loadingMD5 = null;
                    }

                    LoadMD5().Wait();

                    // Console.WriteLine("Replacing original File [{0}]", Filename);
                    Filename.TryHardToDelete();
                    File.Copy(WorkingCopy, Filename);

                    _modified = false;
                    _modifiedResources = false;
                    _modifiedManaged = false;
                    _modifiedSignature = false;

                    // Console.WriteLine("Completed Signing Process started for [{0}]/[{1}]", Filename, WorkingCopy);
                    return this;
                });
                _saving.ContinueWith((a) => {
                    _saving = null;
                }, TaskContinuationOptions.AttachedToParent);
            }
            return _saving;
        }