ResourceReader.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. //
  2. // System.Resources.ResourceReader.cs
  3. //
  4. // Authors:
  5. // Duncan Mak <[email protected]>
  6. // Nick Drochak <[email protected]>
  7. // Dick Porter <[email protected]>
  8. //
  9. // (C) 2001, 2002 Ximian Inc, http://www.ximian.com
  10. //
  11. using System.Collections;
  12. using System.Resources;
  13. using System.IO;
  14. using System.Text;
  15. using System.Runtime.Serialization;
  16. using System.Runtime.Serialization.Formatters.Binary;
  17. namespace System.Resources
  18. {
  19. public sealed class ResourceReader : IResourceReader, IEnumerable, IDisposable
  20. {
  21. BinaryReader reader;
  22. IFormatter formatter;
  23. internal int resourceCount = 0;
  24. int typeCount = 0;
  25. Type[] types;
  26. int[] hashes;
  27. long[] positions;
  28. int dataSectionOffset;
  29. long nameSectionOffset;
  30. // Constructors
  31. public ResourceReader (Stream stream)
  32. {
  33. if (stream == null)
  34. throw new ArgumentNullException ("Value cannot be null.");
  35. if (!stream.CanRead)
  36. throw new ArgumentException ("Stream was not readable.");
  37. reader = new BinaryReader(stream, Encoding.UTF8);
  38. formatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.File|StreamingContextStates.Persistence));
  39. ReadHeaders();
  40. }
  41. public ResourceReader (string fileName)
  42. {
  43. if (fileName == null)
  44. throw new ArgumentNullException ("Path cannot be null.");
  45. if (!System.IO.File.Exists (fileName))
  46. throw new FileNotFoundException ("Could not find file " + Path.GetFullPath(fileName));
  47. reader = new BinaryReader (new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read));
  48. formatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.File|StreamingContextStates.Persistence));
  49. ReadHeaders();
  50. }
  51. /* Read the ResourceManager header and the
  52. * ResourceReader header.
  53. */
  54. private void ReadHeaders()
  55. {
  56. try {
  57. int manager_magic = reader.ReadInt32();
  58. if(manager_magic != ResourceManager.MagicNumber) {
  59. throw new ArgumentException("Stream is not a valid .resources file!");
  60. }
  61. int manager_ver = reader.ReadInt32();
  62. int manager_len = reader.ReadInt32();
  63. /* We know how long the header is, even if
  64. * the version number is too new
  65. */
  66. if(manager_ver > ResourceManager.HeaderVersionNumber) {
  67. reader.BaseStream.Seek(manager_len, SeekOrigin.Current);
  68. } else {
  69. string reader_class=reader.ReadString();
  70. if(!reader_class.StartsWith("System.Resources.ResourceReader")) {
  71. throw new NotSupportedException("This .resources file requires reader class " + reader_class);
  72. }
  73. string set_class=reader.ReadString();
  74. if(!set_class.StartsWith(typeof(ResourceSet).FullName) && !set_class.StartsWith("System.Resources.RuntimeResourceSet")) {
  75. throw new NotSupportedException("This .resources file requires set class " + set_class);
  76. }
  77. }
  78. /* Now read the ResourceReader header */
  79. int reader_ver = reader.ReadInt32();
  80. if(reader_ver != 1) {
  81. throw new NotSupportedException("This .resources file requires unsupported set class version: " + reader_ver.ToString());
  82. }
  83. resourceCount = reader.ReadInt32();
  84. typeCount = reader.ReadInt32();
  85. types=new Type[typeCount];
  86. for(int i=0; i<typeCount; i++) {
  87. string type_name=reader.ReadString();
  88. /* FIXME: Should we ask for
  89. * type loading exceptions
  90. * here?
  91. */
  92. types[i]=Type.GetType(type_name);
  93. if(types[i]==null) {
  94. throw new ArgumentException("Could not load type {0}", type_name);
  95. }
  96. }
  97. /* There are between 0 and 7 bytes of
  98. * padding here, consisting of the
  99. * letters PAD. The next item (Hash
  100. * values for each resource name) need
  101. * to be aligned on an 8-byte
  102. * boundary.
  103. */
  104. int pad_align=(int)(reader.BaseStream.Position & 7);
  105. int pad_chars=0;
  106. if(pad_align!=0) {
  107. pad_chars=8-pad_align;
  108. }
  109. for(int i=0; i<pad_chars; i++) {
  110. byte pad_byte=reader.ReadByte();
  111. if(pad_byte!="PAD"[i%3]) {
  112. throw new ArgumentException("Malformed .resources file (padding values incorrect)");
  113. }
  114. }
  115. /* Read in the hash values for each
  116. * resource name. These can be used
  117. * by ResourceSet (calling internal
  118. * methods) to do a fast compare on
  119. * resource names without doing
  120. * expensive string compares (but we
  121. * dont do that yet, so far we only
  122. * implement the Enumerator interface)
  123. */
  124. hashes=new int[resourceCount];
  125. for(int i=0; i<resourceCount; i++) {
  126. hashes[i]=reader.ReadInt32();
  127. }
  128. /* Read in the virtual offsets for
  129. * each resource name
  130. */
  131. positions=new long[resourceCount];
  132. for(int i=0; i<resourceCount; i++) {
  133. positions[i]=reader.ReadInt32();
  134. }
  135. dataSectionOffset = reader.ReadInt32();
  136. nameSectionOffset = reader.BaseStream.Position;
  137. } catch(EndOfStreamException e) {
  138. throw new ArgumentException("Stream is not a valied .resources file! It was possibly truncated.", e);
  139. }
  140. }
  141. /* Cut and pasted from BinaryReader, because it's
  142. * 'protected' there
  143. */
  144. private int Read7BitEncodedInt() {
  145. int ret = 0;
  146. int shift = 0;
  147. byte b;
  148. do {
  149. b = reader.ReadByte();
  150. ret = ret | ((b & 0x7f) << shift);
  151. shift += 7;
  152. } while ((b & 0x80) == 0x80);
  153. return ret;
  154. }
  155. private string ResourceName(int index)
  156. {
  157. lock(this)
  158. {
  159. long pos=positions[index]+nameSectionOffset;
  160. reader.BaseStream.Seek(pos, SeekOrigin.Begin);
  161. /* Read a 7-bit encoded byte length field */
  162. int len=Read7BitEncodedInt();
  163. byte[] str=new byte[len];
  164. reader.Read(str, 0, len);
  165. return Encoding.Unicode.GetString(str);
  166. }
  167. }
  168. private object ResourceValue(int index)
  169. {
  170. lock(this)
  171. {
  172. long pos=positions[index]+nameSectionOffset;
  173. reader.BaseStream.Seek(pos, SeekOrigin.Begin);
  174. /* Read a 7-bit encoded byte length field */
  175. long len=Read7BitEncodedInt();
  176. /* ... and skip that data to the info
  177. * we want, the offset into the data
  178. * section
  179. */
  180. reader.BaseStream.Seek(len, SeekOrigin.Current);
  181. long data_offset=reader.ReadInt32();
  182. reader.BaseStream.Seek(data_offset+dataSectionOffset, SeekOrigin.Begin);
  183. int type_index=Read7BitEncodedInt();
  184. Type type=types[type_index];
  185. if (type==typeof(Byte)) {
  186. return(reader.ReadByte());
  187. /* for some reason Char is serialized */
  188. /*} else if (type==typeof(Char)) {
  189. return(reader.ReadChar());*/
  190. } else if (type==typeof(Decimal)) {
  191. return(reader.ReadDecimal());
  192. } else if (type==typeof(DateTime)) {
  193. return(new DateTime(reader.ReadInt64()));
  194. } else if (type==typeof(Double)) {
  195. return(reader.ReadDouble());
  196. } else if (type==typeof(Int16)) {
  197. return(reader.ReadInt16());
  198. } else if (type==typeof(Int32)) {
  199. return(reader.ReadInt32());
  200. } else if (type==typeof(Int64)) {
  201. return(reader.ReadInt64());
  202. } else if (type==typeof(SByte)) {
  203. return(reader.ReadSByte());
  204. } else if (type==typeof(Single)) {
  205. return(reader.ReadSingle());
  206. } else if (type==typeof(String)) {
  207. return(reader.ReadString());
  208. } else if (type==typeof(TimeSpan)) {
  209. return(new TimeSpan(reader.ReadInt64()));
  210. } else if (type==typeof(UInt16)) {
  211. return(reader.ReadUInt16());
  212. } else if (type==typeof(UInt32)) {
  213. return(reader.ReadUInt32());
  214. } else if (type==typeof(UInt64)) {
  215. return(reader.ReadUInt64());
  216. } else {
  217. /* non-intrinsic types are
  218. * serialized
  219. */
  220. object obj=formatter.Deserialize(reader.BaseStream);
  221. if(obj.GetType() != type) {
  222. /* We got a bogus
  223. * object. This
  224. * exception is the
  225. * best match I could
  226. * find. (.net seems
  227. * to throw
  228. * BadImageFormatException,
  229. * which the docs
  230. * state is used when
  231. * file or dll images
  232. * cant be loaded by
  233. * the runtime.)
  234. */
  235. throw new InvalidOperationException("Deserialized object is wrong type");
  236. }
  237. return(obj);
  238. }
  239. }
  240. }
  241. public void Close ()
  242. {
  243. Dispose(true);
  244. }
  245. public IDictionaryEnumerator GetEnumerator () {
  246. if (reader == null){
  247. throw new InvalidOperationException("ResourceReader is closed.");
  248. }
  249. else {
  250. return new ResourceEnumerator (this);
  251. }
  252. }
  253. IEnumerator IEnumerable.GetEnumerator ()
  254. {
  255. return ((IResourceReader) this).GetEnumerator();
  256. }
  257. void IDisposable.Dispose ()
  258. {
  259. Dispose(true);
  260. }
  261. private void Dispose (bool disposing)
  262. {
  263. if(disposing) {
  264. if(reader!=null) {
  265. reader.Close();
  266. }
  267. }
  268. reader=null;
  269. hashes=null;
  270. positions=null;
  271. types=null;
  272. }
  273. internal class ResourceEnumerator : IDictionaryEnumerator
  274. {
  275. private ResourceReader reader;
  276. private int index = -1;
  277. private bool finished = false;
  278. internal ResourceEnumerator(ResourceReader readerToEnumerate){
  279. reader = readerToEnumerate;
  280. }
  281. public virtual DictionaryEntry Entry
  282. {
  283. get {
  284. if (reader.reader == null)
  285. throw new InvalidOperationException("ResourceReader is closed.");
  286. if (index < 0)
  287. throw new InvalidOperationException("Enumeration has not started. Call MoveNext.");
  288. DictionaryEntry entry = new DictionaryEntry();
  289. entry.Key = Key;
  290. entry.Value = Value;
  291. return entry;
  292. }
  293. }
  294. public virtual object Key
  295. {
  296. get {
  297. if (reader.reader == null)
  298. throw new InvalidOperationException("ResourceReader is closed.");
  299. if (index < 0)
  300. throw new InvalidOperationException("Enumeration has not started. Call MoveNext.");
  301. return (reader.ResourceName(index));
  302. }
  303. }
  304. public virtual object Value
  305. {
  306. get {
  307. if (reader.reader == null)
  308. throw new InvalidOperationException("ResourceReader is closed.");
  309. if (index < 0)
  310. throw new InvalidOperationException("Enumeration has not started. Call MoveNext.");
  311. return(reader.ResourceValue(index));
  312. }
  313. }
  314. public virtual object Current
  315. {
  316. get {
  317. /* Entry does the checking, no
  318. * need to repeat it here
  319. */
  320. return Entry;
  321. }
  322. }
  323. public virtual bool MoveNext ()
  324. {
  325. if (reader.reader == null)
  326. throw new InvalidOperationException("ResourceReader is closed.");
  327. if (finished) {
  328. return false;
  329. }
  330. if (++index < reader.resourceCount){
  331. return true;
  332. }
  333. else {
  334. finished=true;
  335. return false;
  336. }
  337. }
  338. public void Reset () {
  339. if (reader.reader == null)
  340. throw new InvalidOperationException("ResourceReader is closed.");
  341. index = -1;
  342. finished = false;
  343. }
  344. } // internal class ResourceEnumerator
  345. } // public sealed class ResourceReader
  346. } // namespace System.Resources