AddResourceData() public méthode

public AddResourceData ( string name, string typeName, byte serializedData ) : void
name string
typeName string
serializedData byte
Résultat void
Exemple #1
0
    /// <summary>
    /// Adds a given resourcename and data to the app resources in the target assembly
    /// </summary>
    /// <param name="ResourceName"></param>
    /// <param name="ResourceData"></param>
    /// <remarks></remarks>
    public void Add(string ResourceName, byte[] ResourceData)
    {
        // make sure the writer is initialized
        InitAssembly();

        // have to enumerate this way
        for (var x = 0; x <= _Resources.Count - 1; x++)
        {
            var res = _Resources[x];
            if (res.Name.Contains(".Resources.resources"))
            {
                // Have to assume this is the root application's .net resources.
                // That might not be the case though.

                // cast as embeded resource to get at the data
                var EmbededResource = (Mono.Cecil.EmbeddedResource)res;

                // a Resource reader is required to read the resource data
                var ResReader = new ResourceReader(new MemoryStream(EmbededResource.GetResourceData()));

                // Use this output stream to capture all the resource data from the
                // existing resource block, so we can add the new resource into it
                var    MemStreamOut  = new MemoryStream();
                var    ResWriter     = new System.Resources.ResourceWriter(MemStreamOut);
                var    ResEnumerator = ResReader.GetEnumerator();
                byte[] resdata       = null;
                while (ResEnumerator.MoveNext())
                {
                    var    resname = (string)ResEnumerator.Key;
                    string restype = "";
                    // if we come across a resource named the same as the one
                    // we're about to add, skip it
                    if (Strings.StrComp(resname, ResourceName, CompareMethod.Text) != 0)
                    {
                        ResReader.GetResourceData(resname, out restype, out resdata);
                        ResWriter.AddResourceData(resname, restype, resdata);
                    }
                }

                // add the new resource data here
                ResWriter.AddResourceData(ResourceName, "ResourceTypeCode.ByteArray", ResourceData);
                // gotta call this to render the memory stream
                ResWriter.Generate();

                // update the resource
                var buf         = MemStreamOut.ToArray();
                var NewEmbedRes = new EmbeddedResource(res.Name, res.Attributes, buf);
                _Resources.Remove(res);
                _Resources.Add(NewEmbedRes);
                // gotta bail out, there can't be 2 embedded resource chunks, right?
                break;                 // TODO: might not be correct. Was : Exit For
            }
        }
    }
        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;
        }
 private void WriteCollectedBamlStreams(ResourceWriter resourceWriter)
 {
     foreach (var bamlStream in _bamlStreams)
     {
         resourceWriter.AddResourceData(
             GetResourceName(bamlStream.Key, bamlStream.Value), bamlStream.Key.type, bamlStream.Key.data);
     }
 }
        public static bool CombineResourceFile(string fileName, string language, string outputFileName)
        {
            if (language == null || language.Length == 0)
            {
                return(false);
            }
            if (fileName == null || fileName.Length == 0)
            {
                throw new ArgumentNullException("fileName");
            }
            if (File.Exists(fileName) == false)
            {
                throw new FileNotFoundException(fileName);
            }
            var values = new Dictionary <string, System.Tuple <string, byte[]> >();

            FillValues2(fileName, values);
            var rootPath = Path.GetDirectoryName(fileName);
            var fn2      = Path.Combine(
                Path.Combine(rootPath, language),
                Path.GetFileNameWithoutExtension(fileName) + "." + language + EXT_resources);

            if (File.Exists(fn2))
            {
                if (FillValues2(fn2, values) > 0)
                {
                    if (outputFileName == null || outputFileName.Length == 0)
                    {
                        outputFileName = fileName;
                    }

                    using (var writer = new System.Resources.ResourceWriter(outputFileName))
                    {
                        var names = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);
                        foreach (var item in values)
                        {
                            if (names.ContainsKey(item.Key) == false)
                            {
                                writer.AddResourceData(item.Key, item.Value.Item1, item.Value.Item2);
                                names[item.Key] = null;
                            }
                            else
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.BackgroundColor = ConsoleColor.White;
                                Console.WriteLine("Same name resource item:" + fileName + " # " + item.Key);
                                Console.ResetColor();
                            }
                        }
                    }
                    return(true);
                }
            }
            return(false);
        }
Exemple #5
0
		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();
		}
Exemple #6
0
        public void PostRename(ConfuserContext context, INameService service, 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 (EmbeddedResource 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));
                IDictionaryEnumerator 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();
                    }

                    writer.AddResourceData(name, typeName, data);
                }
                writer.Generate();
                res.Data = MemoryImageStream.Create(stream.ToArray());
            }
        }
		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);
			}
		}
Exemple #8
0
		/// <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;
		}
        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));
        }