/// <summary> /// Constructor /// </summary> /// <param name="name">Name of resource</param> /// <param name="typeCode">Type code</param> /// <param name="userTypeName">User type or null if it's not a <see cref="ResourceTypeCode.UserTypes"/></param> public MultiResourceInfo(string name, ResourceTypeCode typeCode, string userTypeName) { if (name == null) { throw new ArgumentNullException(nameof(name)); } Name = name; TypeCode = typeCode; UserTypeName = userTypeName ?? string.Empty; }
internal object?LoadObject(int pos, out ResourceTypeCode typeCode) { if (_version == 1) { object?o = LoadObjectV1(pos); typeCode = (o is string) ? ResourceTypeCode.String : ResourceTypeCode.StartOfUserTypes; return(o); } return(LoadObjectV2(pos, out typeCode)); }
internal object LoadObject(int pos, out ResourceTypeCode typeCode) { if (this._version == 1) { object obj2 = this.LoadObjectV1(pos); typeCode = (obj2 is string) ? ResourceTypeCode.String : ResourceTypeCode.StartOfUserTypes; return(obj2); } return(this.LoadObjectV2(pos, out typeCode)); }
internal object LoadObject(int pos, out ResourceTypeCode typeCode) { if (this._version != 1) { return(this.LoadObjectV2(pos, out typeCode)); } object obj = this.LoadObjectV1(pos); typeCode = obj is string?ResourceTypeCode.String : ResourceTypeCode.StartOfUserTypes; return(obj); }
/// <summary>从打开的资源文件或流检索指定资源的类型名称和数据。</summary> /// <param name="resourceName">资源的名称。</param> /// <param name="resourceType">当此方法返回时,包含表示检索资源的类型名称的字符串 (有关详细信息,请参见注释部分)。此参数未经初始化即被传递。</param> /// <param name="resourceData">此方法返回时,包含一个字节数组,该字节数组为所检索类型的二进制表示形式。此参数未经初始化即被传递。</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="resourceName" /> 为 null。</exception> /// <exception cref="T:System.ArgumentException"> /// <paramref name="resourceName" />。</exception> /// <exception cref="T:System.BadImageFormatException"> /// <paramref name="resourceName" /> 具有无效的类型。</exception> /// <exception cref="T:System.FormatException">检索的资源数据已损坏。</exception> /// <exception cref="T:System.InvalidOperationException">当前 <see cref="T:System.Resources.ResourceReader" /> 对象未初始化,可能因被其已关闭。</exception> public void GetResourceData(string resourceName, out string resourceType, out byte[] resourceData) { if (resourceName == null) { throw new ArgumentNullException("resourceName"); } if (this._resCache == null) { throw new InvalidOperationException(Environment.GetResourceString("ResourceReaderIsClosed")); } int[] array = new int[this._numResources]; int posForResource = this.FindPosForResource(resourceName); if (posForResource == -1) { throw new ArgumentException(Environment.GetResourceString("Arg_ResourceNameNotExist", (object)resourceName)); } lock (this) { for (int local_8 = 0; local_8 < this._numResources; ++local_8) { this._store.BaseStream.Position = this._nameSectionOffset + (long)this.GetNamePosition(local_8); int local_9 = this._store.Read7BitEncodedInt(); if (local_9 < 0) { throw new FormatException(Environment.GetResourceString("BadImageFormat_ResourcesNameInvalidOffset", (object)local_9)); } this._store.BaseStream.Position += (long)local_9; int local_10 = this._store.ReadInt32(); if (local_10 < 0 || (long)local_10 >= this._store.BaseStream.Length - this._dataSectionOffset) { throw new FormatException(Environment.GetResourceString("BadImageFormat_ResourcesDataInvalidOffset", (object)local_10)); } array[local_8] = local_10; } Array.Sort <int>(array); int local_4 = Array.BinarySearch <int>(array, posForResource); int local_5 = (int)((local_4 < this._numResources - 1 ? (long)array[local_4 + 1] + this._dataSectionOffset : this._store.BaseStream.Length) - ((long)posForResource + this._dataSectionOffset)); this._store.BaseStream.Position = this._dataSectionOffset + (long)posForResource; ResourceTypeCode local_6 = (ResourceTypeCode)this._store.Read7BitEncodedInt(); if (local_6 < ResourceTypeCode.Null || local_6 >= (ResourceTypeCode)(64 + this._typeTable.Length)) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_InvalidType")); } resourceType = this.TypeNameFromTypeCode(local_6); int local_5_1 = local_5 - (int)(this._store.BaseStream.Position - (this._dataSectionOffset + (long)posForResource)); byte[] local_7 = this._store.ReadBytes(local_5_1); if (local_7.Length != local_5_1) { throw new FormatException(Environment.GetResourceString("BadImageFormat_ResourceNameCorrupted")); } resourceData = local_7; } }
void InitializeFrom(ResourceElementOptions options) { if (options.ResourceData.Code != ResourceTypeCode.ByteArray && options.ResourceData.Code != ResourceTypeCode.Stream) { throw new InvalidOperationException(); } var builtin = (BuiltInResourceData)options.ResourceData; resourceTypeCode = options.ResourceData.Code; Name = options.Name; Data = (byte[])builtin.Data; }
public bool Read() { if (!_enumerator.MoveNext()) { return(false); } _name = _enumerator.Key.ToString(); _reader.GetResourceData(_name, out _typeName, out _data); _typeCode = ResourceUtils.GetTypeCode(_typeName); return(true); }
internal object LoadObjectV2(int pos, out ResourceTypeCode typeCode) { try { return(this._LoadObjectV2(pos, out typeCode)); } catch (EndOfStreamException ex) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_TypeMismatch"), (Exception)ex); } catch (ArgumentOutOfRangeException ex) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_TypeMismatch"), (Exception)ex); } }
// This takes a virtual offset into the data section and reads a String // from that location. // Anyone who calls LoadObject should make sure they take a lock so // no one can cause us to do a seek in here. internal String LoadString(int pos) { BCLDebug.Assert(_store != null, "ResourceReader is closed!"); _store.BaseStream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin); String s = null; int typeIndex = _store.Read7BitEncodedInt(); if (_version == 1) { if (typeIndex == -1) { return(null); } if (FindType(typeIndex) != typeof(String)) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceNotString_Type", FindType(typeIndex).GetType().FullName)); } s = _store.ReadString(); } else { ResourceTypeCode typeCode = (ResourceTypeCode)typeIndex; if (typeCode != ResourceTypeCode.String && typeCode != ResourceTypeCode.Null) { String typeString; if (typeCode < ResourceTypeCode.StartOfUserTypes) { typeString = typeCode.ToString(); } else { typeString = FindType(typeCode - ResourceTypeCode.StartOfUserTypes).FullName; } throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceNotString_Type", typeString)); } if (typeCode == ResourceTypeCode.String) // ignore Null { s = _store.ReadString(); } } BCLDebug.Log("RESMGRFILEFORMAT", "LoadString(" + pos.ToString("x", CultureInfo.InvariantCulture) + " returned " + (s == null ? "[a null string]" : s)); return(s); }
private string TypeNameFromTypeCode(ResourceTypeCode typeCode) { if (typeCode < ResourceTypeCode.StartOfUserTypes) { return("ResourceTypeCode." + typeCode.ToString()); } int index = (int)(typeCode - 64); long position = this._store.BaseStream.Position; try { this._store.BaseStream.Position = (long)this._typeNamePositions[index]; return(this._store.ReadString()); } finally { this._store.BaseStream.Position = position; } }
// This takes a virtual offset into the data section and reads a String // from that location. // Anyone who calls LoadObject should make sure they take a lock so // no one can cause us to do a seek in here. internal string?LoadString(int pos) { Debug.Assert(_store != null, "ResourceReader is closed!"); _store.BaseStream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin); string?s = null; int typeIndex = _store.Read7BitEncodedInt(); if (_version == 1) { if (typeIndex == -1) { return(null); } if (FindType(typeIndex) != typeof(string)) { throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotString_Type, FindType(typeIndex).FullName)); } s = _store.ReadString(); } else { ResourceTypeCode typeCode = (ResourceTypeCode)typeIndex; if (typeCode != ResourceTypeCode.String && typeCode != ResourceTypeCode.Null) { string?typeString; if (typeCode < ResourceTypeCode.StartOfUserTypes) { typeString = typeCode.ToString(); } else { typeString = FindType(typeCode - ResourceTypeCode.StartOfUserTypes).FullName; } throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotString_Type, typeString)); } if (typeCode == ResourceTypeCode.String) // ignore Null { s = _store.ReadString(); } } return(s); }
internal string LoadString(int pos) { string fullName; this._store.BaseStream.Seek(this._dataSectionOffset + pos, SeekOrigin.Begin); string str = null; int typeIndex = this._store.Read7BitEncodedInt(); if (this._version == 1) { if (typeIndex == -1) { return(null); } if (this.FindType(typeIndex) != typeof(string)) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceNotString_Type", new object[] { this.FindType(typeIndex).FullName })); } return(this._store.ReadString()); } ResourceTypeCode code = (ResourceTypeCode)typeIndex; switch (code) { case ResourceTypeCode.String: case ResourceTypeCode.Null: if (code == ResourceTypeCode.String) { str = this._store.ReadString(); } return(str); } if (code < ResourceTypeCode.StartOfUserTypes) { fullName = code.ToString(); } else { fullName = this.FindType(((int)code) - 0x40).FullName; } throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceNotString_Type", new object[] { fullName })); }
internal object?LoadObjectV2(int pos, out ResourceTypeCode typeCode) { Debug.Assert(_store != null, "ResourceReader is closed!"); Debug.Assert(_version >= 2, ".resources file was not a V2 (or higher) .resources file!"); try { // mega try-catch performs exceptionally bad on x64; factored out body into // _LoadObjectV2 and wrap here. return(_LoadObjectV2(pos, out typeCode)); } catch (EndOfStreamException eof) { throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch, eof); } catch (ArgumentOutOfRangeException e) { throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch, e); } }
private string TypeNameFromTypeCode(ResourceTypeCode typeCode) { string str; if (typeCode < ResourceTypeCode.StartOfUserTypes) { return("ResourceTypeCode." + typeCode.ToString()); } int index = ((int)typeCode) - 0x40; long position = this._store.BaseStream.Position; try { this._store.BaseStream.Position = this._typeNamePositions[index]; str = this._store.ReadString(); } finally { this._store.BaseStream.Position = position; } return(str); }
private String TypeNameFromTypeCode(ResourceTypeCode typeCode) { BCLDebug.Assert(typeCode >= 0, "can't be negative"); if (typeCode < ResourceTypeCode.StartOfUserTypes) { BCLDebug.Assert(!String.Equals(typeCode.ToString(), "LastPrimitive"), "Change ResourceTypeCode metadata order so LastPrimitive isn't what Enum.ToString prefers."); return("ResourceTypeCode." + typeCode.ToString()); } else { int typeIndex = typeCode - ResourceTypeCode.StartOfUserTypes; BCLDebug.Assert(typeIndex >= 0 && typeIndex < _typeTable.Length, "TypeCode is broken or corrupted!"); long oldPos = _store.BaseStream.Position; try { _store.BaseStream.Position = _typeNamePositions[typeIndex]; return(_store.ReadString()); } finally { _store.BaseStream.Position = oldPos; } } }
internal string LoadString(int pos) { this._store.BaseStream.Seek(this._dataSectionOffset + (long)pos, SeekOrigin.Begin); string str = (string)null; int typeIndex = this._store.Read7BitEncodedInt(); if (this._version == 1) { if (typeIndex == -1) { return((string)null); } if ((Type)this.FindType(typeIndex) != typeof(string)) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceNotString_Type", (object)this.FindType(typeIndex).FullName)); } str = this._store.ReadString(); } else { ResourceTypeCode resourceTypeCode = (ResourceTypeCode)typeIndex; switch (resourceTypeCode) { case ResourceTypeCode.String: case ResourceTypeCode.Null: if (resourceTypeCode == ResourceTypeCode.String) { str = this._store.ReadString(); break; } break; default: throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceNotString_Type", (object)(resourceTypeCode >= ResourceTypeCode.StartOfUserTypes ? this.FindType((int)(resourceTypeCode - 64)).FullName : resourceTypeCode.ToString()))); } } return(str); }
internal static bool CanCache(ResourceTypeCode value) { return (value <= ResourceTypeCode.TimeSpan); }
internal object LoadObjectV2(int pos, out ResourceTypeCode typeCode) { object obj2; try { obj2 = this._LoadObjectV2(pos, out typeCode); } catch (EndOfStreamException exception) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_TypeMismatch"), exception); } catch (ArgumentOutOfRangeException exception2) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_TypeMismatch"), exception2); } return obj2; }
public UserResourceType(string name, ResourceTypeCode code) { this.name = name; this.code = code; }
private string TypeNameFromTypeCode(ResourceTypeCode typeCode) { string str; if (typeCode < ResourceTypeCode.StartOfUserTypes) { return ("ResourceTypeCode." + typeCode.ToString()); } int index = ((int) typeCode) - 0x40; long position = this._store.BaseStream.Position; try { this._store.BaseStream.Position = this._typeNamePositions[index]; str = this._store.ReadString(); } finally { this._store.BaseStream.Position = position; } return str; }
[SecuritySafeCritical] // Asserts permission to create & delete a temp file. public void Generate() { if (_resourceList == null) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceWriterSaved")); } BinaryWriter bw = new BinaryWriter(_output, Encoding.UTF8); List <String> typeNames = new List <String>(); // Write out the ResourceManager header // Write out magic number bw.Write(ResourceManager.MagicNumber); // Write out ResourceManager header version number bw.Write(ResourceManager.HeaderVersionNumber); MemoryStream resMgrHeaderBlob = new MemoryStream(240); BinaryWriter resMgrHeaderPart = new BinaryWriter(resMgrHeaderBlob); // Write out class name of IResourceReader capable of handling // this file. resMgrHeaderPart.Write(MultitargetingHelpers.GetAssemblyQualifiedName(typeof(ResourceReader), typeConverter)); // Write out class name of the ResourceSet class best suited to // handling this file. // This needs to be the same even with multi-targeting. It's the // full name -- not the ----sembly qualified name. resMgrHeaderPart.Write(ResourceManager.ResSetTypeName); resMgrHeaderPart.Flush(); // Write number of bytes to skip over to get past ResMgr header bw.Write((int)resMgrHeaderBlob.Length); // Write the rest of the ResMgr header bw.Write(resMgrHeaderBlob.GetBuffer(), 0, (int)resMgrHeaderBlob.Length); // End ResourceManager header // Write out the RuntimeResourceSet header // Version number bw.Write(RuntimeResourceSet.Version); #if RESOURCE_FILE_FORMAT_DEBUG // Write out a tag so we know whether to enable or disable // debugging support when reading the file. bw.Write("***DEBUG***"); #endif // number of resources int numResources = _resourceList.Count; if (_preserializedData != null) { numResources += _preserializedData.Count; } bw.Write(numResources); // Store values in temporary streams to write at end of file. int[] nameHashes = new int[numResources]; int[] namePositions = new int[numResources]; int curNameNumber = 0; MemoryStream nameSection = new MemoryStream(numResources * AverageNameSize); BinaryWriter names = new BinaryWriter(nameSection, Encoding.Unicode); // The data section can be very large, and worse yet, we can grow the byte[] used // for the data section repeatedly. When using large resources like ~100 images, // this can lead to both a fragmented large object heap as well as allocating about // 2-3x of our storage needs in extra overhead. Using a temp file can avoid this. // Assert permission to get a temp file name, which requires two permissions. // Additionally, we may be running under an account that doesn't have permission to // write to the temp directory (enforced via a Windows ACL). Fall back to a MemoryStream. Stream dataSection = null; // Either a FileStream or a MemoryStream String tempFile = null; #if MONO_FEATURE_CAS PermissionSet permSet = new PermissionSet(PermissionState.None); permSet.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted)); permSet.AddPermission(new FileIOPermission(PermissionState.Unrestricted)); #endif try { #if MONO_FEATURE_CAS permSet.Assert(); #endif tempFile = Path.GetTempFileName(); File.SetAttributes(tempFile, FileAttributes.Temporary | FileAttributes.NotContentIndexed); // Explicitly opening with FileOptions.DeleteOnClose to avoid complicated File.Delete // (safe from ----s w/ antivirus software, etc) dataSection = new FileStream(tempFile, FileMode.Open, FileAccess.ReadWrite, FileShare.Read, 4096, FileOptions.DeleteOnClose | FileOptions.SequentialScan); } catch (UnauthorizedAccessException) { // In case we're running under an account that can't access a temp directory. dataSection = new MemoryStream(); } catch (IOException) { // In case Path.GetTempFileName fails because no unique file names are available dataSection = new MemoryStream(); } finally { #if MONO_FEATURE_CAS PermissionSet.RevertAssert(); #endif } using (dataSection) { BinaryWriter data = new BinaryWriter(dataSection, Encoding.UTF8); #if FEATURE_SERIALIZATION IFormatter objFormatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.File | StreamingContextStates.Persistence)); #endif // FEATURE_SERIALIZATION #if RESOURCE_FILE_FORMAT_DEBUG // Write NAMES right before the names section. names.Write(new byte[] { (byte)'N', (byte)'A', (byte)'M', (byte)'E', (byte)'S', (byte)'-', (byte)'-', (byte)'>' }); // Write DATA at the end of the name table section. data.Write(new byte[] { (byte)'D', (byte)'A', (byte)'T', (byte)'A', (byte)'-', (byte)'-', (byte)'-', (byte)'>' }); #endif // We've stored our resources internally in a Hashtable, which // makes no guarantees about the ordering while enumerating. // While we do our own sorting of the resource names based on their // hash values, that's only sorting the nameHashes and namePositions // arrays. That's all that is strictly required for correctness, // but for ease of generating a patch in the future that // modifies just .resources files, we should re-sort them. SortedList sortedResources = new SortedList(_resourceList, FastResourceComparer.Default); if (_preserializedData != null) { foreach (KeyValuePair <String, PrecannedResource> entry in _preserializedData) { sortedResources.Add(entry.Key, entry.Value); } } IDictionaryEnumerator items = sortedResources.GetEnumerator(); // Write resource name and position to the file, and the value // to our temporary buffer. Save Type as well. while (items.MoveNext()) { nameHashes[curNameNumber] = FastResourceComparer.HashFunction((String)items.Key); namePositions[curNameNumber++] = (int)names.Seek(0, SeekOrigin.Current); names.Write((String)items.Key); // key names.Write((int)data.Seek(0, SeekOrigin.Current)); // virtual offset of value. #if RESOURCE_FILE_FORMAT_DEBUG names.Write((byte)'*'); #endif Object value = items.Value; ResourceTypeCode typeCode = FindTypeCode(value, typeNames); // Write out type code Write7BitEncodedInt(data, (int)typeCode); // Write out value PrecannedResource userProvidedResource = value as PrecannedResource; if (userProvidedResource != null) { data.Write(userProvidedResource.Data); } else { #if FEATURE_SERIALIZATION WriteValue(typeCode, value, data, objFormatter); #else WriteValue(typeCode, value, data); #endif } #if RESOURCE_FILE_FORMAT_DEBUG data.Write(new byte[] { (byte)'S', (byte)'T', (byte)'O', (byte)'P' }); #endif } // At this point, the ResourceManager header has been written. // Finish RuntimeResourceSet header // Write size & contents of class table bw.Write(typeNames.Count); for (int i = 0; i < typeNames.Count; i++) { bw.Write(typeNames[i]); } // Write out the name-related items for lookup. // Note that the hash array and the namePositions array must // be sorted in parallel. Array.Sort(nameHashes, namePositions); // Prepare to write sorted name hashes (alignment fixup) // Note: For 64-bit machines, these MUST be aligned on 8 byte // boundaries! Pointers on IA64 must be aligned! And we'll // run faster on X86 machines too. bw.Flush(); int alignBytes = ((int)bw.BaseStream.Position) & 7; if (alignBytes > 0) { for (int i = 0; i < 8 - alignBytes; i++) { bw.Write("PAD"[i % 3]); } } // Write out sorted name hashes. // Align to 8 bytes. Contract.Assert((bw.BaseStream.Position & 7) == 0, "ResourceWriter: Name hashes array won't be 8 byte aligned! Ack!"); #if RESOURCE_FILE_FORMAT_DEBUG bw.Write(new byte[] { (byte)'H', (byte)'A', (byte)'S', (byte)'H', (byte)'E', (byte)'S', (byte)'-', (byte)'>' }); #endif foreach (int hash in nameHashes) { bw.Write(hash); } #if RESOURCE_FILE_FORMAT_DEBUG Console.Write("Name hashes: "); foreach (int hash in nameHashes) { Console.Write(hash.ToString("x") + " "); } Console.WriteLine(); #endif // Write relative positions of all the names in the file. // Note: this data is 4 byte aligned, occuring immediately // after the 8 byte aligned name hashes (whose length may // potentially be odd). Contract.Assert((bw.BaseStream.Position & 3) == 0, "ResourceWriter: Name positions array won't be 4 byte aligned! Ack!"); #if RESOURCE_FILE_FORMAT_DEBUG bw.Write(new byte[] { (byte)'P', (byte)'O', (byte)'S', (byte)'-', (byte)'-', (byte)'-', (byte)'-', (byte)'>' }); #endif foreach (int pos in namePositions) { bw.Write(pos); } #if RESOURCE_FILE_FORMAT_DEBUG Console.Write("Name positions: "); foreach (int pos in namePositions) { Console.Write(pos.ToString("x") + " "); } Console.WriteLine(); #endif // Flush all BinaryWriters to their underlying streams. bw.Flush(); names.Flush(); data.Flush(); // Write offset to data section int startOfDataSection = (int)(bw.Seek(0, SeekOrigin.Current) + nameSection.Length); startOfDataSection += 4; // We're writing an int to store this data, adding more bytes to the header BCLDebug.Log("RESMGRFILEFORMAT", "Generate: start of DataSection: 0x" + startOfDataSection.ToString("x", CultureInfo.InvariantCulture) + " nameSection length: " + nameSection.Length); bw.Write(startOfDataSection); // Write name section. bw.Write(nameSection.GetBuffer(), 0, (int)nameSection.Length); names.Close(); // Write data section. Contract.Assert(startOfDataSection == bw.Seek(0, SeekOrigin.Current), "ResourceWriter::Generate - start of data section is wrong!"); dataSection.Position = 0; dataSection.CopyTo(bw.BaseStream); data.Close(); } // using(dataSection) <--- Closes dataSection, which was opened w/ FileOptions.DeleteOnClose bw.Flush(); // Indicate we've called Generate _resourceList = null; }
private void WriteValue(ResourceTypeCode typeCode, Object value, BinaryWriter writer, IFormatter objFormatter)
internal Object LoadObjectV2(int pos, out ResourceTypeCode typeCode) { BCLDebug.Assert(_store != null, "ResourceReader is closed!"); BCLDebug.Assert(_version >= 2, ".resources file was not a V2 (or higher) .resources file!"); _store.BaseStream.Seek(_dataSectionOffset+pos, SeekOrigin.Begin); typeCode = (ResourceTypeCode) _store.Read7BitEncodedInt(); BCLDebug.Log("RESMGRFILEFORMAT", "LoadObjectV2 type: "+typeCode+" pos: 0x"+_store.BaseStream.Position.ToString("x", CultureInfo.InvariantCulture)); switch(typeCode) { case ResourceTypeCode.Null: return null; case ResourceTypeCode.String: return _store.ReadString(); case ResourceTypeCode.Boolean: return _store.ReadBoolean(); case ResourceTypeCode.Char: return (char) _store.ReadUInt16(); case ResourceTypeCode.Byte: return _store.ReadByte(); case ResourceTypeCode.SByte: return _store.ReadSByte(); case ResourceTypeCode.Int16: return _store.ReadInt16(); case ResourceTypeCode.UInt16: return _store.ReadUInt16(); case ResourceTypeCode.Int32: return _store.ReadInt32(); case ResourceTypeCode.UInt32: return _store.ReadUInt32(); case ResourceTypeCode.Int64: return _store.ReadInt64(); case ResourceTypeCode.UInt64: return _store.ReadUInt64(); case ResourceTypeCode.Single: return _store.ReadSingle(); case ResourceTypeCode.Double: return _store.ReadDouble(); case ResourceTypeCode.Decimal: return _store.ReadDecimal(); case ResourceTypeCode.DateTime: // Use DateTime's ToBinary & FromBinary. Int64 data = _store.ReadInt64(); return DateTime.FromBinary(data); case ResourceTypeCode.TimeSpan: Int64 ticks = _store.ReadInt64(); return new TimeSpan(ticks); // Special types case ResourceTypeCode.ByteArray: { int len = _store.ReadInt32(); if (_ums == null) return _store.ReadBytes(len); if (len > _ums.Length - _ums.Position) throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourceDataTooLong")); byte[] bytes = new byte[len]; int r = _ums.Read(bytes, 0, len); BCLDebug.Assert(r == len, "ResourceReader needs to use a blocking read here. (Call _store.ReadBytes(len)?)"); return bytes; } case ResourceTypeCode.Stream: { int len = _store.ReadInt32(); if (_ums == null) { byte[] bytes = _store.ReadBytes(len); // Lifetime of memory == lifetime of this stream. return new PinnedBufferMemoryStream(bytes); } // make sure we don't create an UnmanagedMemoryStream that is longer than the resource stream. if (len > _ums.Length - _ums.Position) throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourceDataTooLong")); // For the case that we've memory mapped in the .resources // file, just return a Stream pointing to that block of memory. unsafe { return new UnmanagedMemoryStream(_ums.PositionPointer, len, len, FileAccess.Read, true); } } default: BCLDebug.Assert(typeCode >= ResourceTypeCode.StartOfUserTypes, String.Format(CultureInfo.InvariantCulture, "ResourceReader: Unsupported ResourceTypeCode in .resources file! {0}", typeCode)); // Throw new exception? break; } // Normal serialized objects int typeIndex = typeCode - ResourceTypeCode.StartOfUserTypes; return DeserializeObject(typeIndex); }
public TypeResData(ResourceTypeCode typeCode, HexSpan codeSpan, HexSpan dataSpan, Bit7String utf8TypeName) : base(typeCode, codeSpan, dataSpan, dataSpan) => Utf8TypeName = utf8TypeName;
// WriteValue takes a value and writes it to stream. It // can take some specific action based on the type, such as write out a compact // version of the object if it's a type recognized by this ResourceWriter, or // use Serialization to write out the object using the objFormatter. // For instance, the default implementation recognizes primitives such as Int32 // as special types and calls WriteInt32(int) with the value of the object. This // can be much more compact than serializing the same object. // /* private void WriteValueV1(Type type, Object value, BinaryWriter writer, IFormatter objFormatter) { // For efficiency reasons, most of our primitive types will be explicitly // recognized here. Some value classes are also special cased here. if (type == typeof(String)) writer.Write((String) value); else if (type == typeof(Int32)) writer.Write((int)value); else if (type == typeof(Byte)) writer.Write((byte)value); else if (type == typeof(SByte)) writer.Write((sbyte)value); else if (type == typeof(Int16)) writer.Write((short)value); else if (type == typeof(Int64)) writer.Write((long)value); else if (type == typeof(UInt16)) writer.Write((ushort)value); else if (type == typeof(UInt32)) writer.Write((uint)value); else if (type == typeof(UInt64)) writer.Write((ulong)value); else if (type == typeof(Single)) writer.Write((float)value); else if (type == typeof(Double)) writer.Write((double)value); else if (type == typeof(DateTime)) { // Ideally we should use DateTime's ToBinary & FromBinary, // but we can't for compatibility reasons. writer.Write(((DateTime)value).Ticks); } else if (type == typeof(TimeSpan)) writer.Write(((TimeSpan)value).Ticks); else if (type == typeof(Decimal)) { int[] bits = Decimal.GetBits((Decimal)value); BCLDebug.Assert(bits.Length == 4, "ResourceReader::LoadObject assumes Decimal's GetBits method returns an array of 4 ints"); for(int i=0; i<bits.Length; i++) writer.Write(bits[i]); } else if (type == null) { BCLDebug.Assert(value == null, "Type is null iff value is null"); #if RESOURCE_FILE_FORMAT_DEBUG writer.Write("<null value>"); #endif } else objFormatter.Serialize(writer.BaseStream, value); } */ private void WriteValue(ResourceTypeCode typeCode, Object value, BinaryWriter writer, IFormatter objFormatter) { switch(typeCode) { case ResourceTypeCode.Null: break; case ResourceTypeCode.String: writer.Write((String) value); break; case ResourceTypeCode.Boolean: writer.Write((bool) value); break; case ResourceTypeCode.Char: writer.Write((UInt16) (char) value); break; case ResourceTypeCode.Byte: writer.Write((byte) value); break; case ResourceTypeCode.SByte: writer.Write((sbyte) value); break; case ResourceTypeCode.Int16: writer.Write((Int16) value); break; case ResourceTypeCode.UInt16: writer.Write((UInt16) value); break; case ResourceTypeCode.Int32: writer.Write((Int32) value); break; case ResourceTypeCode.UInt32: writer.Write((UInt32) value); break; case ResourceTypeCode.Int64: writer.Write((Int64) value); break; case ResourceTypeCode.UInt64: writer.Write((UInt64) value); break; case ResourceTypeCode.Single: writer.Write((Single) value); break; case ResourceTypeCode.Double: writer.Write((Double) value); break; case ResourceTypeCode.Decimal: writer.Write((Decimal) value); break; case ResourceTypeCode.DateTime: // Use DateTime's ToBinary & FromBinary. Int64 data = ((DateTime) value).ToBinary(); writer.Write(data); break; case ResourceTypeCode.TimeSpan: writer.Write(((TimeSpan) value).Ticks); break; // Special Types case ResourceTypeCode.ByteArray: { byte[] bytes = (byte[]) value; writer.Write(bytes.Length); writer.Write(bytes, 0, bytes.Length); break; } case ResourceTypeCode.Stream: { MemoryStream ms = (MemoryStream) value; if (ms.Length > Int32.MaxValue) throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_MemStreamLength")); int offset, len; ms.InternalGetOriginAndLength(out offset, out len); byte[] bytes = ms.InternalGetBuffer(); writer.Write(len); writer.Write(bytes, offset, len); break; } default: BCLDebug.Assert(typeCode >= ResourceTypeCode.StartOfUserTypes, String.Format(CultureInfo.InvariantCulture, "ResourceReader: Unsupported ResourceTypeCode in .resources file! {0}", typeCode)); objFormatter.Serialize(writer.BaseStream, value); break; } }
internal static void Execute(Lazy<IUndoCommandManager> undoCommandManager, IAppWindow appWindow, IResourceNodeFactory resourceNodeFactory, IFileTreeNodeData[] nodes, ResourceTypeCode typeCode, Func<IResourceElementSetNode, IResourceElementNode[], IUndoCommand> createCommand) { var rsrcSetNode = nodes[0] as IResourceElementSetNode; if (rsrcSetNode == null) rsrcSetNode = nodes[0].TreeNode.Parent.Data as IResourceElementSetNode; Debug.Assert(rsrcSetNode != null); var module = nodes[0].GetModule(); Debug.Assert(module != null); if (module == null) throw new InvalidOperationException(); var dlg = new WF.OpenFileDialog { RestoreDirectory = true, Multiselect = true, Filter = PickFilenameConstants.AnyFilenameFilter, }; if (dlg.ShowDialog() != WF.DialogResult.OK) return; var fnames = dlg.FileNames; if (fnames.Length == 0) return; var newNodes = new IResourceElementNode[fnames.Length]; var treeView = appWindow.FileTreeView.TreeView; var treeNodeGroup = appWindow.FileTreeView.FileTreeNodeGroups.GetGroup(FileTreeNodeGroupType.ResourceElementTreeNodeGroup); for (int i = 0; i < fnames.Length; i++) { var fn = fnames[i]; try { var rsrcElem = new ResourceElement { Name = Path.GetFileName(fn), ResourceData = new BuiltInResourceData(typeCode, File.ReadAllBytes(fn)), }; newNodes[i] = (IResourceElementNode)treeView.Create(resourceNodeFactory.Create(module, rsrcElem, treeNodeGroup)).Data; } catch (Exception ex) { Shared.App.MsgBox.Instance.Show(string.Format(dnSpy_AsmEditor_Resources.Error_ReadingFiles, ex.Message)); return; } } undoCommandManager.Value.Add(createCommand(rsrcSetNode, newNodes.ToArray())); appWindow.FileTabManager.FollowReference(newNodes[0]); }
private void WriteValue(ResourceTypeCode typeCode, object value, BinaryWriter writer) { Contract.Requires(writer != null); switch (typeCode) { case ResourceTypeCode.Null: break; case ResourceTypeCode.String: writer.Write((string)value); break; case ResourceTypeCode.Boolean: writer.Write((bool)value); break; case ResourceTypeCode.Char: writer.Write((ushort)(char)value); break; case ResourceTypeCode.Byte: writer.Write((byte)value); break; case ResourceTypeCode.SByte: writer.Write((sbyte)value); break; case ResourceTypeCode.Int16: writer.Write((short)value); break; case ResourceTypeCode.UInt16: writer.Write((ushort)value); break; case ResourceTypeCode.Int32: writer.Write((int)value); break; case ResourceTypeCode.UInt32: writer.Write((uint)value); break; case ResourceTypeCode.Int64: writer.Write((long)value); break; case ResourceTypeCode.UInt64: writer.Write((ulong)value); break; case ResourceTypeCode.Single: writer.Write((float)value); break; case ResourceTypeCode.Double: writer.Write((double)value); break; case ResourceTypeCode.Decimal: writer.Write((decimal)value); break; case ResourceTypeCode.DateTime: // Use DateTime's ToBinary & FromBinary. long data = ((DateTime)value).ToBinary(); writer.Write(data); break; case ResourceTypeCode.TimeSpan: writer.Write(((TimeSpan)value).Ticks); break; // Special Types case ResourceTypeCode.ByteArray: { byte[] bytes = (byte[])value; writer.Write(bytes.Length); writer.Write(bytes, 0, bytes.Length); break; } case ResourceTypeCode.Stream: { StreamWrapper sw = (StreamWrapper)value; if (sw.Stream.GetType() == typeof(MemoryStream)) { MemoryStream ms = (MemoryStream)sw.Stream; if (ms.Length > int.MaxValue) throw new ArgumentException(SR.ArgumentOutOfRange_StreamLength); byte[] arr = ms.ToArray(); writer.Write(arr.Length); writer.Write(arr, 0, arr.Length); } else { Stream s = sw.Stream; // we've already verified that the Stream is seekable if (s.Length > int.MaxValue) throw new ArgumentException(SR.ArgumentOutOfRange_StreamLength); s.Position = 0; writer.Write((int)s.Length); byte[] buffer = new byte[4096]; int read = 0; while ((read = s.Read(buffer, 0, buffer.Length)) != 0) { writer.Write(buffer, 0, read); } if (sw.CloseAfterWrite) { s.Close(); } } break; } default: Contract.Assert(typeCode >= ResourceTypeCode.StartOfUserTypes, string.Format(CultureInfo.InvariantCulture, "ResourceReader: Unsupported ResourceTypeCode in .resources file! {0}", typeCode)); throw new PlatformNotSupportedException(SR.NotSupported_BinarySerializedResources); } }
void InitializeFrom(ResourceElementOptions options) { if (options.ResourceData.Code != ResourceTypeCode.ByteArray && options.ResourceData.Code != ResourceTypeCode.Stream) throw new InvalidOperationException(); var builtin = (BuiltInResourceData)options.ResourceData; this.resourceTypeCode = options.ResourceData.Code; this.Name = options.Name; this.Data = (byte[])builtin.Data; }
private void WriteValue(ResourceTypeCode typeCode, object value, BinaryWriter writer, IFormatter objFormatter) { switch (typeCode) { case ResourceTypeCode.Null: return; case ResourceTypeCode.String: writer.Write((string) value); return; case ResourceTypeCode.Boolean: writer.Write((bool) value); return; case ResourceTypeCode.Char: writer.Write((ushort) ((char) value)); return; case ResourceTypeCode.Byte: writer.Write((byte) value); return; case ResourceTypeCode.SByte: writer.Write((sbyte) value); return; case ResourceTypeCode.Int16: writer.Write((short) value); return; case ResourceTypeCode.UInt16: writer.Write((ushort) value); return; case ResourceTypeCode.Int32: writer.Write((int) value); return; case ResourceTypeCode.UInt32: writer.Write((uint) value); return; case ResourceTypeCode.Int64: writer.Write((long) value); return; case ResourceTypeCode.UInt64: writer.Write((ulong) value); return; case ResourceTypeCode.Single: writer.Write((float) value); return; case ResourceTypeCode.Double: writer.Write((double) value); return; case ResourceTypeCode.Decimal: writer.Write((decimal) value); return; case ResourceTypeCode.DateTime: { long num = ((DateTime) value).ToBinary(); writer.Write(num); return; } case ResourceTypeCode.TimeSpan: { TimeSpan span = (TimeSpan) value; writer.Write(span.Ticks); return; } case ResourceTypeCode.ByteArray: { byte[] buffer = (byte[]) value; writer.Write(buffer.Length); writer.Write(buffer, 0, buffer.Length); return; } case ResourceTypeCode.Stream: { StreamWrapper wrapper = (StreamWrapper) value; if (wrapper.m_stream.GetType() == typeof(MemoryStream)) { int num2; int num3; MemoryStream stream = (MemoryStream) wrapper.m_stream; if (stream.Length > 0x7fffffffL) { throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_StreamLength")); } stream.InternalGetOriginAndLength(out num2, out num3); byte[] buffer2 = stream.InternalGetBuffer(); writer.Write(num3); writer.Write(buffer2, num2, num3); return; } Stream stream2 = wrapper.m_stream; if (stream2.Length > 0x7fffffffL) { throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_StreamLength")); } stream2.Position = 0L; writer.Write((int) stream2.Length); byte[] buffer3 = new byte[0x1000]; int count = 0; while ((count = stream2.Read(buffer3, 0, buffer3.Length)) != 0) { writer.Write(buffer3, 0, count); } if (wrapper.m_closeAfterWrite) { stream2.Close(); } return; } } objFormatter.Serialize(writer.BaseStream, value); }
public StringResData(ResourceTypeCode typeCode, HexSpan codeSpan, HexSpan dataSpan, Bit7String utf8StringValue) : base(typeCode, codeSpan, dataSpan, utf8StringValue.StringSpan) => Utf8StringValue = utf8StringValue;
public BuiltInResourceData(ResourceTypeCode code, object data) { this.code = code; this.data = data; }
public ArrayResData(ResourceTypeCode typeCode, HexSpan codeSpan, HexSpan dataSpan, HexSpan nestedFileData) : base(typeCode, codeSpan, dataSpan, nestedFileData) { }
static ResourceElementType Convert(ResourceTypeCode code) { if (code >= ResourceTypeCode.UserTypes) return ResourceElementType.SerializedType; return (ResourceElementType)code; }
internal static void Execute(ILSpyTreeNode[] nodes, ResourceTypeCode typeCode, Func<ResourceElementSetTreeNode, ResourceElementTreeNode[], IUndoCommand> createCommand) { var rsrcSetNode = nodes[0] as ResourceElementSetTreeNode; if (rsrcSetNode == null) rsrcSetNode = nodes[0].Parent as ResourceElementSetTreeNode; Debug.Assert(rsrcSetNode != null); var module = ILSpyTreeNode.GetModule(nodes[0]); Debug.Assert(module != null); if (module == null) throw new InvalidOperationException(); var dlg = new WF.OpenFileDialog { RestoreDirectory = true, Multiselect = true, Filter = "All files (*.*)|*.*", }; if (dlg.ShowDialog() != WF.DialogResult.OK) return; var fnames = dlg.FileNames; if (fnames.Length == 0) return; var newNodes = new ResourceElementTreeNode[fnames.Length]; for (int i = 0; i < fnames.Length; i++) { var fn = fnames[i]; try { var rsrcElem = new ResourceElement { Name = Path.GetFileName(fn), ResourceData = new BuiltInResourceData(typeCode, File.ReadAllBytes(fn)), }; newNodes[i] = ResourceFactory.Create(module, rsrcElem); } catch (Exception ex) { MainWindow.Instance.ShowMessageBox(string.Format("Error reading files: {0}", ex.Message)); return; } } UndoCommandManager.Instance.Add(createCommand(rsrcSetNode, newNodes.ToArray())); }
// Finds the ResourceTypeCode for a type, or adds this type to the // types list. private ResourceTypeCode FindTypeCode(Object value, List <String> types) { if (value == null) { return(ResourceTypeCode.Null); } Type type = value.GetType(); if (type == typeof(String)) { return(ResourceTypeCode.String); } else if (type == typeof(Int32)) { return(ResourceTypeCode.Int32); } else if (type == typeof(Boolean)) { return(ResourceTypeCode.Boolean); } else if (type == typeof(Char)) { return(ResourceTypeCode.Char); } else if (type == typeof(Byte)) { return(ResourceTypeCode.Byte); } else if (type == typeof(SByte)) { return(ResourceTypeCode.SByte); } else if (type == typeof(Int16)) { return(ResourceTypeCode.Int16); } else if (type == typeof(Int64)) { return(ResourceTypeCode.Int64); } else if (type == typeof(UInt16)) { return(ResourceTypeCode.UInt16); } else if (type == typeof(UInt32)) { return(ResourceTypeCode.UInt32); } else if (type == typeof(UInt64)) { return(ResourceTypeCode.UInt64); } else if (type == typeof(Single)) { return(ResourceTypeCode.Single); } else if (type == typeof(Double)) { return(ResourceTypeCode.Double); } else if (type == typeof(Decimal)) { return(ResourceTypeCode.Decimal); } else if (type == typeof(DateTime)) { return(ResourceTypeCode.DateTime); } else if (type == typeof(TimeSpan)) { return(ResourceTypeCode.TimeSpan); } else if (type == typeof(byte[])) { return(ResourceTypeCode.ByteArray); } else if (type == typeof(StreamWrapper)) { return(ResourceTypeCode.Stream); } // This is a user type, or a precanned resource. Find type // table index. If not there, add new element. String typeName; if (type == typeof(PrecannedResource)) { typeName = ((PrecannedResource)value).TypeName; if (typeName.StartsWith("ResourceTypeCode.", StringComparison.Ordinal)) { typeName = typeName.Substring(17); // Remove through '.' ResourceTypeCode typeCode = (ResourceTypeCode)Enum.Parse(typeof(ResourceTypeCode), typeName); return(typeCode); } } else { typeName = MultitargetingHelpers.GetAssemblyQualifiedName(type, typeConverter); } int typeIndex = types.IndexOf(typeName); if (typeIndex == -1) { typeIndex = types.Count; types.Add(typeName); } return((ResourceTypeCode)(typeIndex + ResourceTypeCode.StartOfUserTypes)); }
private void WriteValue(ResourceTypeCode typeCode, Object value, BinaryWriter writer) #endif // FEATURE_SERIALIZATION { Contract.Requires(writer != null); switch (typeCode) { case ResourceTypeCode.Null: break; case ResourceTypeCode.String: writer.Write((String)value); break; case ResourceTypeCode.Boolean: writer.Write((bool)value); break; case ResourceTypeCode.Char: writer.Write((UInt16)(char)value); break; case ResourceTypeCode.Byte: writer.Write((byte)value); break; case ResourceTypeCode.SByte: writer.Write((sbyte)value); break; case ResourceTypeCode.Int16: writer.Write((Int16)value); break; case ResourceTypeCode.UInt16: writer.Write((UInt16)value); break; case ResourceTypeCode.Int32: writer.Write((Int32)value); break; case ResourceTypeCode.UInt32: writer.Write((UInt32)value); break; case ResourceTypeCode.Int64: writer.Write((Int64)value); break; case ResourceTypeCode.UInt64: writer.Write((UInt64)value); break; case ResourceTypeCode.Single: writer.Write((Single)value); break; case ResourceTypeCode.Double: writer.Write((Double)value); break; case ResourceTypeCode.Decimal: writer.Write((Decimal)value); break; case ResourceTypeCode.DateTime: // Use DateTime's ToBinary & FromBinary. Int64 data = ((DateTime)value).ToBinary(); writer.Write(data); break; case ResourceTypeCode.TimeSpan: writer.Write(((TimeSpan)value).Ticks); break; // Special Types case ResourceTypeCode.ByteArray: { byte[] bytes = (byte[])value; writer.Write(bytes.Length); writer.Write(bytes, 0, bytes.Length); break; } case ResourceTypeCode.Stream: { StreamWrapper sw = (StreamWrapper)value; if (sw.m_stream.GetType() == typeof(MemoryStream)) { MemoryStream ms = (MemoryStream)sw.m_stream; if (ms.Length > Int32.MaxValue) { throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_StreamLength")); } int offset, len; ms.InternalGetOriginAndLength(out offset, out len); byte[] bytes = ms.InternalGetBuffer(); writer.Write(len); writer.Write(bytes, offset, len); } else { Stream s = sw.m_stream; // we've already verified that the Stream is seekable if (s.Length > Int32.MaxValue) { throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_StreamLength")); } s.Position = 0; writer.Write((int)s.Length); byte[] buffer = new byte[_DefaultBufferSize]; int read = 0; while ((read = s.Read(buffer, 0, buffer.Length)) != 0) { writer.Write(buffer, 0, read); } if (sw.m_closeAfterWrite) { s.Close(); } } break; } default: Contract.Assert(typeCode >= ResourceTypeCode.StartOfUserTypes, String.Format(CultureInfo.InvariantCulture, "ResourceReader: Unsupported ResourceTypeCode in .resources file! {0}", typeCode)); #if FEATURE_SERIALIZATION objFormatter.Serialize(writer.BaseStream, value); break; #else throw new NotSupportedException(Environment.GetResourceString("NotSupported_ResourceObjectSerialization")); #endif // FEATURE_SERIALIZATION } }
private void WriteValue(ResourceTypeCode typeCode, Object value, BinaryWriter writer, IFormatter objFormatter) #if NOT_DEFINED // keep Thinner happy {}
private void WriteValue(ResourceTypeCode typeCode, Object value, BinaryWriter writer) #endif // FEATURE_SERIALIZATION { Contract.Requires(writer != null); switch(typeCode) { case ResourceTypeCode.Null: break; case ResourceTypeCode.String: writer.Write((String) value); break; case ResourceTypeCode.Boolean: writer.Write((bool) value); break; case ResourceTypeCode.Char: writer.Write((UInt16) (char) value); break; case ResourceTypeCode.Byte: writer.Write((byte) value); break; case ResourceTypeCode.SByte: writer.Write((sbyte) value); break; case ResourceTypeCode.Int16: writer.Write((Int16) value); break; case ResourceTypeCode.UInt16: writer.Write((UInt16) value); break; case ResourceTypeCode.Int32: writer.Write((Int32) value); break; case ResourceTypeCode.UInt32: writer.Write((UInt32) value); break; case ResourceTypeCode.Int64: writer.Write((Int64) value); break; case ResourceTypeCode.UInt64: writer.Write((UInt64) value); break; case ResourceTypeCode.Single: writer.Write((Single) value); break; case ResourceTypeCode.Double: writer.Write((Double) value); break; case ResourceTypeCode.Decimal: writer.Write((Decimal) value); break; case ResourceTypeCode.DateTime: // Use DateTime's ToBinary & FromBinary. Int64 data = ((DateTime) value).ToBinary(); writer.Write(data); break; case ResourceTypeCode.TimeSpan: writer.Write(((TimeSpan) value).Ticks); break; // Special Types case ResourceTypeCode.ByteArray: { byte[] bytes = (byte[]) value; writer.Write(bytes.Length); writer.Write(bytes, 0, bytes.Length); break; } case ResourceTypeCode.Stream: { StreamWrapper sw = (StreamWrapper)value; if (sw.m_stream.GetType() == typeof(MemoryStream)) { MemoryStream ms = (MemoryStream)sw.m_stream; if (ms.Length > Int32.MaxValue) throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_StreamLength")); int offset, len; ms.InternalGetOriginAndLength(out offset, out len); byte[] bytes = ms.InternalGetBuffer(); writer.Write(len); writer.Write(bytes, offset, len); } else { Stream s = sw.m_stream; // we've already verified that the Stream is seekable if (s.Length > Int32.MaxValue) throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_StreamLength")); s.Position = 0; writer.Write((int)s.Length); byte[] buffer = new byte[_DefaultBufferSize]; int read = 0; while ((read = s.Read(buffer, 0, buffer.Length)) != 0) { writer.Write(buffer, 0, read); } if (sw.m_closeAfterWrite) { s.Close(); } } break; } default: Contract.Assert(typeCode >= ResourceTypeCode.StartOfUserTypes, String.Format(CultureInfo.InvariantCulture, "ResourceReader: Unsupported ResourceTypeCode in .resources file! {0}", typeCode)); #if FEATURE_SERIALIZATION objFormatter.Serialize(writer.BaseStream, value); break; #else throw new NotSupportedException(Environment.GetResourceString("NotSupported_ResourceObjectSerialization")); #endif // FEATURE_SERIALIZATION } }
private object?_LoadObjectV2(int pos, out ResourceTypeCode typeCode) { _store.BaseStream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin); typeCode = (ResourceTypeCode)_store.Read7BitEncodedInt(); switch (typeCode) { case ResourceTypeCode.Null: return(null); case ResourceTypeCode.String: return(_store.ReadString()); case ResourceTypeCode.Boolean: return(_store.ReadBoolean()); case ResourceTypeCode.Char: return((char)_store.ReadUInt16()); case ResourceTypeCode.Byte: return(_store.ReadByte()); case ResourceTypeCode.SByte: return(_store.ReadSByte()); case ResourceTypeCode.Int16: return(_store.ReadInt16()); case ResourceTypeCode.UInt16: return(_store.ReadUInt16()); case ResourceTypeCode.Int32: return(_store.ReadInt32()); case ResourceTypeCode.UInt32: return(_store.ReadUInt32()); case ResourceTypeCode.Int64: return(_store.ReadInt64()); case ResourceTypeCode.UInt64: return(_store.ReadUInt64()); case ResourceTypeCode.Single: return(_store.ReadSingle()); case ResourceTypeCode.Double: return(_store.ReadDouble()); case ResourceTypeCode.Decimal: return(_store.ReadDecimal()); case ResourceTypeCode.DateTime: // Use DateTime's ToBinary & FromBinary. long data = _store.ReadInt64(); return(DateTime.FromBinary(data)); case ResourceTypeCode.TimeSpan: long ticks = _store.ReadInt64(); return(new TimeSpan(ticks)); // Special types case ResourceTypeCode.ByteArray: { int len = _store.ReadInt32(); if (len < 0) { throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, len)); } if (_ums == null) { if (len > _store.BaseStream.Length) { throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, len)); } return(_store.ReadBytes(len)); } if (len > _ums.Length - _ums.Position) { throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, len)); } byte[] bytes = new byte[len]; int r = _ums.Read(bytes, 0, len); Debug.Assert(r == len, "ResourceReader needs to use a blocking read here. (Call _store.ReadBytes(len)?)"); return(bytes); } case ResourceTypeCode.Stream: { int len = _store.ReadInt32(); if (len < 0) { throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, len)); } if (_ums == null) { byte[] bytes = _store.ReadBytes(len); // Lifetime of memory == lifetime of this stream. return(new PinnedBufferMemoryStream(bytes)); } // make sure we don't create an UnmanagedMemoryStream that is longer than the resource stream. if (len > _ums.Length - _ums.Position) { throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, len)); } // For the case that we've memory mapped in the .resources // file, just return a Stream pointing to that block of memory. unsafe { return(new UnmanagedMemoryStream(_ums.PositionPointer, len, len, FileAccess.Read)); } } default: if (typeCode < ResourceTypeCode.StartOfUserTypes) { throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch); } break; } // Normal serialized objects int typeIndex = typeCode - ResourceTypeCode.StartOfUserTypes; return(DeserializeObject(typeIndex)); }
internal static bool CanCache(ResourceTypeCode value) { Debug.Assert(value >= 0, "negative ResourceTypeCode. What?"); return(value <= ResourceTypeCode.LastPrimitive); }
private String TypeNameFromTypeCode(ResourceTypeCode typeCode) { Contract.Requires(typeCode >= 0, "can't be negative"); if (typeCode < ResourceTypeCode.StartOfUserTypes) { Contract.Assert(!String.Equals(typeCode.ToString(), "LastPrimitive"), "Change ResourceTypeCode metadata order so LastPrimitive isn't what Enum.ToString prefers."); return "ResourceTypeCode." + typeCode.ToString(); } else { int typeIndex = typeCode - ResourceTypeCode.StartOfUserTypes; Contract.Assert(typeIndex >= 0 && typeIndex < _typeTable.Length, "TypeCode is broken or corrupted!"); long oldPos = _store.BaseStream.Position; try { _store.BaseStream.Position = _typeNamePositions[typeIndex]; return _store.ReadString(); } finally { _store.BaseStream.Position = oldPos; } } }
internal Object LoadObjectV2(int pos, out ResourceTypeCode typeCode) { Contract.Assert(_store != null, "ResourceReader is closed!"); Contract.Assert(_version >= 2, ".resources file was not a V2 (or higher) .resources file!"); try { // mega try-catch performs exceptionally bad on x64; factored out body into // _LoadObjectV2 and wrap here. return _LoadObjectV2(pos, out typeCode); } catch (EndOfStreamException eof) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_TypeMismatch"), eof); } catch (ArgumentOutOfRangeException e) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_TypeMismatch"), e); } }
private unsafe object _LoadObjectV2(int pos, out ResourceTypeCode typeCode) { this._store.BaseStream.Seek(this._dataSectionOffset + pos, SeekOrigin.Begin); typeCode = (ResourceTypeCode) this._store.Read7BitEncodedInt(); switch (typeCode) { case ResourceTypeCode.Null: return null; case ResourceTypeCode.String: return this._store.ReadString(); case ResourceTypeCode.Boolean: return this._store.ReadBoolean(); case ResourceTypeCode.Char: return (char) this._store.ReadUInt16(); case ResourceTypeCode.Byte: return this._store.ReadByte(); case ResourceTypeCode.SByte: return this._store.ReadSByte(); case ResourceTypeCode.Int16: return this._store.ReadInt16(); case ResourceTypeCode.UInt16: return this._store.ReadUInt16(); case ResourceTypeCode.Int32: return this._store.ReadInt32(); case ResourceTypeCode.UInt32: return this._store.ReadUInt32(); case ResourceTypeCode.Int64: return this._store.ReadInt64(); case ResourceTypeCode.UInt64: return this._store.ReadUInt64(); case ResourceTypeCode.Single: return this._store.ReadSingle(); case ResourceTypeCode.Double: return this._store.ReadDouble(); case ResourceTypeCode.Decimal: return this._store.ReadDecimal(); case ResourceTypeCode.DateTime: return DateTime.FromBinary(this._store.ReadInt64()); case ResourceTypeCode.TimeSpan: return new TimeSpan(this._store.ReadInt64()); case ResourceTypeCode.ByteArray: { int count = this._store.ReadInt32(); if (count < 0) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourceDataLengthInvalid", new object[] { count })); } if (this._ums == null) { if (count > this._store.BaseStream.Length) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourceDataLengthInvalid", new object[] { count })); } return this._store.ReadBytes(count); } if (count > (this._ums.Length - this._ums.Position)) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourceDataLengthInvalid", new object[] { count })); } byte[] buffer = new byte[count]; this._ums.Read(buffer, 0, count); return buffer; } case ResourceTypeCode.Stream: { int num4 = this._store.ReadInt32(); if (num4 < 0) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourceDataLengthInvalid", new object[] { num4 })); } if (this._ums == null) { return new PinnedBufferMemoryStream(this._store.ReadBytes(num4)); } if (num4 > (this._ums.Length - this._ums.Position)) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourceDataLengthInvalid", new object[] { num4 })); } return new UnmanagedMemoryStream(this._ums.PositionPointer, (long) num4, (long) num4, FileAccess.Read, true); } } if (typeCode < ResourceTypeCode.StartOfUserTypes) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_TypeMismatch")); } int typeIndex = ((int) typeCode) - 0x40; return this.DeserializeObject(typeIndex); }
/// <summary> /// Constructor /// </summary> /// <param name="name">Full name including assembly of type</param> /// <param name="code">User type code</param> public UserResourceType(string name, ResourceTypeCode code) { this.name = name; this.code = code; }
internal static bool CanCache(ResourceTypeCode value) { Contract.Assert(value >= 0, "negative ResourceTypeCode. What?"); return value <= ResourceTypeCode.LastPrimitive; }
internal Object LoadObject(int pos, out ResourceTypeCode typeCode) { if (_version == 1) { Object o = LoadObjectV1(pos); typeCode = (o is String) ? ResourceTypeCode.String : ResourceTypeCode.StartOfUserTypes; return o; } return LoadObjectV2(pos, out typeCode); }
public SimpleResData(ResourceTypeCode typeCode, HexSpan codeSpan, HexPosition position, uint length) : base(typeCode, codeSpan, new HexSpan(position, length), new HexSpan(position, length)) { }
[System.Security.SecuritySafeCritical] // auto-generated private Object _LoadObjectV2(int pos, out ResourceTypeCode typeCode) { _store.BaseStream.Seek(_dataSectionOffset+pos, SeekOrigin.Begin); typeCode = (ResourceTypeCode) _store.Read7BitEncodedInt(); BCLDebug.Log("RESMGRFILEFORMAT", "LoadObjectV2 type: "+typeCode+" pos: 0x"+_store.BaseStream.Position.ToString("x", CultureInfo.InvariantCulture)); switch(typeCode) { case ResourceTypeCode.Null: return null; case ResourceTypeCode.String: return _store.ReadString(); case ResourceTypeCode.Boolean: return _store.ReadBoolean(); case ResourceTypeCode.Char: return (char) _store.ReadUInt16(); case ResourceTypeCode.Byte: return _store.ReadByte(); case ResourceTypeCode.SByte: return _store.ReadSByte(); case ResourceTypeCode.Int16: return _store.ReadInt16(); case ResourceTypeCode.UInt16: return _store.ReadUInt16(); case ResourceTypeCode.Int32: return _store.ReadInt32(); case ResourceTypeCode.UInt32: return _store.ReadUInt32(); case ResourceTypeCode.Int64: return _store.ReadInt64(); case ResourceTypeCode.UInt64: return _store.ReadUInt64(); case ResourceTypeCode.Single: return _store.ReadSingle(); case ResourceTypeCode.Double: return _store.ReadDouble(); case ResourceTypeCode.Decimal: return _store.ReadDecimal(); case ResourceTypeCode.DateTime: // Use DateTime's ToBinary & FromBinary. Int64 data = _store.ReadInt64(); return DateTime.FromBinary(data); case ResourceTypeCode.TimeSpan: Int64 ticks = _store.ReadInt64(); return new TimeSpan(ticks); // Special types case ResourceTypeCode.ByteArray: { int len = _store.ReadInt32(); if (len < 0) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourceDataLengthInvalid", len)); } if (_ums == null) { if (len > _store.BaseStream.Length) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourceDataLengthInvalid", len)); } return _store.ReadBytes(len); } if (len > _ums.Length - _ums.Position) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourceDataLengthInvalid", len)); } byte[] bytes = new byte[len]; int r = _ums.Read(bytes, 0, len); Contract.Assert(r == len, "ResourceReader needs to use a blocking read here. (Call _store.ReadBytes(len)?)"); return bytes; } case ResourceTypeCode.Stream: { int len = _store.ReadInt32(); if (len < 0) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourceDataLengthInvalid", len)); } if (_ums == null) { byte[] bytes = _store.ReadBytes(len); // Lifetime of memory == lifetime of this stream. return new PinnedBufferMemoryStream(bytes); } // make sure we don't create an UnmanagedMemoryStream that is longer than the resource stream. if (len > _ums.Length - _ums.Position) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourceDataLengthInvalid", len)); } // For the case that we've memory mapped in the .resources // file, just return a Stream pointing to that block of memory. unsafe { return new UnmanagedMemoryStream(_ums.PositionPointer, len, len, FileAccess.Read, true); } } default: if (typeCode < ResourceTypeCode.StartOfUserTypes) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_TypeMismatch")); } break; } // Normal serialized objects #if FEATURE_SERIALIZATION int typeIndex = typeCode - ResourceTypeCode.StartOfUserTypes; return DeserializeObject(typeIndex); #else throw new NotSupportedException(Environment.GetResourceString("NotSupported_ResourceObjectSerialization")); #endif // FEATURE_SERIALIZATION }
internal object LoadObject(int pos, out ResourceTypeCode typeCode) { if (this._version == 1) { object obj2 = this.LoadObjectV1(pos); typeCode = (obj2 is string) ? ResourceTypeCode.String : ResourceTypeCode.StartOfUserTypes; return obj2; } return this.LoadObjectV2(pos, out typeCode); }
internal static bool CanCache(ResourceTypeCode value) { return(value <= ResourceTypeCode.TimeSpan); }
internal Object LoadObjectV2(int pos, out ResourceTypeCode typeCode) { BCLDebug.Assert(_store != null, "ResourceReader is closed!"); BCLDebug.Assert(_version >= 2, ".resources file was not a V2 (or higher) .resources file!"); _store.BaseStream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin); typeCode = (ResourceTypeCode)_store.Read7BitEncodedInt(); BCLDebug.Log("RESMGRFILEFORMAT", "LoadObjectV2 type: " + typeCode + " pos: 0x" + _store.BaseStream.Position.ToString("x", CultureInfo.InvariantCulture)); switch (typeCode) { case ResourceTypeCode.Null: return(null); case ResourceTypeCode.String: return(_store.ReadString()); case ResourceTypeCode.Boolean: return(_store.ReadBoolean()); case ResourceTypeCode.Char: return((char)_store.ReadUInt16()); case ResourceTypeCode.Byte: return(_store.ReadByte()); case ResourceTypeCode.SByte: return(_store.ReadSByte()); case ResourceTypeCode.Int16: return(_store.ReadInt16()); case ResourceTypeCode.UInt16: return(_store.ReadUInt16()); case ResourceTypeCode.Int32: return(_store.ReadInt32()); case ResourceTypeCode.UInt32: return(_store.ReadUInt32()); case ResourceTypeCode.Int64: return(_store.ReadInt64()); case ResourceTypeCode.UInt64: return(_store.ReadUInt64()); case ResourceTypeCode.Single: return(_store.ReadSingle()); case ResourceTypeCode.Double: return(_store.ReadDouble()); case ResourceTypeCode.Decimal: return(_store.ReadDecimal()); case ResourceTypeCode.DateTime: // Use DateTime's ToBinary & FromBinary. Int64 data = _store.ReadInt64(); return(DateTime.FromBinary(data)); case ResourceTypeCode.TimeSpan: Int64 ticks = _store.ReadInt64(); return(new TimeSpan(ticks)); // Special types case ResourceTypeCode.ByteArray: { int len = _store.ReadInt32(); if (_ums == null) { return(_store.ReadBytes(len)); } if (len > _ums.Length - _ums.Position) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourceDataTooLong")); } byte[] bytes = new byte[len]; int r = _ums.Read(bytes, 0, len); BCLDebug.Assert(r == len, "ResourceReader needs to use a blocking read here. (Call _store.ReadBytes(len)?)"); return(bytes); } case ResourceTypeCode.Stream: { int len = _store.ReadInt32(); if (_ums == null) { byte[] bytes = _store.ReadBytes(len); // Lifetime of memory == lifetime of this stream. return(new PinnedBufferMemoryStream(bytes)); } // make sure we don't create an UnmanagedMemoryStream that is longer than the resource stream. if (len > _ums.Length - _ums.Position) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourceDataTooLong")); } // For the case that we've memory mapped in the .resources // file, just return a Stream pointing to that block of memory. unsafe { return(new UnmanagedMemoryStream(_ums.PositionPointer, len, len, FileAccess.Read, true)); } } default: BCLDebug.Assert(typeCode >= ResourceTypeCode.StartOfUserTypes, String.Format(CultureInfo.InvariantCulture, "ResourceReader: Unsupported ResourceTypeCode in .resources file! {0}", typeCode)); // Throw new exception? break; } // Normal serialized objects int typeIndex = typeCode - ResourceTypeCode.StartOfUserTypes; return(DeserializeObject(typeIndex)); }