private static bool TryAddBinaryResource(this ResourceWriter writer, IResource resource) { var binary = resource.Type != TypeNames.String && resource.Type != TypeNames.ByteArray; if (!binary) { return(false); } var value = resource.Value; if (value == null) { return(false); } var binaryFormatter = new BinaryFormatter( ) { Binder = TypeResolver.Binder, SurrogateSelector = TypeResolver.SurrogateSelector }; using (var stream = new MemoryStream( )) { binaryFormatter.Serialize(stream, resource.Value); writer.AddResourceData(resource.Name, resource.Type.ToString( ), stream.ToArray( )); } return(true); }
private void WriteCollectedBamlStreams(ResourceWriter resourceWriter) { foreach (var bamlStream in _bamlStreams) { resourceWriter.AddResourceData( GetResourceName(bamlStream.Key, bamlStream.Value), bamlStream.Key.type, bamlStream.Key.data); } }
public bool Process(AssemblyDefinition containingAssembly, Res resource, ResReader resourceReader, ResourceWriter resourceWriter) { string fix = _repackContext.FixStr(resource.type); if (fix == resource.type) { resourceWriter.AddResourceData(resource.name, resource.type, resource.data); } else { var output2 = new MemoryStream(resource.data.Length); var sr = new SerReader(_repackContext, new MemoryStream(resource.data), output2); sr.Stream(); resourceWriter.AddResourceData(resource.name, fix, output2.ToArray()); } return(true); }
public void PostRename(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) { var module = def as ModuleDefMD; if (module == null) { return; } var wpfResInfo = context.Annotations.Get <Dictionary <string, Dictionary <string, BamlDocument> > >(module, BAMLKey); if (wpfResInfo == null) { return; } foreach (var res in module.Resources.OfType <EmbeddedResource>()) { Dictionary <string, BamlDocument> resInfo; if (!wpfResInfo.TryGetValue(res.Name, out resInfo)) { continue; } var stream = new MemoryStream(); var writer = new ResourceWriter(stream); res.Data.Position = 0; var reader = new ResourceReader(new ImageStream(res.Data)); var enumerator = reader.GetEnumerator(); while (enumerator.MoveNext()) { var name = (string)enumerator.Key; string typeName; byte[] data; reader.GetResourceData(name, out typeName, out data); BamlDocument document; if (resInfo.TryGetValue(name, out document)) { var docStream = new MemoryStream(); docStream.Position = 4; BamlWriter.WriteDocument(document, docStream); docStream.Position = 0; docStream.Write(BitConverter.GetBytes((int)docStream.Length - 4), 0, 4); data = docStream.ToArray(); name = document.DocumentName; } writer.AddResourceData(name, typeName, data); } writer.Generate(); res.Data = MemoryImageStream.Create(stream.ToArray()); } }
private void AddNewGenericThemesXaml( ResourceWriter resourceWriter, IEnumerable <string> genericThemeResources) { _logger.Info("Creating new themes/generic.xaml"); var newBamlDocument = _bamlGenerator.GenerateThemesGenericXaml(genericThemeResources); resourceWriter.AddResourceData( GenericThemesBamlName, "ResourceTypeCode.Stream", BamlUtils.ToResourceBytes(newBamlDocument)); }
public void buildUpdatePackage(updatePackage package, string changesDe, string changesEn) { //Argumente prüfen if (package == null) { throw new ArgumentException("package"); } if (string.IsNullOrEmpty(changesDe) && string.IsNullOrEmpty(changesEn)) { throw new ArgumentException("changesDe und changesEn"); } //Prüfen ob das Projekt schon gespeichert wurde (notwendig!) if (string.IsNullOrEmpty(_session.currentProjectPath)) { throw new Exception("Das Projekt muss gespeichert werden bevor Updatepakete erstellt werden können."); } //Lokales Basisverzeichnis für die Aktualisieren bestimmen. string updateDirectory = Path.Combine(Path.GetDirectoryName(_session.currentProjectPath), _projectStructure[0]); //Updatepaket für die Dateien erstellen using (var fsUpdatePackage = new FileStream(Path.Combine(updateDirectory, package.getFilename()), FileMode.Create)) { using (var writer = new ResourceWriter(fsUpdatePackage)) { //Jede Datei ins Paket schreiben und vorher komprimieren foreach (var fcAction in package.fileCopyActions) { foreach (var fileData in fcAction.Files) { if (File.Exists(fileData.Fullpath)) { writer.AddResourceData(fileData.ID, "fileCopyActionData", compressData(File.ReadAllBytes(fileData.Fullpath))); } } } writer.Generate(); } } //Paketgröße setzen package.packageSize = new FileInfo(Path.Combine(updateDirectory, package.getFilename())).Length; string packageHash = Convert.ToBase64String( SHA512.Create().ComputeHash(File.ReadAllBytes(Path.Combine(updateDirectory, package.getFilename())))); package.packageSignature = updateSystemDotNet.Core.RSA.Sign(packageHash, _session.currentProject.keyPair.privateKey); //Changelog erstellen und speichern XmlDocument xChangelog = createChangelogs(changesDe, changesEn); using (var xWriter = new StreamWriter(Path.Combine(updateDirectory, package.getChangelogFilename()), false, Encoding.UTF8)) { xChangelog.Save(xWriter); } }
public static void Main() { ResourceWriter rw = new ResourceWriter(@".\TypeResources.resources"); int n1 = 1032; rw.AddResourceData("Integer1", "ResourceTypeCode.Int32", BitConverter.GetBytes(n1)); int n2 = 2064; rw.AddResourceData("Integer2", "ResourceTypeCode.Int32", BitConverter.GetBytes(n2)); rw.Generate(); rw.Close(); ResourceReader rr = new ResourceReader(@".\TypeResources.resources"); IDictionaryEnumerator e = rr.GetEnumerator(); while (e.MoveNext()) { Console.WriteLine("{0}: {1}", e.Key, e.Value); } }
static void Main(string[] args) { string dataDirectory = args[0]; string targetFile = args[1]; XmlDocument map = new XmlDocument(); XmlNode xFilesNode = map.CreateElement("Files"); ResourceWriter writer = new ResourceWriter(targetFile); foreach (string file in Directory.GetFiles(dataDirectory, "*", SearchOption.AllDirectories)) { XmlNode xFile = map.CreateElement("File"); string id = Guid.NewGuid().ToString(); string targetDirectory = Path.GetDirectoryName(file).Replace(dataDirectory, ""); if (targetDirectory.StartsWith("\\")) { targetDirectory = targetDirectory.Substring(1); } xFile.AppendChild(createNode(map, "Id", id)); xFile.AppendChild(createNode(map, "Directory", targetDirectory));; xFile.AppendChild(createNode(map, "Filename", Path.GetFileName(file))); xFilesNode.AppendChild(xFile); writer.AddResourceData(id, "setupData", Compress(File.ReadAllBytes(file))); } map.AppendChild(xFilesNode); using (MemoryStream msData = new MemoryStream()) { using (StreamWriter sw = new StreamWriter(msData, Encoding.UTF8)) { map.Save(sw); writer.AddResourceData("map", "setupData", msData.ToArray()); } } writer.Generate(); writer.Dispose(); }
private void Form1_Load(object sender, EventArgs e) { //var stream = Resources.ResourceManager.GetStream("LookupTable"); //customers = (Lookup<string, Dictionary<string, string>>)(new BinaryFormatter().Deserialize(stream)); try { using (var ms = new MemoryStream()) { byte[] data = (byte[])Resources.ResourceManager.GetObject("LookupTableBIN"); ms.Write(data, 0, data.Length); customers = Jil.JSON.Deserialize <Lookup <string, Dictionary <string, string> > >((string)(new BinaryFormatter().Deserialize(ms))); ms.Dispose(); ms.Close(); } } catch { List <string> lines = new List <string>(File.ReadAllLines(@"C:\Users\ZACH-GAMING\Documents\InsightLocations.txt")); string[] labels = lines[0].Split('\t'); lines.RemoveAt(0); customers = (Lookup <string, Dictionary <string, string> >)lines.ToLookup( l => l.Split('\t')[5], l => l.Split('\t').Select( (x, i) => new { Item = x, Index = i } ).ToDictionary( k => labels[k.Index], k => k.Item ) ); using (var ms = new MemoryStream()) { new BinaryFormatter().Serialize( ms, Jil.JSON.Serialize <Lookup <string, Dictionary <string, string> > >( customers ) ); var data = ms.ToArray(); ResourceWriter rw = new ResourceWriter("Resources.LookupTableBIN"); rw.AddResourceData("LookupTableBIN", "ByteArray", data); rw.Generate(); rw.Dispose(); rw.Close(); //ms.Read((byte[])Resources.LookupTableBIN.SyncRoot, 0, data.Length); ms.Dispose(); ms.Close(); } } }
private void WriteDocuments(List <BamlDocument> documents) { var indexedDocuments = documents.ToDictionary(x => x.DocumentName); var newResources = new List <EmbeddedResource>(); foreach (var resource in Module.Resources.OfType <EmbeddedResource>()) { using (var stream = new MemoryStream()) { using (var resourceWriter = new ResourceWriter(stream)) { using (var resourceStream = resource.CreateReader().AsStream()) { using (var resourceReader = new ResourceReader(resourceStream)) { var enumerator = resourceReader.GetEnumerator(); while (enumerator.MoveNext()) { var name = (string)enumerator.Key; resourceReader.GetResourceData(name, out var typeName, out var data); if (indexedDocuments.TryGetValue(name, out var document)) { using (var documentStream = new MemoryStream()) { documentStream.Position = 4; BamlWriter.WriteDocument(document, documentStream); documentStream.Position = 0; documentStream.Write(BitConverter.GetBytes((int)documentStream.Length - 4), 0, 4); data = documentStream.ToArray(); } } resourceWriter.AddResourceData(name, typeName, data); } } } resourceWriter.Generate(); newResources.Add(new EmbeddedResource(resource.Name, stream.ToArray(), resource.Attributes)); } } } foreach (var resource in newResources) { var index = Module.Resources.IndexOfEmbeddedResource(resource.Name); Module.Resources[index] = resource; } }
public void Map() { if (!_assembly.HasWpfResource) { return; } var resource = _assembly.GetWpfResource(); if (!resource.HasWpfBaml) { return; } var data = resource.GetData(); bool changed = false; using (var outputStream = new MemoryStream()) { using (var reader = new ResourceReaderEx(data)) { using (var writer = new ResourceWriter(outputStream)) { while (reader.Read()) { byte[] resourceData = reader.Data; Map(reader, ref resourceData, ref changed); writer.AddResourceData(reader.Name, reader.TypeName, resourceData); } } } if (changed) { resource.SetData(outputStream.ToArray()); } } }
static void Main(string[] args) { var parameters = new CompilerParameters { GenerateExecutable = true, OutputAssembly = Path.Combine(Environment.CurrentDirectory, Path.GetTempFileName()) + ".exe", }; // Based on the code your template uses, these will need to change parameters.ReferencedAssemblies.Add("System.dll"); parameters.ReferencedAssemblies.Add("System.Core.dll"); parameters.ReferencedAssemblies.Add("System.Linq.dll"); // Create the embedded resource file on disk string embeddedResourceFile = Path.GetTempFileName(); using (var rw = new ResourceWriter(embeddedResourceFile)) { var tempFile = Path.GetTempFileName(); File.WriteAllText(tempFile, "Hello, World!"); rw.AddResourceData("my.resource.key", "ResourceTypeCode.ByteArray", File.ReadAllBytes(tempFile)); } // Embed the resource file into the exe parameters.EmbeddedResources.Add(embeddedResourceFile); // Source code for dynamically generated exe string source = @" using System; using System.Linq; using System.Resources; namespace DynamicallyEmbeded { class Program { static void Main(string[] args) { var resourceName = typeof(Program).Assembly.GetManifestResourceNames()[0]; Console.WriteLine(""Embedded resource name: {0}"", resourceName); var stream = typeof(Program).Assembly.GetManifestResourceStream(resourceName); var resourceData = new byte[] { }; using (var rr = new ResourceReader(stream)) { var resourceType = """"; rr.GetResourceData(""my.resource.key"", out resourceType, out resourceData); } var contents = new string(resourceData.Select(x => (char)x).ToArray()); Console.WriteLine(""Embedded resource contents: {0}"", contents); Console.Write(""Press any key to continue . . .""); Console.ReadKey(); } } }"; // Create the code CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); var results = provider.CompileAssemblyFromSource(parameters, source); // Start the program (just to show it worked) if (results.Errors.Count == 0) { Process.Start(parameters.OutputAssembly); } }
/// <summary>See <see cref="Task.Execute"/>.</summary> public override bool Execute() { TaskLoggingHelper log = base.Log; ITaskItem targetManifestResource = this._targetManifestResource; ITaskItem[] mergeResources = this._mergeResources; this._outputResource = null; if (mergeResources.Length <= 0) { // If we don't have any resources to merge, then we have already succeeded at (not) merging them. return(true); } FileInfo targetManifestResourceFileInfo = new FileInfo(targetManifestResource.GetMetadata("FullPath")); if (!targetManifestResourceFileInfo.Exists) { log.LogError("The specified manifest resource file (\"{0}\") does not exist.", targetManifestResource.ItemSpec); return(false); } // UNDONE: In all of the IO in this method, we aren't doing any handling of situations where the file changes between when we initially // look at its size and when we actually read the content. // Get all of the new resources and their values. Dictionary <string, byte[]> mergeResourcesValues = new Dictionary <string, byte[]>(mergeResources.Length, StringComparer.Ordinal); foreach (ITaskItem mergeResource in mergeResources) { System.Diagnostics.Debug.Assert(string.Equals(mergeResource.GetMetadata("MergeTarget"), targetManifestResource.ItemSpec, StringComparison.OrdinalIgnoreCase), "Trying to emit a resource into a different manifest resource than the one specified for MergeTarget."); FileInfo mergeResourceFileInfo = new FileInfo(mergeResource.GetMetadata("FullPath")); if (!mergeResourceFileInfo.Exists) { log.LogError("The specified resource file to merge (\"{0}\") does not exist.", mergeResource.ItemSpec); return(false); } byte[] mergeResourceBytes = new byte[mergeResourceFileInfo.Length]; using (FileStream mergeResourceFileStream = new FileStream(mergeResourceFileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.Read, mergeResourceBytes.Length, FileOptions.SequentialScan)) { mergeResourceFileStream.Read(mergeResourceBytes, 0, mergeResourceBytes.Length); } string resourceName = mergeResource.GetMetadata("ResourceName"); if (string.IsNullOrEmpty(resourceName)) { log.LogError("The specified resource file to merge (\"{0}\") is missing a ResourceName metadata value.", mergeResource.ItemSpec); return(false); } if (mergeResourcesValues.ContainsKey(resourceName)) { log.LogError("The specified resource file to merge (\"{0}\") has a duplicate ResourceName metadata value (\"{2}\").", mergeResource.ItemSpec, resourceName); return(false); } mergeResourcesValues.Add(resourceName, mergeResourceBytes); } // Read the existing .resources file into a byte array. byte[] originalResourcesBytes = new byte[targetManifestResourceFileInfo.Length]; using (FileStream originalResourcesFileStream = new FileStream(targetManifestResourceFileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.Read, originalResourcesBytes.Length, FileOptions.SequentialScan)) { originalResourcesFileStream.Read(originalResourcesBytes, 0, originalResourcesBytes.Length); } // The FileMode.Truncate on the next line is to make the .resources file zero-length so that we don't have to worry about any excess being left behind. using (ResourceWriter resourceWriter = new ResourceWriter(new FileStream(targetManifestResourceFileInfo.FullName, FileMode.Truncate, FileAccess.ReadWrite, FileShare.None, originalResourcesBytes.Length + (mergeResources.Length * 1024), FileOptions.SequentialScan))) { // Copy the resources from the original .resources file (now stored in the byte array) into the new .resources file. using (ResourceReader resourceReader = new ResourceReader(new MemoryStream(originalResourcesBytes, 0, originalResourcesBytes.Length, false, false))) { foreach (System.Collections.DictionaryEntry entry in resourceReader) { string resourceName = (string)entry.Key; string resourceType; byte[] resourceData; resourceReader.GetResourceData(resourceName, out resourceType, out resourceData); if (mergeResourcesValues.ContainsKey(resourceName)) { log.LogMessage(MessageImportance.Normal, "Skipping copying resource \"{0}\" of type \"{1}\" to new manifest resource file \"{2}\". A new resource with this name will be merged.", resourceName, resourceType, targetManifestResource.ItemSpec); } else { resourceWriter.AddResourceData(resourceName, resourceType, resourceData); log.LogMessage(MessageImportance.Low, "Copied resource \"{0}\" of type \"{1}\" to new manifest resource file \"{2}\".", resourceName, resourceType, targetManifestResource.ItemSpec); } } } // Add each of the new resources into the new .resources file. foreach (KeyValuePair <string, byte[]> mergeResourceValue in mergeResourcesValues) { resourceWriter.AddResource(mergeResourceValue.Key, mergeResourceValue.Value); log.LogMessage(MessageImportance.Low, "Added new resource \"{0}\" to new manifest resource file \"{1}\".", mergeResourceValue.Key, targetManifestResource.ItemSpec); } } this._outputResource = targetManifestResource; return(true); }
public static void BinaryFormattedResources() { var values = TestData.BinaryFormatted; byte[] writerBuffer, binaryWriterBuffer; using (MemoryStream ms = new MemoryStream()) using (ResourceWriter writer = new ResourceWriter(ms)) { BinaryFormatter binaryFormatter = new BinaryFormatter(); foreach (var pair in values) { using (MemoryStream memoryStream = new MemoryStream()) { binaryFormatter.Serialize(memoryStream, pair.Value); writer.AddResourceData(pair.Key, TestData.GetSerializationTypeName(pair.Value.GetType()), memoryStream.ToArray()); } } writer.Generate(); writerBuffer = ms.ToArray(); } using (MemoryStream ms = new MemoryStream()) using (PreserializedResourceWriter writer = new PreserializedResourceWriter(ms)) { BinaryFormatter binaryFormatter = new BinaryFormatter(); foreach (var pair in values) { using (MemoryStream memoryStream = new MemoryStream()) { binaryFormatter.Serialize(memoryStream, pair.Value); writer.AddBinaryFormattedResource(pair.Key, TestData.GetSerializationTypeName(pair.Value.GetType()), memoryStream.ToArray()); } } writer.Generate(); binaryWriterBuffer = ms.ToArray(); } // PreserializedResourceWriter should write ResourceWriter/ResourceReader format Assert.Equal(writerBuffer, binaryWriterBuffer); using (MemoryStream ms = new MemoryStream(writerBuffer, false)) using (ResourceReader reader = new ResourceReader(ms)) { typeof(ResourceReader).GetField("_permitDeserialization", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(reader, true); IDictionaryEnumerator dictEnum = reader.GetEnumerator(); while (dictEnum.MoveNext()) { ResourceValueEquals(values[(string)dictEnum.Key], dictEnum.Value); } } // DeserializingResourceReader can read ResourceReader format using (MemoryStream ms = new MemoryStream(writerBuffer, false)) using (DeserializingResourceReader reader = new DeserializingResourceReader(ms)) { IDictionaryEnumerator dictEnum = reader.GetEnumerator(); while (dictEnum.MoveNext()) { ResourceValueEquals(values[(string)dictEnum.Key], dictEnum.Value); } } }
public static void CompileExecutable(PatchOptions options) { string embeddedResourceFile = Path.GetTempFileName(); try { var filesWithoutDirectories = options.Files.Select(x => new FileInfo(x).Name).ToArray(); var compilerParameters = new CompilerParameters { GenerateExecutable = true, OutputAssembly = options.OutputAssembly, CompilerOptions = "/target:winexe", // Make it a WPF app as opposed to a console app }; var input = new Dictionary <string, byte[]>(); using (ResourceWriter rw = new ResourceWriter(embeddedResourceFile)) { foreach (var resourceFile in options.Files) { // Trim off the redundant data string pathedResourceFile = new FileInfo(resourceFile).FullName.Substring(options.RootDirectory.Length - options.RootDirectory.Substring(options.RootDirectory.LastIndexOf(Path.DirectorySeparatorChar) + 1).Length); input[pathedResourceFile] = File.ReadAllBytes(Path.Combine(options.RootDirectory, resourceFile)); rw.AddResourceData(pathedResourceFile, "ResourceTypeCode.ByteArray", input[pathedResourceFile]); } } using (ResourceReader item = new ResourceReader(embeddedResourceFile)) { var enumerator = item.GetEnumerator(); while (enumerator.MoveNext()) { var key = (string)enumerator.Key; string resourceType; byte[] resourceData; item.GetResourceData(key, out resourceType, out resourceData); if (resourceData.Length != input[key].Length) { // Output retrieved not the same as input throw new ApplicationException(); } for (int i = 0; i < input[key].Length; i++) { if (input[key][i] != resourceData[i]) { // Output retrieved not the same as input throw new ApplicationException(); } } Debug.WriteLine(string.Join(" ", resourceData)); } } compilerParameters.EmbeddedResources.Add(embeddedResourceFile); var assemblies = typeof(PatchTemplate).Assembly.GetReferencedAssemblies().ToList(); var assemblyLocations = assemblies.Select(a => Assembly.ReflectionOnlyLoad(a.FullName).Location).ToList(); assemblyLocations.Add(typeof(PatchTemplate).Assembly.Location); compilerParameters.ReferencedAssemblies.AddRange(assemblyLocations.ToArray()); // Hack to get WindowsBase into the referenced assemblies list - don't want to do any work to figure this out Console.WriteLine(typeof(AttachedPropertyBrowsableAttribute).Name); // Read the source template string templateFileName = Path.Combine(new FileInfo(typeof(MainWindow).Assembly.Location).DirectoryName, "Template.cs"); #region Process the file replacements to build valid code var originalLines = File.ReadAllLines(templateFileName); StringBuilder total = new StringBuilder(); var newLines = new List <string>(); for (int i = 0; i < originalLines.Length; i++) { var line = originalLines[i]; line = line.Replace(" Debug.", " System.Console."); line = line.Replace("<<PATCH_NOTE_HEADER>>", options.PatchNoteHeader); line = line.Replace("<<PATCH_NOTE_CONTENT>>", options.PatchNoteContent); if (line.Contains("public static void CreatePatch()")) { line = line.Replace("public static void CreatePatch()", "[System.STAThread]static void Main(string[] args)"); } else if (line.EndsWith("// TEXT: Target directories")) { line = string.Format("private static string[] targetDirectories = new string[]{{ {0} }};", string.Join(", ", options.TargetDirectories.Select(x => string.Format("@\"{0}\"", x)))); } // Add the line newLines.Add(line); } string source = string.Join(Environment.NewLine, newLines); #endregion var provider = CodeDomProvider.CreateProvider("CSharp"); var compilerResults = provider.CompileAssemblyFromSource(compilerParameters, source); if (compilerResults.Errors.Count > 0) { throw new Exception(compilerResults.Errors[0].ErrorText); } } finally { File.Delete(embeddedResourceFile); } }