GetResourceData() public method

public GetResourceData ( String resourceName, String &resourceType, byte &resourceData ) : void
resourceName String
resourceType String
resourceData byte
return void
Ejemplo n.º 1
0
        private void build_page_1()
        {
            TextView tv1 = new TextView ();

            try
            {
                string rez = "Adeptus.Resources.resources";
                string key = "mystring1";
                string resourceType = "";
                byte[] resourceData;
                ResourceReader r = new ResourceReader(rez);
                r.GetResourceData (key, out resourceType, out resourceData);
                r.Close();
                System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
                tv1.Buffer.Text = enc.GetString (resourceData);
            }
            catch (Exception exp)
            {
                tv1.Buffer.Text = exp.Message;
            }

            tv1.WrapMode = WrapMode.Word;
            tv1.Editable = false;

            this.AppendPage (tv1);
            this.SetPageTitle (tv1, "Introduction");
            this.SetPageType (tv1, AssistantPageType.Intro);
            this.SetPageComplete (tv1, true);
        }
Ejemplo n.º 2
0
    public static int Main(string[] args)
    {
        System.Resources.ResourceReader res = new System.Resources.ResourceReader(args[0]);
        string type = "";

        Byte[] value = null;
        res.GetResourceData(args[1], out type, out value);
        using (System.IO.Stream stdout = Console.OpenStandardOutput())
        {
            stdout.Write(value, 4, value.Length - 4);
        }
        res.Close();
        return(0);
    }
Ejemplo n.º 3
0
		public void copyFiles() {
			using (
				var msData =
					(UnmanagedMemoryStream)
					Assembly.GetExecutingAssembly().GetManifestResourceStream("updateSystemDotNet.Setup.setup.package")) {
				using (var resReader = new ResourceReader(msData)) {
					//Dateimap einlesen
					var xmlMap = new XmlDocument();
					byte[] mapData = null;
					string tempString;
					resReader.GetResourceData("map", out tempString, out mapData);
					using (var msMap = new MemoryStream(mapData)) {
						using (var srMap = new StreamReader(msMap, Encoding.UTF8)) {
							xmlMap.Load(srMap);
						}
					}

					int totalFiles = (xmlMap.SelectNodes("Files/File").Count);
					int currentFile = 0;

					//Dateien verarbeiten
					foreach (XmlNode fileNode in xmlMap.SelectNodes("Files/File")) {
						byte[] compressedFileData = null;
						resReader.GetResourceData(fileNode.SelectSingleNode("Id").InnerText, out tempString, out compressedFileData);
						writeCompressedFile(
							compressedFileData,
							fileNode.SelectSingleNode("Directory").InnerText,
							fileNode.SelectSingleNode("Filename").InnerText);

						currentFile++;
						if (fileProgressChanged != null)
							fileProgressChanged(this, new ProgressChangedEventArgs(Percent(currentFile, totalFiles), null));
					}
				}
			}
		}
Ejemplo n.º 4
0
        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 (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();
                        name = document.DocumentName;
                    }

                    writer.AddResourceData(name, typeName, data);
                }
                writer.Generate();
                res.Data = MemoryImageStream.Create(stream.ToArray());
            }
        }
Ejemplo n.º 5
0
        public static int FillValues2(string fileName, Dictionary <string, System.Tuple <string, byte[]> > values)
        {
            int result = 0;

            using (var reader = new System.Resources.ResourceReader(fileName))
            {
                var enumer = reader.GetEnumerator();
                while (enumer.MoveNext())
                {
                    string name     = Convert.ToString(enumer.Key);
                    string resType  = null;
                    byte[] itemData = null;
                    reader.GetResourceData(name, out resType, out itemData);
                    if (resType != null && resType.Length > 0 && itemData != null && itemData.Length > 0)
                    {
                        values[name] = new Tuple <string, byte[]>(resType, itemData);
                        result++;
                    }
                }
            }
            return(result);
        }
Ejemplo n.º 6
0
		/// <summary>
		///     Получение иконок для хинтов из ресурсов проекта Controls
		/// </summary>
		/// <param name="resName">Путь к ресурсу формата GKIcons/RSR2_Bush_Fire.png</param>
		/// <returns></returns>
		public static Tuple<string, System.Drawing.Size> GetImageResource(string resName)
		{
			resName = resName.Replace("/Controls;component/", "");
			var assembly = Assembly.GetAssembly(typeof(Controls.AlarmButton));
			var name =
				assembly.GetManifestResourceNames().FirstOrDefault(n => n.EndsWith(".resources", StringComparison.Ordinal));
			var resourceStream = assembly.GetManifestResourceStream(name);
			if (resourceStream == null)
			{
				return new Tuple<string, System.Drawing.Size>("", new System.Drawing.Size());
			}
			byte[] values;
			using (var reader = new ResourceReader(resourceStream))
			{
				string type;
				reader.GetResourceData(resName.ToLowerInvariant(), out type, out values);
			}

			// Получили массив байтов ресурса, теперь преобразуем его в png bitmap, а потом снова в массив битов
			// уже корректного формата, после чего преобразуем его в base64string для удобства обратного преобразования
			// на клиенте

			const int offset = 4;
			var size = BitConverter.ToInt32(values, 0);
			var value1 = new Bitmap(new MemoryStream(values, offset, size));
			byte[] byteArray;
			using (var stream = new MemoryStream())
			{
				value1.Save(stream, ImageFormat.Png);
				stream.Close();

				byteArray = stream.ToArray();
			}

			return new Tuple<string, System.Drawing.Size>(Convert.ToBase64String(byteArray), value1.Size);
		}
Ejemplo n.º 7
0
		public void GetResourceData2 ()
		{
			byte [] expected = new byte [] {
				0x00, 0x01, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF,
				0xFF, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
				0x00, 0x0C, 0x02, 0x00, 0x00, 0x00, 0x51, 0x53,
				0x79, 0x73, 0x74, 0x65, 0x6D, 0x2E, 0x44, 0x72,
				0x61, 0x77, 0x69, 0x6E, 0x67, 0x2C, 0x20, 0x56,
				0x65, 0x72, 0x73, 0x69, 0x6F, 0x6E, 0x3D, 0x32,
				0x2E, 0x30, 0x2E, 0x30, 0x2E, 0x30, 0x2C, 0x20,
				0x43, 0x75, 0x6C, 0x74, 0x75, 0x72, 0x65, 0x3D,
				0x6E, 0x65, 0x75, 0x74, 0x72, 0x61, 0x6C, 0x2C,
				0x20, 0x50, 0x75, 0x62, 0x6C, 0x69, 0x63, 0x4B,
				0x65, 0x79, 0x54, 0x6F, 0x6B, 0x65, 0x6E, 0x3D,
				0x62, 0x30, 0x33, 0x66, 0x35, 0x66, 0x37, 0x66,
				0x31, 0x31, 0x64, 0x35, 0x30, 0x61, 0x33, 0x61,
				0x05, 0x01, 0x00, 0x00, 0x00, 0x13, 0x53, 0x79,
				0x73, 0x74, 0x65, 0x6D, 0x2E, 0x44, 0x72, 0x61,
				0x77, 0x69, 0x6E, 0x67, 0x2E, 0x53, 0x69, 0x7A,
				0x65, 0x02, 0x00, 0x00, 0x00, 0x05, 0x77, 0x69,
				0x64, 0x74, 0x68, 0x06, 0x68, 0x65, 0x69, 0x67,
				0x68, 0x74, 0x00, 0x00, 0x08, 0x08, 0x02, 0x00,
				0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x00,
				0x00, 0x00, 0x0B};
			ResourceReader r = new ResourceReader ("Test/resources/bug81759.resources");
			string type;
			byte [] bytes;
			r.GetResourceData ("imageList.ImageSize", out type, out bytes);
			// Note that const should not be used here.
			Assert.AreEqual ("System.Drawing.Size, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", type, "#1");
			Assert.AreEqual (expected, bytes, "#2");
			r.Close ();
		}
Ejemplo n.º 8
0
		public void GetResourceData ()
		{
			byte [] t1 = new byte [] {0x16, 0x00, 0x00, 0x00, 0x76, 0x65, 0x72, 0x69, 0x74, 0x61, 0x73, 0x20, 0x76, 0x6F, 0x73, 0x20, 0x6C, 0x69, 0x62, 0x65, 0x72, 0x61, 0x62, 0x69, 0x74, 0x0A};
			byte [] t2 = new byte [] {0x0A, 0x73, 0x6F, 0x6D, 0x65, 0x73, 0x74, 0x72, 0x69, 0x6E, 0x67};
			byte [] t3 = new byte [] {0x0E, 0x00, 0x00, 0x00, 0x73, 0x68, 0x61, 0x72, 0x64, 0x65, 0x6E, 0x66, 0x72, 0x65, 0x75, 0x64, 0x65, 0x0A};

			ResourceReader r = new ResourceReader ("Test/resources/StreamTest.resources");
			Hashtable items = new Hashtable ();
			foreach (DictionaryEntry de in r) {
				string type;
				byte [] bytes;
				r.GetResourceData ((string) de.Key, out type, out bytes);
				items [de.Key] = new DictionaryEntry (type, bytes);
			}

			DictionaryEntry p = (DictionaryEntry) items ["test"];
			Assert.AreEqual ("ResourceTypeCode.Stream", p.Key as string, "#1-1");
			Assert.AreEqual (t1, p.Value as byte [], "#1-2");

			p = (DictionaryEntry) items ["test2"];
			Assert.AreEqual ("ResourceTypeCode.String", p.Key as string, "#2-1");
			Assert.AreEqual (t2, p.Value as byte [], "#2-2");

			p = (DictionaryEntry) items ["test3"];
			Assert.AreEqual ("ResourceTypeCode.ByteArray", p.Key as string, "#3-1");
			Assert.AreEqual (t3, p.Value as byte [], "#3-2");

			r.Close ();
		}
Ejemplo n.º 9
0
		public void GetResourceDataNullName ()
		{
			ResourceReader r = new ResourceReader ("Test/resources/StreamTest.resources");
			string type;
			byte [] bytes;

			try {
				r.GetResourceData (null, out type, out bytes);
				Assert.Fail ("#1");
			} catch (ArgumentNullException ex) {
				Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
				Assert.IsNull (ex.InnerException, "#3");
				Assert.IsNotNull (ex.Message, "#4");
				Assert.IsNotNull (ex.ParamName, "#5");
				Assert.AreEqual ("resourceName", ex.ParamName, "#6");
			} finally {
				r.Close ();
			}
		}
Ejemplo n.º 10
0
		public prepareEditPackageResult prepareEditUpdatePackage(updatePackage package) {

			var result = new prepareEditPackageResult();

			//Temporäres Verzeichnis für die Updatedaten erstellen
			string tempPackagePath = Path.Combine(Environment.GetEnvironmentVariable("tmp"), package.ID);
			result.tempPackagePath = tempPackagePath;
			result.updatePackage = package;

			if (!Directory.Exists(tempPackagePath))
				Directory.CreateDirectory(tempPackagePath);

			//Pfad zum Updatepaket ermitteln
			string packagePath = Path.Combine(Path.Combine(_session.currentProjectDirectory, "Updates"), package.getFilename());
			if (!File.Exists(packagePath))
				throw new FileNotFoundException("Das Updatepaket konnte nicht gefunden werden.", packagePath);

			//Updatepaket öffnen
			using(var fsPackage = File.OpenRead(packagePath)) {
				using(var packageReader = new ResourceReader(fsPackage)) {

					//Dateien entpacken und im Tempverzeichnis abspeichern
					foreach (var copyAction in package.fileCopyActions) {
						foreach (var file in copyAction.Files) {
							string newFilename = string.Format("{0}.{1}", file.ID, file.Filename);
							using(var fsFileOut = new FileStream(Path.Combine(tempPackagePath, newFilename), FileMode.Create)) {
								byte[] resourceData;
								string tempType; //ungenutzt aber trotzdem notwendig
								packageReader.GetResourceData(file.ID, out tempType, out resourceData);
								byte[] decompressedData = decompressData(resourceData);
								fsFileOut.Write(decompressedData, 0, decompressedData.Length);
							}

							//Neuen Dateinamen in Updatepaket übernehmen
							file.Fullpath = Path.Combine(tempPackagePath, newFilename);
						}
					}
				}
			}

			//Changelog lesen
			string changelogPath = Path.Combine(Path.Combine(_session.currentProjectDirectory, "Updates"),
			                                    package.getChangelogFilename());
			if(!File.Exists(changelogPath))
				throw new FileNotFoundException("Der Changelog konnte nicht gefunden werden", changelogPath);
			
			using(var fsChangelog = new StreamReader(changelogPath, Encoding.UTF8)) {
				var xmlChangelog = new XmlDocument();
				xmlChangelog.Load(fsChangelog);

				XmlNodeList changelogItems = xmlChangelog.SelectNodes("updateSystemDotNet.Changelog/Items/Item");
				if(changelogItems == null)
					throw new InvalidOperationException("Es konnte im Changelog keine Änderungseinträge gefunden werden.");

				if (changelogItems.Count >= 1 && changelogItems[0].SelectSingleNode("Change") != null)
					result.changelogGerman = changelogItems[0].SelectSingleNode("Change").InnerText;
				if (changelogItems.Count >= 2 && changelogItems[1].SelectSingleNode("Change") != null)
					result.changelogEnglish = changelogItems[1].SelectSingleNode("Change").InnerText;

			}

			return result;
		}
Ejemplo n.º 11
0
        void AnalyzeResources(ConfuserContext context, INameService service, ModuleDefMD module)
        {
            if (analyzer == null) {
                analyzer = new BAMLAnalyzer(context, service);
                analyzer.AnalyzeElement += AnalyzeBAMLElement;
            }

            var wpfResInfo = new Dictionary<string, Dictionary<string, BamlDocument>>();

            foreach (EmbeddedResource res in module.Resources.OfType<EmbeddedResource>()) {
                Match match = ResourceNamePattern.Match(res.Name);
                if (!match.Success)
                    continue;

                var resInfo = new Dictionary<string, BamlDocument>();

                res.Data.Position = 0;
                var reader = new ResourceReader(new ImageStream(res.Data));
                IDictionaryEnumerator enumerator = reader.GetEnumerator();
                while (enumerator.MoveNext()) {
                    var name = (string)enumerator.Key;
                    if (!name.EndsWith(".baml"))
                        continue;

                    string typeName;
                    byte[] data;
                    reader.GetResourceData(name, out typeName, out data);
                    BamlDocument document = analyzer.Analyze(module, name, data);
                    document.DocumentName = name;
                    resInfo.Add(name, document);
                }

                if (resInfo.Count > 0)
                    wpfResInfo.Add(res.Name, resInfo);
            }
            if (wpfResInfo.Count > 0)
                context.Annotations.Set(module, BAMLKey, wpfResInfo);
        }
        private void CollectTranslatedResource(string bundleName, IDictionaryEnumerator dict, ResourceReader reader, List<ResourceTranslation> translations)
        {
            Object dictValue = null;
            try
            {
                dictValue = dict.Value;
            }
            catch (Exception)
            {
                // wenn eine Assembly wie MeonaKernel gebraucht wird, um dict.Value aufzulösen
                return;
            }

            String key = dict.Key.ToString();
            if (key.StartsWith(">>"))
                return;

            String type;
            byte[] data;
            reader.GetResourceData(dict.Key.ToString(), out type, out data);

            ResourceTranslation translation = new ResourceTranslation();
            translation.BinaryValue = data;
            translation.StringValue = dict.Value != null ? dict.Value.ToString() : null;
            translation.TranslationDateTime = DateTime.UtcNow;
            translation.TranslationStatus = COLLECT_STATUS;
            translation.TranslationBy = TRANSLATION_IMPORTER;

            if (translation.StringValue != null || translation.BinaryValue != null)
            {
                translation.Locale = assembly.GetName().CultureInfo.Name;
                translation.Resource = new Resource();
                translation.Resource.Key = key;
                translation.Resource.ResourceClass = type;

                translations.Add(translation);
            }
        }
Ejemplo n.º 13
0
        /// <inheritdoc/>
        public void Write(
            TinyBinaryWriter writer)
        {
            var orderedResources = new SortedDictionary<Int16, Tuple<ResourceKind, Byte[]>>();
            foreach (var item in _resources.OfType<EmbeddedResource>())
            {
                var count = 0U;
                using (var reader = new ResourceReader(item.GetResourceStream()))
                {
                    foreach (DictionaryEntry resource in reader)
                    {
                        String resourceType;
                        Byte[] resourceData;
                        var resourceName = resource.Key.ToString();

                        reader.GetResourceData(resourceName, out resourceType, out resourceData);

                        var kind = GetResourceKind(resourceType, resourceData);

                        if (kind == ResourceKind.Bitmap)
                        {
                            using (var stream = new MemoryStream(resourceData.Length))
                            {
                                var bitmapProcessor = new TinyBitmapProcessor((Bitmap)resource.Value);
                                bitmapProcessor.Process(writer.GetMemoryBasedClone(stream));
                                resourceData = stream.ToArray();
                            }
                        }

                        orderedResources.Add(GenerateIdFromResourceName(resourceName),
                            new Tuple<ResourceKind, Byte[]>(kind, resourceData));

                        ++count;
                    }
                }

                _context.ResourceFileTable.AddResourceFile(item, count);
            }

            foreach (var item in orderedResources)
            {
                var kind = item.Value.Item1;
                var bytes = item.Value.Item2;

                var padding = 0;
                switch (kind)
                {
                    case ResourceKind.String:
                        var stringLength = (Int32)bytes[0];
                        if (stringLength < 0x7F)
                        {
                            bytes = bytes.Skip(1).Concat(Enumerable.Repeat((Byte)0, 1)).ToArray();
                        }
                        else
                        {
                            bytes = bytes.Skip(2).Concat(Enumerable.Repeat((Byte)0, 1)).ToArray();
                        }
                        break;
                    case ResourceKind.Bitmap:
                        padding = _context.ResourceDataTable.AlignToWord();
                        break;
                    case ResourceKind.Binary:
                        bytes = bytes.Skip(4).ToArray();
                        break;
                    case ResourceKind.Font:
                        padding = _context.ResourceDataTable.AlignToWord();
                        bytes = bytes.Skip(32).ToArray(); // File size + resource header size
                        break;
                }

                // Pre-process font data (swap endiannes if needed).
                if (kind == ResourceKind.Font)
                {
                    using (var stream = new MemoryStream(bytes.Length))
                    {
                        var fontProcessor = new TinyFontProcessor(bytes);
                        fontProcessor.Process(writer.GetMemoryBasedClone(stream));
                        bytes = stream.ToArray();
                    }
                }

                writer.WriteInt16(item.Key);
                writer.WriteByte((Byte)kind);
                writer.WriteByte((Byte)padding);
                writer.WriteInt32(_context.ResourceDataTable.CurrentOffset);

                _context.ResourceDataTable.AddResourceData(bytes);
            }

            if (orderedResources.Count != 0)
            {
                writer.WriteInt16(0x7FFF);
                writer.WriteByte((Byte)ResourceKind.None);
                writer.WriteByte(0x00);
                writer.WriteInt32(_context.ResourceDataTable.CurrentOffset);
            }
        }
Ejemplo n.º 14
0
		/// <summary>
		/// Bietet Zugriff auf die Resourcen in einem Updatepaket.
		/// </summary>
		/// <param name="packagePath">Der Pfad zu dem Updatepaket.</param>
		/// <param name="resID">Die ID der Resource die ausgelesen werden soll.</param>
		/// <returns>Gibt die Resource in Form eines ByteArrays zurück.</returns>
		protected byte[] accessUpdatePackage(string packagePath, string resID) {
			var resReader = new ResourceReader(packagePath);
			try {
				byte[] outData;
				string outType;
				resReader.GetResourceData(resID, out outType, out outData);
				return outData;
			}
			finally {
				resReader.Close();
			}
		}
Ejemplo n.º 15
0
 private Stream GetResourceAsStream(string name)
 {
     Stream stream = Assembly.GetEntryAssembly().GetManifestResourceStream("Concierge_Manager.Properties.Resources.resources");
     ResourceReader reader = new ResourceReader(stream);
     string resourceType = "";
     byte[] data = null;
     reader.GetResourceData(name, out resourceType , out data );
     MemoryStream ms = new MemoryStream(data, 4, data.Length - 4); // it seems that we are getting the file length in the first four bytes
     return ms;
 }
        private void CollectSingleResource(string resourceName, IDictionaryEnumerator dict, ResourceBundle bundle, ResourceReader reader, Object dictValue)
        {
            var resource = new Resource();
            resource.Key = dict.Key.ToString();
            resource.CreateDateTime = DateTime.UtcNow;
            resource.LastChangeDateTime = DateTime.UtcNow;
            resource.DesignerSupportFlag = resource.Key.StartsWith(">>");

            String type;
            byte[] data;
            reader.GetResourceData(dict.Key.ToString(), out type, out data);
            resource.ResourceClass = type;
            resource.BinaryValue = data;

            bundle.Resources.Add(resource);

            resource.StringValue = dictValue != null ? dictValue.ToString() : null;
            if (dictValue is String)
                resource.ResourceType = ResourceType.STRING;
            else if (dictValue is Bitmap)
                resource.ResourceType = ResourceType.IMAGE;
            else
                resource.ResourceType = ResourceType.OTHER_BINARY;
        }
Ejemplo n.º 17
0
        // ******************************************************************
        /// <summary>
        /// The path separator is '/'.  The path should not start with '/'.
        /// </summary>
        /// <param name="asm"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public static Stream GetAssemblyResourceStream(Assembly asm, string path)
        {
            // Just to be sure
            if (path[0] == '/')
            {
                path = path.Substring(1);
            }

            // Just to be sure
            if (path.IndexOf('\\') == -1)
            {
                path = path.Replace('\\', '/');
            }

            Stream resStream = null;

            string resName = asm.GetName().Name + ".g.resources";     // Ref: Thomas Levesque Answer at:

            // http://stackoverflow.com/questions/2517407/enumerating-net-assembly-resources-at-runtime

            using (var stream = asm.GetManifestResourceStream(resName))
            {
                using (var resReader = new System.Resources.ResourceReader(stream))
                {
                    string dataType = null;
                    byte[] data     = null;
                    try
                    {
                        resReader.GetResourceData(path.ToLower(), out dataType, out data);
                    }
                    catch (Exception ex)
                    {
                        DebugPrintResources(resReader);
                    }

                    if (data != null)
                    {
                        switch (dataType)     // COde from
                        {
                        // Handle internally serialized string data (ResourceTypeCode members).
                        case "ResourceTypeCode.String":
                            BinaryReader reader  = new BinaryReader(new MemoryStream(data));
                            string       binData = reader.ReadString();
                            Console.WriteLine("   Recreated Value: {0}", binData);
                            break;

                        case "ResourceTypeCode.Int32":
                            Console.WriteLine("   Recreated Value: {0}", BitConverter.ToInt32(data, 0));
                            break;

                        case "ResourceTypeCode.Boolean":
                            Console.WriteLine("   Recreated Value: {0}", BitConverter.ToBoolean(data, 0));
                            break;

                        // .jpeg image stored as a stream.
                        case "ResourceTypeCode.Stream":
                            ////const int OFFSET = 4;
                            ////int size = BitConverter.ToInt32(data, 0);
                            ////Bitmap value1 = new Bitmap(new MemoryStream(data, OFFSET, size));
                            ////Console.WriteLine("   Recreated Value: {0}", value1);

                            const int OFFSET = 4;
                            resStream = new MemoryStream(data, OFFSET, data.Length - OFFSET);

                            break;

                        // Our only other type is DateTimeTZI.
                        default:
                            ////// No point in deserializing data if the type is unavailable.
                            ////if (dataType.Contains("DateTimeTZI") && loaded)
                            ////{
                            ////    BinaryFormatter binFmt = new BinaryFormatter();
                            ////    object value2 = binFmt.Deserialize(new MemoryStream(data));
                            ////    Console.WriteLine("   Recreated Value: {0}", value2);
                            ////}
                            ////break;
                            break;
                        }

                        // resStream = new MemoryStream(resData);
                    }
                }
            }

            return(resStream);
        }
Ejemplo n.º 18
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;
		}