internal override void Read(BinaryReader reader) { Version = reader.ReadUInt16(); VersionNeededToExtract = reader.ReadUInt16(); Flags = (HeaderFlags) reader.ReadUInt16(); CompressionMethod = (ZipCompressionMethod) reader.ReadUInt16(); LastModifiedTime = reader.ReadUInt16(); LastModifiedDate = reader.ReadUInt16(); Crc = reader.ReadUInt32(); CompressedSize = reader.ReadUInt32(); UncompressedSize = reader.ReadUInt32(); ushort nameLength = reader.ReadUInt16(); ushort extraLength = reader.ReadUInt16(); ushort commentLength = reader.ReadUInt16(); DiskNumberStart = reader.ReadUInt16(); InternalFileAttributes = reader.ReadUInt16(); ExternalFileAttributes = reader.ReadUInt32(); RelativeOffsetOfEntryHeader = reader.ReadUInt32(); byte[] name = reader.ReadBytes(nameLength); Name = DecodeString(name); byte[] extra = reader.ReadBytes(extraLength); byte[] comment = reader.ReadBytes(commentLength); Comment = DecodeString(comment); LoadExtra(extra); }
private void TransformToPNG() { using (MemoryStream ms = new MemoryStream(this.rawData)) { BinaryReader r = new BinaryReader(ms); Bitmap colorImage = new Bitmap(ms); ms.Position = 0; r.ReadBytes(24); if (r.ReadUInt32() == 0x41464C41U) { int length = r.ReadInt32(); length = (int)((length & 0xFF000000) >> 24) | (int)((length & 0x00FF0000) >> 8) | (int)((length & 0x0000FF00) << 8) | (int)((length & 0x000000FF) << 24); using (MemoryStream alphaStream = new MemoryStream(r.ReadBytes(length))) { Bitmap alphaImage = new Bitmap(alphaStream); if (colorImage.Width != alphaImage.Width || colorImage.Height != alphaImage.Height) throw new InvalidDataException("Not a proper TS4 Thumbnail image"); //int[,] rawImage = new int[colorImage.Width, colorImage.Height]; //for (int y = 0; y < colorImage.Height; y++) //{ // for (int x = 0; x < colorImage.Width; x++) // { // Color color = colorImage.GetPixel(x, y); // byte alpha = alphaImage.GetPixel(x, y).R; // rawImage[x, y] = Color.FromArgb(alpha, color).ToArgb(); // } //} colorImage = UpdateAlpha(colorImage, alphaImage); this.Image = colorImage; } } this.Image = colorImage; } }
public BAR(Stream file) { if (!file.CanRead || !file.CanSeek) { throw new NotSupportedException("Cannot read or seek in stream"); } using (var br = new BinaryReader(file)) { if (file.Length < 16 || br.ReadUInt32() != 0x01524142) { throw new InvalidDataException("Invalid signature"); } int fileC = br.ReadInt32(); fileList = new List<BARFile>(fileC); Debug.WriteLine("Loading BAR with " + fileC + " files"); file.Position = 16; for (int i = 0; i < fileC; i++) { var bf = new BARFile(); bf.type = br.ReadUInt32(); { byte[] b = br.ReadBytes(4); Buffer.BlockCopy(b, 0, bf._id, 0, 4); } long lpos = file.Position + 8; uint pos = br.ReadUInt32(); int len = br.ReadInt32(); file.Position = pos; bf.data = br.ReadBytes(len); fileList.Add(bf); file.Position = lpos; } } //BinaryReader should close file }
public bool Load(string path) { using (FileStream fs = new FileStream(path, FileMode.Open)) { using (BinaryReader reader = new BinaryReader(fs)) { for (int i = 0; i < 8; ++i) { reader.ReadBytes(4); } uint count = reader.ReadUInt32(); uint offset = reader.ReadUInt32(); fs.Position = (long)offset; try { for (int i = 0; i < count; ++i) { ulong ext = reader.ReadUInt64(); ulong fpath = reader.ReadUInt64(); uint language = reader.ReadUInt32(); reader.ReadBytes(4); uint id = reader.ReadUInt32(); reader.ReadBytes(4); this.Add(ext, fpath, language, id); } } catch (Exception) { return false; } } } return true; }
public ITI(string filename) { impi fil = new impi(); // FIXME: Possible re-use this.noteName = MidiHelper.OctaveMacro(); using (FileStream rop = new FileStream( filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (BinaryReader bob = new BinaryReader(rop)) { byte[] mal = bob.ReadBytes(Marshal.SizeOf(fil)); this.iti_instrument = IOHelper.xread<impi>(fil,mal); // Get Samples { impx[] samp = new impx[iti_instrument.impNumberOfSamples]; for (int i = 0; i < iti_instrument.impNumberOfSamples;i++) samp[i] = IOHelper.xread<impx>( samp[i], bob.ReadBytes(Marshal.SizeOf(samp[i])) ); this.ITI_SMPH = samp; } bob.Close(); rop.Close(); mal = null; } }
static void Main(string[] args) { OpenFileDialog OpenFile = new OpenFileDialog(); OpenFile.Multiselect = false; OpenFile.Title = "Cartridge"; OpenFile.Filter = "GBA Files (.gba)|*.gba"; OpenFile.FilterIndex = 1; string Cartridge; Console.WriteLine("Gneiss - Game Boy Advance Cartridge Reader."); Console.CursorVisible = false; if (OpenFile.ShowDialog() == DialogResult.OK) { Cartridge = OpenFile.FileName; BinaryReader BR = new BinaryReader(File.OpenRead(Cartridge)); BR.BaseStream.Seek(0xA0, SeekOrigin.Begin); Console.WriteLine("\n\nCartridge Name: {0}", Encoding.UTF8.GetString(BR.ReadBytes(12))); BR.BaseStream.Seek(0xAC, SeekOrigin.Begin); Console.WriteLine("Serial: {0}", Encoding.UTF8.GetString(BR.ReadBytes(4))); BR.BaseStream.Seek(0x108, SeekOrigin.Begin); Console.WriteLine("Name: {0}", Encoding.UTF8.GetString(BR.ReadBytes(24))); Console.Read(); } }
public static byte[] GetWaveData(BinaryReader file, ref WaveInfo waveInfo) { byte[] returnData; //Read the wave file header from the buffer. waveInfo.ChunkID = file.ReadInt32(); waveInfo.FileSize = file.ReadInt32(); waveInfo.RiffType = file.ReadInt32(); waveInfo.FormatID = file.ReadInt32(); waveInfo.FormatSize = file.ReadInt32(); waveInfo.FormatCode = file.ReadInt16(); waveInfo.Channels = file.ReadInt16(); waveInfo.SampleRate = file.ReadInt32(); waveInfo.FormatAverageBps = file.ReadInt32(); waveInfo.FormatBlockAlign = file.ReadInt16(); waveInfo.BitDepth = file.ReadInt16(); if (waveInfo.FormatSize == 18) { // Read any extra values waveInfo.FormatExtraSize = file.ReadInt16(); file.ReadBytes(waveInfo.FormatExtraSize); } waveInfo.DataID = file.ReadInt32(); waveInfo.DataSize = file.ReadInt32(); // Store the audio data of the wave file to a byte array. returnData = file.ReadBytes(waveInfo.DataSize); return returnData; }
public static bool ReadFile(string FileName) { LCMeshReader.OpenedFile = FileName; LCMeshReader.pMesh = new tMeshContainer(); BinaryReader b = new BinaryReader( new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.Read)); LCMeshReader.pMesh.HeaderInfo = new tHeaderInfo(); LCMeshReader.pMesh.HeaderInfo.Format = b.ReadBytes(4); LCMeshReader.pMesh.HeaderInfo.Version = b.ReadInt32(); LCMeshReader.pMesh.HeaderInfo.MeshDataSize = b.ReadInt32(); LCMeshReader.pMesh.HeaderInfo.MeshCount = b.ReadUInt32(); LCMeshReader.pMesh.HeaderInfo.VertexCount = b.ReadUInt32(); LCMeshReader.pMesh.HeaderInfo.JointCount = b.ReadUInt32(); LCMeshReader.pMesh.HeaderInfo.TextureMaps = b.ReadUInt32(); LCMeshReader.pMesh.HeaderInfo.NormalCount = b.ReadUInt32(); LCMeshReader.pMesh.HeaderInfo.ObjCount = b.ReadUInt32(); LCMeshReader.pMesh.HeaderInfo.UnknownCount = b.ReadUInt32(); LCMeshReader.pMesh.FileName = b.ReadBytes(b.ReadInt32()); LCMeshReader.pMesh.Scale = b.ReadSingle(); LCMeshReader.pMesh.Value1 = b.ReadUInt32(); LCMeshReader.pMesh.FilePath = FileName; bool flag = false; if (LCMeshReader.pMesh.HeaderInfo.Version == 16) { if (LCMeshReader.ReadV10(b, b.BaseStream.Position)) flag = true; } else if (LCMeshReader.pMesh.HeaderInfo.Version == 17 && LCMeshReader.ReadV11(b, b.BaseStream.Position)) flag = true; b.Close(); return flag; }
/// <summary> /// The read. /// </summary> /// <param name="client"> /// </param> /// <param name="packet"> /// </param> public static void Read(Client client, byte[] packet) { LogUtil.Debug(DebugInfoDetail.Network, "\r\nReceived:\r\n" + HexOutput.Output(packet)); MemoryStream m_stream = new MemoryStream(packet); BinaryReader m_reader = new BinaryReader(m_stream); // now we should do password check and then send OK or Error // sending OK now m_stream.Position = 8; short userNameLength = IPAddress.NetworkToHostOrder(m_reader.ReadInt16()); string userName = Encoding.ASCII.GetString(m_reader.ReadBytes(userNameLength)); short loginKeyLength = IPAddress.NetworkToHostOrder(m_reader.ReadInt16()); string loginKey = Encoding.ASCII.GetString(m_reader.ReadBytes(loginKeyLength)); LoginEncryption loginEncryption = new LoginEncryption(); if (loginEncryption.IsValidLogin(loginKey, client.ServerSalt, userName)) { client.IsBot = true; byte[] chars = AccountCharacterList.Create(userName); LogUtil.Debug(DebugInfoDetail.Network, "\r\nReceived:\r\n" + HexOutput.Output(chars)); client.Send(chars); } else { byte[] loginerr = LoginError.Create(); client.Send(loginerr); client.Server.DisconnectClient(client); } }
public static ConnectionSettings Read(byte[] data) { var cs = new ConnectionSettings(); using (var ms = new MemoryStream(data)) using (var br = new BinaryReader(ms)) { cs.Version = br.ReadInt32(); cs.Counter = br.ReadInt32(); cs.Autodetect = (Autodetect)br.ReadInt32(); var len = br.ReadInt32(); cs.ProxyServer = Utf8.GetString(br.ReadBytes(len)); len = br.ReadInt32(); cs.ExtraData = Utf8.GetString(br.ReadBytes(len)); len = br.ReadInt32(); cs.AutodetectScript = Utf8.GetString(br.ReadBytes(len)); // So damn lazy. using (var ms2 = new MemoryStream()) { var ba = new byte[Environment.SystemPageSize]; while ((len = br.Read(ba, 0, ba.Length)) != 0) { ms2.Write(ba, 0, len); } cs.Junk = ms2.ToArray(); } } return cs; }
/// <summary> /// Creatis this object and sets all it properties /// </summary> /// <param name="binaryReader"></param> internal CLSID(BinaryReader binaryReader) { Data1 = binaryReader.ReadBytes(4).Reverse().ToArray(); Data2 = binaryReader.ReadBytes(2).Reverse().ToArray(); Data3 = binaryReader.ReadBytes(2).Reverse().ToArray(); Data4 = binaryReader.ReadBytes(8).Reverse().ToArray(); }
public static Certificate GetSignedCertificate(Uri apiUri, CertificateStore certStore) { using (WebClient client = new WebClient()) { client.Headers.Add("User-Agent", GetUserAgent()); byte[] data = client.DownloadData(apiUri.AbsoluteUri + "?cmd=dlc&email=" + certStore.Certificate.IssuedTo.EmailAddress.Address); using (BinaryReader bR = new BinaryReader(new MemoryStream(data))) { int errorCode = bR.ReadInt32(); if (errorCode != 0) { string message = Encoding.UTF8.GetString(bR.ReadBytes(bR.ReadInt32())); string remoteStackTrace = Encoding.UTF8.GetString(bR.ReadBytes(bR.ReadInt32())); throw new BitChatException(message); } Certificate cert = new Certificate(bR); if (!cert.IssuedTo.EmailAddress.Equals(certStore.Certificate.IssuedTo.EmailAddress) || (cert.PublicKeyEncryptionAlgorithm != certStore.PrivateKey.Algorithm) || (cert.PublicKeyXML != certStore.PrivateKey.GetPublicKey())) throw new BitChatException("Invalid signed certificate received. Please try again."); return cert; } } }
public void Deserialize(byte[] buffer) { if (buffer.Length == 240) { MemoryStream MS = new MemoryStream(buffer); BinaryReader BR = new BinaryReader(MS); ushort length = BR.ReadUInt16(); if (length == 240) { ushort type = BR.ReadUInt16(); if (type == 1124) { Username = Encoding.ASCII.GetString(BR.ReadBytes(16)); Username = Username.Replace("\0", ""); BR.ReadBytes(112); Password = Encoding.ASCII.GetString(BR.ReadBytes(16)); BR.ReadBytes(112); Server = Encoding.ASCII.GetString(BR.ReadBytes(16)); Server = Server.Replace("\0", ""); } } BR.Close(); MS.Close(); } }
public static void ReadBlendomatic(FileStream file) { BinaryReader reader = new BinaryReader(file); NumberOfBlendingModes = reader.ReadUInt32(); NumberOfTiles = reader.ReadUInt32(); BlendingModes = new Dictionary<byte, BlendingMode>(); Console.WriteLine("Number of blending modes: " + NumberOfBlendingModes); Console.WriteLine("Number of tiles: " + NumberOfTiles); for (var i = 0; i < NumberOfBlendingModes; i++ ) { BlendingMode mode; mode.TileSize = reader.ReadUInt32(); mode.Tiles = new Dictionary<byte, byte[]>(); var TileFlags = reader.ReadBytes(31); // all 1 wtf reader.ReadBytes((int)mode.TileSize * 4); for (var j = 0; j < NumberOfTiles; j++) { mode.Tiles[(byte)j] = reader.ReadBytes((int)mode.TileSize); } BlendingModes[(byte)i] = mode; } }
internal override void Read(BinaryReader reader) { Version = reader.ReadUInt16(); VersionNeededToExtract = reader.ReadUInt16(); Flags = (HeaderFlags) reader.ReadUInt16(); CompressionMethod = (ZipCompressionMethod) reader.ReadUInt16(); LastModifiedTime = reader.ReadUInt16(); LastModifiedDate = reader.ReadUInt16(); Crc = reader.ReadUInt32(); CompressedSize = reader.ReadUInt32(); UncompressedSize = reader.ReadUInt32(); ushort nameLength = reader.ReadUInt16(); ushort extraLength = reader.ReadUInt16(); ushort commentLength = reader.ReadUInt16(); DiskNumberStart = reader.ReadUInt16(); InternalFileAttributes = reader.ReadUInt16(); ExternalFileAttributes = reader.ReadUInt32(); RelativeOffsetOfEntryHeader = reader.ReadUInt32(); byte[] name = reader.ReadBytes(nameLength); Name = DecodeString(name); byte[] extra = reader.ReadBytes(extraLength); byte[] comment = reader.ReadBytes(commentLength); Comment = DecodeString(comment); LoadExtra(extra); var unicodePathExtra = Extra.FirstOrDefault(u => u.Type == ExtraDataType.UnicodePathExtraField); if (unicodePathExtra != null) { Name = ((ExtraUnicodePathExtraField)unicodePathExtra).UnicodeName; } }
/// <summary> /// Creates a new FAR3Archive instance from a path. /// </summary> /// <param name="Path">The path to the archive.</param> public FAR3Archive(string Path) { m_ArchivePath = Path; if (isReadingSomething == false) { isReadingSomething = true; try { m_Reader = new BinaryReader(File.Open(Path, FileMode.Open, FileAccess.Read, FileShare.Read)); } catch (Exception) { throw new FAR3Exception("Could not open the specified archive - " + Path + "! (FAR3Archive())"); } string Header = Encoding.ASCII.GetString(m_Reader.ReadBytes(8)); uint Version = m_Reader.ReadUInt32(); if ((Header != "FAR!byAZ") || (Version != 3)) { throw new FAR3Exception("Archive wasn't a valid FAR V.3 archive! (FAR3Archive())"); } uint ManifestOffset = m_Reader.ReadUInt32(); m_ManifestOffset = ManifestOffset; m_Reader.BaseStream.Seek(ManifestOffset, SeekOrigin.Begin); uint NumFiles = m_Reader.ReadUInt32(); for (int i = 0; i < NumFiles; i++) { Far3Entry Entry = new Far3Entry(); Entry.DecompressedFileSize = m_Reader.ReadUInt32(); byte[] Dummy = m_Reader.ReadBytes(3); Entry.CompressedFileSize = (uint)((Dummy[0] << 0) | (Dummy[1] << 8) | (Dummy[2]) << 16); Entry.DataType = m_Reader.ReadByte(); Entry.DataOffset = m_Reader.ReadUInt32(); //Entry.HasFilename = m_Reader.ReadUInt16(); Entry.IsCompressed = m_Reader.ReadByte(); Entry.AccessNumber = m_Reader.ReadByte(); Entry.FilenameLength = m_Reader.ReadUInt16(); Entry.TypeID = m_Reader.ReadUInt32(); Entry.FileID = m_Reader.ReadUInt32(); Entry.Filename = Encoding.ASCII.GetString(m_Reader.ReadBytes(Entry.FilenameLength)); if (!m_Entries.ContainsKey(Entry.Filename)) m_Entries.Add(Entry.Filename, Entry); m_EntriesList.Add(Entry); m_EntryByID.Add(Entry.FileID, Entry); //isn't this a bad idea? i have a feeling this is a bad idea... } //Keep the stream open, it helps peformance. //m_Reader.Close(); isReadingSomething = false; } }
/// <summary> Parses the Replay.Messages.Events file. </summary> /// <param name="buffer"> Buffer containing the contents of the replay.messages.events file. </param> /// <returns> A list of chat messages parsed from the buffer. </returns> public static void Parse(Replay replay, byte[] buffer) { using (var stream = new MemoryStream(buffer)) { using (var reader = new BinaryReader(stream)) { int totalTime = 0; while (reader.BaseStream.Position < reader.BaseStream.Length) { // While not EOF var message = new ChatMessage(); var time = ParseTimestamp(reader); // sometimes we only have a header for the message if (reader.BaseStream.Position >= reader.BaseStream.Length) break; message.PlayerId = reader.ReadByte(); // I believe this 'PlayerId' is an index for this client list, which can include observers // var player = replay.ClientList[message.PlayerId]; totalTime += time; var opCode = reader.ReadByte(); if (opCode == 0x80) reader.ReadBytes(4); else if (opCode == 0x83) reader.ReadBytes(8); else if (opCode == 2 && message.PlayerId <= 10) { if (message.PlayerId == 80) continue; message.MessageTarget = (ChatMessageTarget)(opCode & 7); var length = reader.ReadByte(); if ((opCode & 8) == 8) length += 64; if ((opCode & 16) == 16) length += 128; message.Message = Encoding.UTF8.GetString(reader.ReadBytes(length)); } else { } if (message.Message != null) { message.Timestamp = new TimeSpan(0, 0, (int)Math.Round(totalTime / 16.0)); replay.ChatMessages.Add(message); } } } } }
internal void Read(BinaryReader reader, float CoordZ, float scale) { SkinVertIndex = BitConverter.ToUInt32(reader.ReadBytes(4), 0); for (int i = 0; i < SkinVertPos.Length; i++) SkinVertPos[i] = BitConverter.ToSingle(reader.ReadBytes(4), 0)* scale; SkinVertPos[2] *= CoordZ; }
public void Read(BinaryReader reader, float CoordZ, float scale) { Position = new float[3]; for (int i = 0; i < Position.Length; i++) { Position[i] = BitConverter.ToSingle(reader.ReadBytes(4), 0) * scale; } NormalVector = new float[3]; for (int i = 0; i < NormalVector.Length; i++) { NormalVector[i] = BitConverter.ToSingle(reader.ReadBytes(4), 0); } UV = new float[2]; for (int i = 0; i < UV.Length; i++) { UV[i] = BitConverter.ToSingle(reader.ReadBytes(4), 0); } BoneNum = new WORD[2]; for (int i = 0; i < BoneNum.Length; i++) { BoneNum[i] = BitConverter.ToUInt16(reader.ReadBytes(2), 0); } BoneWeight = reader.ReadByte(); NonEdgeFlag = reader.ReadByte(); Position[2] *= CoordZ; NormalVector[2] *= CoordZ; }
private static Model LoadFromBIN(string pModelFile) { BinaryReader reader = new BinaryReader(new FileStream(pModelFile, FileMode.Open)); int numberOfVertices = reader.ReadInt32(); int floatsPerVertex = 6; Vertices = new float[numberOfVertices * floatsPerVertex]; byte[] byteArray = new byte[Vertices.Length * sizeof(float)]; byteArray = reader.ReadBytes(byteArray.Length); Buffer.BlockCopy(byteArray, 0, Vertices, 0, byteArray.Length); int numberOfTriangles = reader.ReadInt32(); Indices = new int[numberOfTriangles * 3]; byteArray = new byte[Indices.Length * sizeof(int)]; byteArray = reader.ReadBytes(Indices.Length * sizeof(int)); Buffer.BlockCopy(byteArray, 0, Indices, 0, byteArray.Length); reader.Close(); ModelMesh mesh = new ModelMesh(Vertices, Indices, false); List<ModelMesh> meshes = new List<ModelMesh>(); meshes.Add(mesh); return new Model(meshes); }
public RegistryHive(string file) { if (!File.Exists(file)) throw new FileNotFoundException(); using (FileStream stream = File.OpenRead(file)) { using (BinaryReader reader = new BinaryReader(stream)) { byte[] buf = reader.ReadBytes(4); if (buf[0] != 'r' || buf[1] != 'e' || buf[2] != 'g' || buf[3] != 'f') throw new NotSupportedException(); reader.ReadBytes(8); buf = reader.ReadBytes(8); long timestamp = BitConverter.ToInt64(buf, 0); this.WasExported = (timestamp == 0) ? true : false; //fast-forward reader.BaseStream.Position += (0x1000 + 0x20 + 4)-reader.BaseStream.Position; this.RootKey = new NodeKey(reader); } } }
internal NameResolutionRecord(BinaryReader reader) { UInt16 type = reader.ReadUInt16(); int valueLength = reader.ReadUInt16(); if (type != EndRecordType) { int entriesLength = valueLength; if (type == Ip6RecordType) { this.IsIpVersion6 = true; this.IpAddress = reader.ReadBytes(Ip6Length); entriesLength -= Ip6Length; } else { this.IsIpVersion6 = false; this.IpAddress = reader.ReadBytes(Ip4Length); entriesLength -= Ip4Length; } this.DnsEntries = this.ReadDnsEntries(reader, entriesLength); int remainderLength = valueLength % ValueAlignmentBoundary; if (remainderLength > 0) { reader.ReadBytes(ValueAlignmentBoundary - remainderLength); // Read fill bytes to boundary. } } }
public void ByteArraySegmentedStream_ReadBytesTest() { var arr = new byte[100]; for (byte i = 0; i < 100; i++) arr[i] = i; var stream = new ByteArraySegmentedStream(true); stream.AddSegment(new ArraySegment<byte>(arr, 0, 10)); stream.AddSegment(new ArraySegment<byte>(arr, 10, 25)); stream.AddSegment(new ArraySegment<byte>(arr, 5, 10)); var reader = new BinaryReader(stream); var bs = reader.ReadBytes(5); Assert.AreEqual(bs.Length, 5); for (byte i = 0; i < 5; i++) Assert.AreEqual(i, bs[i]); bs = reader.ReadBytes(10); Assert.AreEqual(bs.Length, 10); for (byte i = 0; i < 10; i++) Assert.AreEqual(i + 5, bs[i]); bs = reader.ReadBytes(100); Assert.AreEqual(bs.Length, 30); for (byte i = 0; i < 20; i++) Assert.AreEqual(i + 15, bs[i]); for (byte i = 0; i < 10; i++) Assert.AreEqual(i + 5, bs[i + 20]); }
public RPF7File(Stream inputStream, String filname = "") { this.Filename = filname; Stream = inputStream; Info = new Structs.RPF7Header(Stream); if (new string(Info.Magic) != "RPF7") { throw new Exception("Invalid RPF Magic"); } sixteenRoundsDecrypt = (Info.Flag >> 28) == 0xf; if (sixteenRoundsDecrypt) { throw new Exception("Needed to be tested first"); } using (BinaryReader binaryStream = new BinaryReader(AES.DecryptStream(new StreamKeeper(this.Stream), sixteenRoundsDecrypt))) { MemoryStream entriesInfo = new MemoryStream(binaryStream.ReadBytes(0x10 * Info.EntriesCount)); MemoryStream filenames = new MemoryStream(binaryStream.ReadBytes(Info.EntriesNamesLength)); this.Root = Entry.CreateFromHeader(new Structs.RPF7EntryInfoTemplate(entriesInfo), this, entriesInfo, filenames); } if (!(this.Root is DirectoryEntry)) { throw new Exception("Expected root to be directory"); } }
public FDSFile(BinaryReader r) { byte[] tmp = r.ReadBytes(4); int numdisks; if (tmp.SequenceEqual(Check)) { numdisks = r.ReadByte(); ExtraData = r.ReadBytes(11); } else if (tmp.SequenceEqual(CheckAlt)) { // compensate (won't write identically) r.BaseStream.Seek(0, SeekOrigin.Begin); numdisks = (int)(r.BaseStream.Length / 65500); ExtraData = new byte[11]; } else { throw new InvalidOperationException("Bad Header!"); } if (r.BaseStream.Length - r.BaseStream.Position != numdisks * 65500) throw new InvalidOperationException("Bad File Length!"); while (numdisks > 0) { Disks.Add(new FDSDisk(r)); numdisks--; } }
public static byte[] UncompressStream(Stream stream, int filesize, int memsize) { BinaryReader r = new BinaryReader(stream); long end = stream.Position + filesize; byte[] uncdata = new byte[memsize]; BinaryWriter bw = new BinaryWriter(new MemoryStream(uncdata)); byte[] data = r.ReadBytes(2); if (checking) if (data.Length != 2) throw new InvalidDataException("Hit unexpected end of file at " + stream.Position); int datalen = (((data[0] & 0x80) != 0) ? 4 : 3) * (((data[0] & 0x01) != 0) ? 2 : 1); data = r.ReadBytes(datalen); if (checking) if (data.Length != datalen) throw new InvalidDataException("Hit unexpected end of file at " + stream.Position); long realsize = 0; for (int i = 0; i < data.Length; i++) realsize = (realsize << 8) + data[i]; if (checking) if (realsize != memsize) throw new InvalidDataException(String.Format( "Resource data indicates size does not match index at 0x{0}. Read 0x{1}. Expected 0x{2}.", stream.Position.ToString("X8"), realsize.ToString("X8"), memsize.ToString("X8"))); while (stream.Position < end) { Dechunk(stream, bw); } if (checking) if (bw.BaseStream.Position != memsize) throw new InvalidDataException(String.Format("Read 0x{0:X8} bytes. Expected 0x{1:X8}.", bw.BaseStream.Position, memsize)); bw.Close(); return uncdata; }
public InstallShieldPackage(string filename, int priority) { this.priority = priority; s = FileSystem.Open(filename); // Parse package header BinaryReader reader = new BinaryReader(s); uint signature = reader.ReadUInt32(); if (signature != 0x8C655D13) throw new InvalidDataException("Not an Installshield package"); reader.ReadBytes(8); /*var FileCount = */reader.ReadUInt16(); reader.ReadBytes(4); /*var ArchiveSize = */reader.ReadUInt32(); reader.ReadBytes(19); var TOCAddress = reader.ReadInt32(); reader.ReadBytes(4); var DirCount = reader.ReadUInt16(); // Parse the directory list s.Seek(TOCAddress, SeekOrigin.Begin); BinaryReader TOCreader = new BinaryReader(s); for (var i = 0; i < DirCount; i++) ParseDirectory(TOCreader); }
public void UOExtPacket(IClientPeer peer, byte header, byte[] buffer, int offset, short length) { MemoryStream ms = new MemoryStream(buffer, offset, length); BinaryReader br = new BinaryReader(ms); byte sequence = br.ReadByte(); switch (sequence) { case (0x00): byte version = br.ReadByte(); byte[] uoextmd5 = br.ReadBytes(16); byte[] uoextguimd5 = br.ReadBytes(16); if (version != 0) { peer.Close(); } else { if (!ByteArrayCompare(uoextmd5, Dll.UOExt.MD5)) { peer.Send(new Handshake(0x01)); peer.Send(Dll.UOExt.SimpleHeader); foreach (DllContent dc in Dll.UOExt.Content) { peer.Send(dc); } return; } else if (!ByteArrayCompare(uoextguimd5, Dll.UOExtGUI.MD5)) { peer.Send(new Handshake(0x02)); peer.Send(Dll.UOExtGUI.SimpleHeader); foreach (DllContent dc in Dll.UOExtGUI.Content) { peer.Send(dc); } } else { peer.Send(new Handshake(0x00)); } peer.Send(m_libraryList); peer.Send(m_pluginsList); } break; case (0x03): for (short i = 0; i < Dll.Dlls.Length; i++) { peer.Send(Dll.Dlls[i].Header); foreach (DllContent dc in Dll.Dlls[i].Content) { peer.Send(dc); } } peer.Send(m_initComplete); break; } }
private static AntiForgeryToken DeserializeImpl(BinaryReader reader) { byte b = reader.ReadByte(); if (b != 1) { return null; } AntiForgeryToken antiForgeryToken = new AntiForgeryToken(); byte[] data = reader.ReadBytes(16); antiForgeryToken.SecurityToken = new BinaryBlob(128, data); antiForgeryToken.IsSessionToken = reader.ReadBoolean(); if (!antiForgeryToken.IsSessionToken) { bool flag = reader.ReadBoolean(); if (flag) { byte[] data2 = reader.ReadBytes(32); antiForgeryToken.ClaimUid = new BinaryBlob(256, data2); } else { antiForgeryToken.Username = reader.ReadString(); } antiForgeryToken.AdditionalData = reader.ReadString(); } if (reader.BaseStream.ReadByte() != -1) { return null; } return antiForgeryToken; }
public FAR1Archive(string Path) { m_Path = Path; m_Reader = new BinaryReader(File.Open(Path, FileMode.Open)); string Header = Encoding.ASCII.GetString(m_Reader.ReadBytes(8)); uint Version = m_Reader.ReadUInt32(); if ((Header != "FAR!byAZ") || (Version != 1)) { throw(new Exception("Archive wasn't a valid FAR V.1 archive!")); } m_ManifestOffset = m_Reader.ReadUInt32(); m_Reader.BaseStream.Seek(m_ManifestOffset, SeekOrigin.Begin); m_NumFiles = m_Reader.ReadUInt32(); for (int i = 0; i < m_NumFiles; i++) { FarEntry Entry = new FarEntry(); Entry.DataLength = m_Reader.ReadInt32(); Entry.DataLength2 = m_Reader.ReadInt32(); Entry.DataOffset = m_Reader.ReadInt32(); Entry.FilenameLength = m_Reader.ReadInt16(); Entry.Filename = Encoding.ASCII.GetString(m_Reader.ReadBytes(Entry.FilenameLength)); m_Entries.Add(Entry); } m_Reader.Close(); }
private OricFileInfo[] ReadFTDosDirectory() { OricFileInfo[] diskDirectory = null; int iDirFileCount = 0; UInt16 i16DirectoryIndex = 1; UInt16 i16EntryIndex = 1; System.Text.Encoding enc = System.Text.Encoding.ASCII; ArrayList diskCatalog = new ArrayList(); Byte bNextTrack = 20; Byte bNextSector = 2; Byte bCurrTrack = bNextTrack; Byte bCurrSector = bNextSector; Boolean bMoreDirectories = true; while (bMoreDirectories) { iDirFileCount = 0; Byte[] sectorData = base.ReadSector(bNextTrack, bNextSector); System.IO.MemoryStream stm = new System.IO.MemoryStream(sectorData, 0, sectorData.Length); System.IO.BinaryReader rdr = new System.IO.BinaryReader(stm); Byte[] bByteArray = new Byte[32]; bByteArray = rdr.ReadBytes(2); bNextTrack = rdr.ReadByte(); bNextSector = rdr.ReadByte(); for (int iLoop = 0; iLoop < 14; iLoop++) { OricFileInfo diskFile = new OricFileInfo(); diskFile.MediaType = OricExplorer.MediaType.DiskFile; diskFile.FirstTrack = rdr.ReadByte(); diskFile.FirstSector = rdr.ReadByte(); diskFile.Folder = base.diskFolder; diskFile.ParentName = base.diskPathname; Byte bProtection = rdr.ReadByte(); if (bProtection == 'U') { diskFile.Protection = OricProgram.ProtectionStatus.Unlocked; } else if (bProtection == 'L') { diskFile.Protection = OricProgram.ProtectionStatus.Locked; } else { diskFile.Protection = OricProgram.ProtectionStatus.Unlocked; } bByteArray = rdr.ReadBytes(8); if ((bByteArray[0] != 0xFF && bByteArray[0] != 0x00 && bByteArray[0] != 0x6C) && diskFile.FirstTrack != 0xFF) { String strFilename = enc.GetString(bByteArray).Trim(); if (strFilename.Length > 0) { // Read decimal point between filename and extension bByteArray = rdr.ReadBytes(1); // Read the Extension bByteArray = rdr.ReadBytes(3); String strExtension = enc.GetString(bByteArray).Trim(); diskFile.Name = strFilename; diskFile.Extension = strExtension; if (strExtension.Length > 0) { diskFile.ProgramName = String.Format("{0}.{1}", diskFile.Name, diskFile.Extension); } else { diskFile.ProgramName = diskFile.Name; } bByteArray = rdr.ReadBytes(1); if (strExtension.Equals("SCR")) { diskFile.Format = OricProgram.ProgramFormat.TextScreen; } else if (strExtension.Equals("BAS")) { diskFile.Format = OricProgram.ProgramFormat.BasicProgram; } else if (strExtension.Equals("CMD") || strExtension.Equals("BIN") || strExtension.Equals("SYS")) { diskFile.Format = OricProgram.ProgramFormat.CodeFile; } else { diskFile.Format = OricProgram.ProgramFormat.UnknownFile; } diskFile.LengthSectors = rdr.ReadByte(); bByteArray = rdr.ReadBytes(1); Byte[] fileDesc = base.ReadSector(diskFile.FirstTrack, diskFile.FirstSector); System.IO.MemoryStream stm2 = new System.IO.MemoryStream(fileDesc, 0, sectorData.Length); System.IO.BinaryReader rdr2 = new System.IO.BinaryReader(stm2); bByteArray = rdr2.ReadBytes(2); diskFile.StartAddress = rdr2.ReadUInt16(); diskFile.EndAddress = (ushort)(diskFile.StartAddress + rdr2.ReadUInt16()); diskFile.ExeAddress = 0; diskFile.AutoRun = OricProgram.AutoRunFlag.Disabled; if ((diskFile.StartAddress == 0x0000 && diskFile.EndAddress == 0x0000) && strExtension != "SYS") { diskFile.Format = OricProgram.ProgramFormat.UnknownFile; } //diskFile.FirstTrack = diskFile.DirectoryIndex = i16DirectoryIndex; diskFile.EntryIndex = i16EntryIndex; diskCatalog.Add(diskFile); iDirFileCount++; } i16EntryIndex++; } else { bByteArray = rdr.ReadBytes(7); //swOutfile.WriteLine(); } } iDirFileCount = 0; if ((bNextTrack == 0xFF && bNextSector == 0) || (bNextTrack == 0x6C && bNextSector == 0x6C) || (bNextTrack == 0x00 && bNextSector == 0x00)) { bMoreDirectories = false; } else { bCurrTrack = bNextTrack; bCurrSector = bNextSector; i16EntryIndex = 1; i16DirectoryIndex++; } } diskDirectory = new OricFileInfo[diskCatalog.Count]; diskCatalog.CopyTo(diskDirectory); return(diskDirectory); }
private void BuildTDosSectorMap2(UInt16[] sectorMap, String diskPathname) { int iFileNum = 1; UInt16 bNextTrack = 0; UInt16 bNextSector = 0; UInt16 bNextDescTrack; UInt16 bNextDescSector; Byte[] bByteArray = new Byte[10]; String strSectorKey = ""; OricFileInfo[] programList = ReadDirectory(diskPathname); foreach (OricFileInfo programInfo in programList) { if (programInfo.Format != OricProgram.ProgramFormat.UnknownFile) { UInt16 bTrack; UInt16 bSector; bTrack = programInfo.FirstTrack; bSector = programInfo.FirstSector; if (bTrack == 0x00 && bSector == 0x00) { // This is the DOS file (FTDOS3-2.sys) so don't process it } else { do { Byte[] bitmapSector = base.ReadSector(bTrack, bSector, ref bNextTrack, ref bNextSector); // Add file descriptor to the sector map UpdateSectorMap(sectorMap, bTrack, bSector, (UInt16)(0x1100 + Convert.ToByte(iFileNum))); bTrack = bNextTrack; bSector = bNextSector; // Safety net /*if (bTrack > tracksPerSide || bNextSector > sectorsPerTrack) * { * // Might have a problem * bSector = 0; * }*/ } while (bSector != 0); strSectorKey = CreateKey(programInfo.FirstTrack, programInfo.FirstSector); bNextTrack = programInfo.FirstTrack; bNextSector = programInfo.FirstSector; do { // Read the file descriptor Byte[] sectorData = base.ReadSector(bNextTrack, bNextSector); System.IO.MemoryStream stm = new System.IO.MemoryStream(sectorData, 0, sectorData.Length); System.IO.BinaryReader rdr = new System.IO.BinaryReader(stm); bNextTrack = rdr.ReadByte(); bNextSector = rdr.ReadByte(); bNextDescTrack = bNextTrack; bNextDescSector = bNextSector; rdr.ReadBytes(4); //Byte bFirstDesc = rdr.ReadByte(); int iDescIndex = 0; int iTotalDescriptors = 125; Byte bDataTrack; Byte bDataSector; bDataTrack = rdr.ReadByte(); bDataSector = rdr.ReadByte(); if (bDataTrack != 0xFF && bDataSector != 0xFF) { UpdateSectorMap(sectorMap, bDataTrack, bDataSector, (UInt16)(0x1000 + Convert.ToByte(iFileNum))); } while (bDataSector != 0xFF && iDescIndex < iTotalDescriptors) { if (bDataSector != 0xFF) { bDataTrack = rdr.ReadByte(); bDataSector = rdr.ReadByte(); if (bDataSector != 0xFF) { UpdateSectorMap(sectorMap, bDataTrack, bDataSector, (UInt16)(0x1000 + Convert.ToByte(iFileNum))); } iDescIndex++; } } strSectorKey = CreateKey(bNextDescTrack, bNextDescSector); } while (bNextDescTrack != 0xFF && bNextDescSector != 0x00); } } iFileNum++; } }
internal UInt16[] BuildSectorMap(String diskPathname) { base.LoadDisk(diskPathname); UInt16 noOfSectors = (UInt16)((tracksPerSide * sectorsPerTrack) * sides); UInt16[] sectorMap = new UInt16[noOfSectors]; for (int index = 0; index < noOfSectors; index++) { sectorMap[index] = 0xFFFF; } // Mark the disk bitmap UpdateSectorMap(sectorMap, 20, 1, 0x0200); if (diskType == DiskTypes.Master) { SetDOSSectors(sectorMap, 0, 1, 62); } Byte directoryTrack = 0x14; Byte directorySector = 0x02; // Mark Directories UpdateSectorMap(sectorMap, directoryTrack, directorySector, 0x0400); Byte nextDirectoryTrack = directoryTrack; Byte nextDirectorySector = directorySector; while ((directoryTrack != 0xFF) && (directoryTrack != 0x6C && directorySector != 0x6C) && (directoryTrack != 0x00 && directorySector != 0x00)) { Byte[] directory = this.ReadSector(directoryTrack, directorySector); System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(directory, 0, directory.Length); System.IO.BinaryReader binReader = new System.IO.BinaryReader(memoryStream); binReader.ReadBytes(2); nextDirectoryTrack = binReader.ReadByte(); nextDirectorySector = binReader.ReadByte(); //Byte nextFreeEntry = binReader.ReadByte(); Byte noOfFiles = 0; /*if (nextFreeEntry == 0x00) * { * noOfFiles = 15; * } * else * { * }*/ if (directoryTrack != 0x6C && directorySector != 0x6C) { UpdateSectorMap(sectorMap, directoryTrack, directorySector, (UInt16)(0x0400 + noOfFiles)); } directoryTrack = nextDirectoryTrack; directorySector = nextDirectorySector; } BuildTDosSectorMap2(sectorMap, diskPathname); return(sectorMap); }
/*! \brief Private function to read GRF0x2xx headers * * Reads the information about files within the archive... * for archive versions 0x02xx * * \todo Find GRF versions other than just 0x200 (do any exist?) * * \param grf Pointer to the Grf struct to read to * \param error Pointer to a GrfErrorType struct/enum for error reporting * \param callback Function to call for each read file. It should return 0 if * everything is fine, 1 if everything is fine (but further * reading should stop), or -1 if there has been an error * \return 0 if everything went fine, 1 if something went wrong */ static uint GRF_readVer2_info(System.IO.BinaryReader br, Grf grf, GrfOpenCallback callback) { uint i, offset, len, len2; byte[] buf, zbuf; /* Check grf */ if (grf.version != 0x200) { throw new Exception("GE_NSUP"); } /* Read the original and compressed sizes */ buf = br.ReadBytes(8); /* Allocate memory and read the compressed file table */ len = GrfSupport.LittleEndian32(buf, 0); zbuf = br.ReadBytes((int)len); if (0 == (len2 = GrfSupport.LittleEndian32(buf, 4))) { return(0); } /* Allocate memory and uncompress the compressed file table */ Array.Resize(ref buf, (int)len2); var stream = new InflaterInputStream(new MemoryStream(zbuf)); stream.Read(buf, 0, buf.Length); stream.Close(); /* Read information about each file */ for (i = offset = 0; i < grf.nfiles; i++) { /* Grab the filename length */ len = GrfSupport.getCStringLength(buf, offset) + 1; /* Make sure its not too large */ if (len >= GrfTypes.GRF_NAMELEN) { throw new Exception("GE_CORRUPTED"); } /* Grab filename */ GrfFile file = new GrfFile(); file.name = GrfSupport.getCString(buf, offset); offset += len; /* Grab the rest of the information */ file.compressed_len = GrfSupport.LittleEndian32(buf, (int)offset); file.compressed_len_aligned = GrfSupport.LittleEndian32(buf, (int)offset + 4); file.real_len = GrfSupport.LittleEndian32(buf, (int)offset + 8); file.flags = buf[offset + 0xC]; file.pos = GrfSupport.LittleEndian32(buf, (int)(offset + 0xD)) + (uint)GRF_HEADER_FULL_LEN; file.hash = GrfSupport.GRF_NameHash(file.name); file.name = NormalizePath(file.name); grf.files.Add(file.name, file); /* Advance to the next file */ offset += 0x11; /* Run the callback, if we have one */ if (callback != null) { callback.doCallback(file); if (!callback.hasReturned()) { throw new Exception("NO_RETURN"); } if (callback.Response < 0) { /* Callback function had an error, so we * have an error */ return(1); } else if (callback.Response > 0) { /* Callback function found the file it needed, * just exit now */ return(0); } } } /* Calling functions will set success... * GRF_SETERR(error,GE_SUCCESS,GRF_readVer2_info); */ return(0); }
/// <summary> /// Encrypt a token with an RSA public key /// </summary> /// <param name="plainText">Plaintext string</param> /// <returns>Encrypted string</returns> public string Encrypt(string plainText) { //// read pem public key Stream s = System.Reflection.Assembly.GetExecutingAssembly(). GetManifestResourceStream("KountRisSdk.kount.rsa.public.key"); System.IO.StreamReader reader = new System.IO.StreamReader(s, Encoding.UTF8); string pem = reader.ReadToEnd(); string header = String.Format("-----BEGIN PUBLIC KEY-----"); string footer = String.Format("-----END PUBLIC KEY-----"); int start = pem.IndexOf(header, StringComparison.Ordinal) + header.Length; int end = pem.IndexOf(footer, start, StringComparison.Ordinal) - start; byte[] key = Convert.FromBase64String(pem.Substring(start, end)); UnicodeEncoding converter = new UnicodeEncoding(); byte[] plainBytes = converter.GetBytes(plainText); RSACryptoServiceProvider rsa = null; //// encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1" byte[] seqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 }; byte[] seq = new byte[15]; //// Read the asn.1 encoded SubjectPublicKeyInfo blob System.IO.MemoryStream mem = new System.IO.MemoryStream(key); System.IO.BinaryReader binr = new System.IO.BinaryReader(mem); byte bt = 0; ushort twobytes = 0; try { twobytes = binr.ReadUInt16(); if (twobytes == 0x8130) { //// data read as little endian order //// (actual data order for Sequence is 30 81) binr.ReadByte(); //// advance 1 byte } else if (twobytes == 0x8230) { binr.ReadInt16(); //// advance 2 bytes } else { return(null); } seq = binr.ReadBytes(15); //// read the Sequence OID if (!this.CompareBytearrays(seq, seqOID)) { //// make sure Sequence for OID is correct return(null); } twobytes = binr.ReadUInt16(); if (twobytes == 0x8103) { //// data read as little endian order (actual data order for Bit String is 03 81) binr.ReadByte(); //// advance 1 byte } else if (twobytes == 0x8203) { binr.ReadInt16(); //// advance 2 bytes } else { return(null); } bt = binr.ReadByte(); if (bt != 0x00) { //// expect null byte next return(null); } twobytes = binr.ReadUInt16(); if (twobytes == 0x8130) { //// data read as little endian order (actual data order for Sequence is 30 81) binr.ReadByte(); //// advance 1 byte } else if (twobytes == 0x8230) { binr.ReadInt16(); //// advance 2 bytes } else { return(null); } twobytes = binr.ReadUInt16(); byte lowbyte = 0x00; byte highbyte = 0x00; if (twobytes == 0x8102) { //// data read as little endian order //// (actual data order for Integer is 02 81) lowbyte = binr.ReadByte(); //// read next bytes which is bytes in modulus } else if (twobytes == 0x8202) { highbyte = binr.ReadByte(); //// advance 2 bytes lowbyte = binr.ReadByte(); } else { return(null); } byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; int modsize = BitConverter.ToInt32(modint, 0); int firstbyte = binr.PeekChar(); if (firstbyte == 0x00) { //// if first byte (highest order) of modulus is zero, don't include it binr.ReadByte(); //// skip this null byte modsize -= 1; //// reduce modulus buffer size by 1 } byte[] modulus = binr.ReadBytes(modsize); //// read the modulus bytes if (binr.ReadByte() != 0x02) { //// expect an Integer for the exponent data return(null); } int expbytes = (int)binr.ReadByte(); byte[] exponent = binr.ReadBytes(expbytes); //// create RSACryptoServiceProvider instance and initialize public key rsa = new RSACryptoServiceProvider(); RSAParameters rsaKeyInfo = new RSAParameters(); rsaKeyInfo.Modulus = modulus; rsaKeyInfo.Exponent = exponent; rsa.ImportParameters(rsaKeyInfo); } finally { binr.Close(); } byte[] encryptedBytes = rsa.Encrypt(plainBytes, false); return(Convert.ToBase64String(encryptedBytes)); }
internal static ZigbeeCommand Parse(byte[] buffer, out uint bytesRead) { if (buffer == null) { throw new ArgumentNullException("buffer"); } bytesRead = 0; System.IO.BinaryReader br = new System.IO.BinaryReader(new MemoryStream(buffer)); var SOP = br.ReadByte(); if (SOP != 0x02) { throw new ArgumentException("Invalid SOP. Not a Zigbee response"); } if (buffer.Length < 4) { return(null); } var cmd = SwapUInt16(br.ReadUInt16()); var NACK = cmd & 32768; var ACK = cmd & 16384; var Response = cmd & 4096; var CommandNumber = 4095 & cmd; var LEN = br.ReadByte(); //pos=3 if (buffer.Length < 5 + LEN) { return(null); } var payload = br.ReadBytes(LEN); var fcs = br.ReadByte(); bytesRead = 5u + LEN; var xor = XOR(buffer, 1u, bytesRead - 2u); if ((xor ^ fcs) != 0) { throw new ArgumentException("Invalid message"); } if (CidResponseTypes == null) { lock (lockObject) { if (CidResponseTypes == null) { LoadResponseTypes(); } } } if (CidResponseTypes.ContainsKey(cmd)) { var type = CidResponseTypes[cmd]; try { return(type.Invoke(new object[] { payload }) as ZigbeeCommand); } catch (System.Exception ex) { return(new UnknownCidResponse(cmd, payload)); } } else if (CidResponseCreators.ContainsKey(cmd)) { var type = CidResponseCreators[cmd]; return(type.Invoke(null, new object[] { payload }) as ZigbeeCommand); } else { return(new UnknownCidResponse(cmd, payload)); } }
public override System.Collections.Generic.Queue <Moonfish.Tags.BlamPointer> ReadFields(System.IO.BinaryReader binaryReader) { System.Collections.Generic.Queue <Moonfish.Tags.BlamPointer> pointerQueue = new System.Collections.Generic.Queue <Moonfish.Tags.BlamPointer>(base.ReadFields(binaryReader)); this.Type = ((TypeEnum)(binaryReader.ReadInt16())); this.fieldpad = binaryReader.ReadBytes(2); this.fieldpad0 = binaryReader.ReadBytes(16); this.AnchorOffset = binaryReader.ReadPoint(); this.WidthScale = binaryReader.ReadSingle(); this.HeightScale = binaryReader.ReadSingle(); this.UnitHudAuxilaryPanelScalingFlags = ((ScalingFlags)(binaryReader.ReadInt16())); this.fieldpad1 = binaryReader.ReadBytes(2); this.fieldpad2 = binaryReader.ReadBytes(20); this.InterfaceBitmap = binaryReader.ReadTagReference(); this.DefaultColor = binaryReader.ReadColourA1R1G1B1(); this.FlashingColor = binaryReader.ReadColourA1R1G1B1(); this.FlashPeriod = binaryReader.ReadSingle(); this.FlashDelay = binaryReader.ReadSingle(); this.NumberOfFlashes = binaryReader.ReadInt16(); this.UnitHudAuxilaryPanelFlashFlags = ((FlashFlags)(binaryReader.ReadInt16())); this.FlashLength = binaryReader.ReadSingle(); this.DisabledColor = binaryReader.ReadColourA1R1G1B1(); this.fieldpad3 = binaryReader.ReadBytes(4); this.SequenceIndex = binaryReader.ReadInt16(); this.fieldpad4 = binaryReader.ReadBytes(2); pointerQueue.Enqueue(binaryReader.ReadBlamPointer(452)); this.fieldpad5 = binaryReader.ReadBytes(4); this.AnchorOffset0 = binaryReader.ReadPoint(); this.WidthScale0 = binaryReader.ReadSingle(); this.HeightScale0 = binaryReader.ReadSingle(); this.UnitHudAuxilaryPanelUnitHudAuxilaryPanelScalingFlags0 = ((UnitHudAuxilaryPanelScalingFlags0)(binaryReader.ReadInt16())); this.fieldpad6 = binaryReader.ReadBytes(2); this.fieldpad7 = binaryReader.ReadBytes(20); this.MeterBitmap = binaryReader.ReadTagReference(); this.ColorAtMeterMinimum = binaryReader.ReadColourR1G1B1(); this.ColorAtMeterMaximum = binaryReader.ReadColourR1G1B1(); this.FlashColor = binaryReader.ReadColourR1G1B1(); this.EmptyColor = binaryReader.ReadColourA1R1G1B1(); this.UnitHudAuxilaryPanelFlags = ((Flags)(binaryReader.ReadByte())); this.MinumumMeterValue = binaryReader.ReadByte(); this.SequenceIndex0 = binaryReader.ReadInt16(); this.AlphaMultiplier = binaryReader.ReadByte(); this.AlphaBias = binaryReader.ReadByte(); this.ValueScale = binaryReader.ReadInt16(); this.Opacity = binaryReader.ReadSingle(); this.Translucency = binaryReader.ReadSingle(); this.DisabledColor0 = binaryReader.ReadColourA1R1G1B1(); pointerQueue.Enqueue(binaryReader.ReadBlamPointer(0)); this.fieldpad8 = binaryReader.ReadBytes(4); this.MinimumFractionCutoff = binaryReader.ReadSingle(); this.UnitHudAuxilaryPanelUnitHudAuxilaryPanelFlags0 = ((UnitHudAuxilaryPanelFlags0)(binaryReader.ReadInt32())); this.fieldpad9 = binaryReader.ReadBytes(24); this.fieldpad10 = binaryReader.ReadBytes(64); return(pointerQueue); }
public static object[][] ReadToObject(string dbfFileName, string tableName) { System.IO.Stream stream = new System.IO.FileStream(dbfFileName, System.IO.FileMode.Open); System.IO.BinaryReader reader = new System.IO.BinaryReader(stream); byte[] buffer = reader.ReadBytes(Marshal.SizeOf(typeof(DbfHeader))); DbfHeader header = IRI.Ket.IO.BinaryStream.ByteArrayToStructure <DbfHeader>(buffer); List <DbfFieldDescriptor> columns = new List <DbfFieldDescriptor>(); if ((header.LengthOfHeader - 33) % 32 != 0) { throw new NotImplementedException(); } int numberOfFields = (header.LengthOfHeader - 33) / 32; for (int i = 0; i < numberOfFields; i++) { buffer = reader.ReadBytes(Marshal.SizeOf(typeof(DbfFieldDescriptor))); columns.Add(DbfFieldDescriptor.Parse(buffer, DbfFileFormat.fieldsEncoding)); } //System.Data.DataTable result = MakeTableSchema(tableName, columns); var result = new object[header.NumberOfRecords][]; ((FileStream)reader.BaseStream).Seek(header.LengthOfHeader, SeekOrigin.Begin); for (int i = 0; i < header.NumberOfRecords; i++) { // First we'll read the entire record into a buffer and then read each field from the buffer // This helps account for any extra space at the end of each record and probably performs better buffer = reader.ReadBytes(header.LengthOfEachRecord); BinaryReader recordReader = new BinaryReader(new MemoryStream(buffer)); // All dbf field records begin with a deleted flag field. Deleted - 0x2A (asterisk) else 0x20 (space) if (recordReader.ReadChar() == '*') { continue; } object[] values = new object[columns.Count]; for (int j = 0; j < columns.Count; j++) { int fieldLenth = columns[j].Length; values[j] = MapFunction[columns[j].Type](recordReader.ReadBytes(fieldLenth)); } recordReader.Close(); result[i] = values; } reader.Close(); stream.Close(); return(result); }
public ActionResult Edit([Bind(Include = "intPetID,strPetNumber,strMicrochipID,strPetName,intPetTypeID,intGenderID,intBreedID,dtmDateofBirth,dblWeight,isBlind,isDeaf,isAggressive,isDeceased,isAllergic,strColor,strNotes,isDeceased,intOwnerID")] TPet tPet, HttpPostedFileBase upload) { try { if (ModelState.IsValid) { SqlParameter[] param = new SqlParameter[] { new SqlParameter("@intPetID", tPet.intPetID), new SqlParameter("@strPetName", tPet.strPetName), new SqlParameter("@strPetNumber", tPet.strPetNumber), new SqlParameter("@strMicrochipID", tPet.strMicrochipID), new SqlParameter("@intPetTypeID", tPet.intPetTypeID), //.intPetTypeID), new SqlParameter("@intGenderID", tPet.intGenderID), new SqlParameter("@intBreedID", tPet.intBreedID), new SqlParameter("@dtmDateofBirth", tPet.dtmDateofBirth), new SqlParameter("@dblWeight", tPet.dblWeight), new SqlParameter("@isBlind", tPet.isBlind), new SqlParameter("@isDeaf", tPet.isDeaf), new SqlParameter("@isAggressive", tPet.isAggressive), new SqlParameter("@isDeceased", tPet.isDeceased), new SqlParameter("@isAllergic", tPet.isAllergic), new SqlParameter("@strColor", tPet.strColor), new SqlParameter("@strNotes", tPet.strNotes), new SqlParameter("@intOwnerID", tPet.intOwnerID) }; db.Database.ExecuteSqlCommand("uspUpdatePets @strPetName, @strPetNumber, @strMicrochipID, @intPetTypeID, @intGenderID, @intBreedID, @dtmDateofBirth, @dblWeight, @isBlind, @isDeaf, @isAggressive, @isDeceased, @isAllergic, @strColor, @strNotes, @intOwnerID", param); //PetImage if (upload != null && upload.ContentLength > 0) { var image = new TPetImage { strFileName = Path.GetFileName(upload.FileName), strFileType = Path.GetExtension(upload.FileName), strContentType = upload.ContentType, intPetID = tPet.intPetID }; using (var reader = new System.IO.BinaryReader(upload.InputStream)) { image.imgContent = reader.ReadBytes(upload.ContentLength); } tPet.TPetImages = new List <TPetImage> { image }; } db.Entry(tPet.TPetImage).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } } catch (RetryLimitExceededException /* dex */) { //Log the error (uncomment dex variable name and add a line here to write a log. ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator."); } ViewBag.intPetTypeID = new SelectList(db.TPetTypes, "intPetTypeID", "strPetType", tPet.intPetTypeID); ViewBag.intGenderID = new SelectList(db.TGenders, "intGenderID", "strGender", tPet.intGenderID); ViewBag.intOwnerID = new SelectList(db.TOwners, "intOwnerID", "strLastName", tPet.intOwnerID); ViewBag.intBreedID = new SelectList(db.TBreeds, "intBreedID", "strBreedName", tPet.intBreedID); ViewBag.intPetID = new SelectList(db.TPets, "intPetID", "strPetNumber", tPet.intPetID); return(View(tPet.TPetImage)); }
public static void DDSToTexture(GameDatabase.TextureInfo texture, bool inPlace, Vector2 size, string cache = null, bool mipmaps = false) { /** * Kopernicus Planetary System Modifier * ==================================== * Created by: BryceSchroeder and Teknoman117 (aka. Nathaniel R. Lewis) * Maintained by: Thomas P., NathanKell and KillAshley * Additional Content by: Gravitasi, aftokino, KCreator, Padishar, Kragrathea, OvenProofMars, zengei, MrHappyFace * ------------------------------------------------------------- * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA * * This library is intended to be used as a plugin for Kerbal Space Program * which is copyright 2011-2015 Squad. Your usage of Kerbal Space Program * itself is governed by the terms of its EULA, not the license above. * * https://kerbalspaceprogram.com */ // Borrowed from stock KSP 1.0 DDS loader (hi Mike!) // Also borrowed the extra bits from Sarbian. byte[] buffer = System.IO.File.ReadAllBytes(texture.file.fullPath); System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(new System.IO.MemoryStream(buffer)); uint num = binaryReader.ReadUInt32(); if (num == DDSHeaders.DDSValues.uintMagic) { DDSHeaders.DDSHeader dDSHeader = new DDSHeaders.DDSHeader(binaryReader); if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDX10) { new DDSHeaders.DDSHeaderDX10(binaryReader); } bool alpha = (dDSHeader.dwFlags & 0x00000002) != 0; bool fourcc = (dDSHeader.dwFlags & 0x00000004) != 0; bool rgb = (dDSHeader.dwFlags & 0x00000040) != 0; bool alphapixel = (dDSHeader.dwFlags & 0x00000001) != 0; bool luminance = (dDSHeader.dwFlags & 0x00020000) != 0; bool rgb888 = dDSHeader.ddspf.dwRBitMask == 0x000000ff && dDSHeader.ddspf.dwGBitMask == 0x0000ff00 && dDSHeader.ddspf.dwBBitMask == 0x00ff0000; //bool bgr888 = dDSHeader.ddspf.dwRBitMask == 0x00ff0000 && dDSHeader.ddspf.dwGBitMask == 0x0000ff00 && dDSHeader.ddspf.dwBBitMask == 0x000000ff; bool rgb565 = dDSHeader.ddspf.dwRBitMask == 0x0000F800 && dDSHeader.ddspf.dwGBitMask == 0x000007E0 && dDSHeader.ddspf.dwBBitMask == 0x0000001F; bool argb4444 = dDSHeader.ddspf.dwABitMask == 0x0000f000 && dDSHeader.ddspf.dwRBitMask == 0x00000f00 && dDSHeader.ddspf.dwGBitMask == 0x000000f0 && dDSHeader.ddspf.dwBBitMask == 0x0000000f; bool rbga4444 = dDSHeader.ddspf.dwABitMask == 0x0000000f && dDSHeader.ddspf.dwRBitMask == 0x0000f000 && dDSHeader.ddspf.dwGBitMask == 0x000000f0 && dDSHeader.ddspf.dwBBitMask == 0x00000f00; bool mipmap = (dDSHeader.dwCaps & DDSHeaders.DDSPixelFormatCaps.MIPMAP) != (DDSHeaders.DDSPixelFormatCaps) 0u; bool isNormalMap = ((dDSHeader.ddspf.dwFlags & 524288u) != 0u || (dDSHeader.ddspf.dwFlags & 2147483648u) != 0u); Vector2 newSize = size == default(Vector2) ? new Vector2(dDSHeader.dwWidth, dDSHeader.dwHeight) : size; if (fourcc) { if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT1) { if (inPlace && !texture.isReadable) { //This is a small hack to re-load the texture, even when it isn't readable. Unfortnately, //we can't control compression, mipmaps, or anything else really, as the texture is still //marked as unreadable. This will update the size and pixel data however. Texture2D tmpTex = new Texture2D((int)newSize.x, (int)newSize.y, TextureFormat.ARGB32, mipmap); Texture2D tmpTexSrc = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, TextureFormat.DXT1, mipmap); tmpTexSrc.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position))); Color32[] colors = tmpTexSrc.GetPixels32(); colors = ResizePixels(colors, tmpTexSrc.width, tmpTexSrc.height, (int)newSize.x, (int)newSize.y); tmpTex.SetPixels32(colors); tmpTex.Apply(false); //size using JPG to force DXT1 byte[] file = ImageConversion.EncodeToPNG(tmpTex);//tmpTex.EncodeToJPG(); if (cache != null) { Directory.GetParent(cache).Create(); System.IO.File.WriteAllBytes(cache, file); } texture.texture.LoadImage(file); GameObject.DestroyImmediate(tmpTex); GameDatabase.DestroyImmediate(tmpTexSrc); } else if (inPlace) { texture.texture.Resize((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, TextureFormat.RGB24, mipmap); texture.texture.Compress(false); texture.texture.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position))); texture.texture.Apply(false, !texture.isReadable); } else { GameObject.DestroyImmediate(texture.texture); texture.texture = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, TextureFormat.DXT1, mipmap); texture.texture.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position))); texture.texture.Apply(false, !texture.isReadable); } } else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT3) { if (inPlace && !texture.isReadable) { //This is a small hack to re-load the texture, even when it isn't readable. Unfortnately, //we can't control compression, mipmaps, or anything else really, as the texture is still //marked as unreadable. This will update the size and pixel data however. Texture2D tmpTex = new Texture2D((int)newSize.x, (int)newSize.y, TextureFormat.ARGB32, mipmap); Texture2D tmpTexSrc = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, (TextureFormat)11, mipmap); tmpTexSrc.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position))); Color32[] colors = tmpTexSrc.GetPixels32(); colors = ResizePixels(colors, tmpTexSrc.width, tmpTexSrc.height, (int)newSize.x, (int)newSize.y); tmpTex.SetPixels32(colors); tmpTex.Apply(false); //size using JPG to force DXT5 byte[] file = ImageConversion.EncodeToPNG(tmpTex); if (cache != null) { Directory.GetParent(cache).Create(); System.IO.File.WriteAllBytes(cache, file); } texture.texture.LoadImage(file); GameObject.DestroyImmediate(tmpTex); GameDatabase.DestroyImmediate(tmpTexSrc); } else if (inPlace) { texture.texture.Resize((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, (TextureFormat)11, mipmap); texture.texture.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position))); texture.texture.Apply(false, !texture.isReadable); } else { GameObject.DestroyImmediate(texture.texture); texture.texture = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, (TextureFormat)11, mipmap); texture.texture.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position))); texture.texture.Apply(false, !texture.isReadable); } } else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT5) { if (inPlace && !texture.isReadable) { //This is a small hack to re-load the texture, even when it isn't readable. Unfortnately, //we can't control compression, mipmaps, or anything else really, as the texture is still //marked as unreadable. This will update the size and pixel data however. Texture2D tmpTex = new Texture2D((int)newSize.x, (int)newSize.y, TextureFormat.ARGB32, mipmap); Texture2D tmpTexSrc = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, TextureFormat.DXT5, mipmap); tmpTexSrc.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position))); Color32[] colors = tmpTexSrc.GetPixels32(); colors = ResizePixels(colors, tmpTexSrc.width, tmpTexSrc.height, (int)newSize.x, (int)newSize.y); tmpTex.SetPixels32(colors); tmpTex.Apply(false); //size using JPG to force DXT5 byte[] file = ImageConversion.EncodeToPNG(tmpTex); if (cache != null) { Directory.GetParent(cache).Create(); System.IO.File.WriteAllBytes(cache, file); } texture.texture.LoadImage(file); GameObject.DestroyImmediate(tmpTex); GameDatabase.DestroyImmediate(tmpTexSrc); } else if (inPlace) { texture.texture.Resize((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, TextureFormat.ARGB32, mipmap); texture.texture.Compress(false); texture.texture.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position))); texture.texture.Apply(false, !texture.isReadable); } else { GameObject.DestroyImmediate(texture.texture); texture.texture = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, TextureFormat.DXT5, mipmap); texture.texture.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position))); texture.texture.Apply(false, !texture.isReadable); } } else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT2) { Debug.Log("DXT2 not supported"); } else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT4) { Debug.Log("DXT4 not supported: "); } else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDX10) { Debug.Log("DX10 dds not supported: "); } else { fourcc = false; } } if (!fourcc) { TextureFormat textureFormat = TextureFormat.ARGB32; bool ok = true; if (rgb && (rgb888 /*|| bgr888*/)) { // RGB or RGBA format textureFormat = alphapixel ? TextureFormat.RGBA32 : TextureFormat.RGB24; } else if (rgb && rgb565) { // Nvidia texconv B5G6R5_UNORM textureFormat = TextureFormat.RGB565; } else if (rgb && alphapixel && argb4444) { // Nvidia texconv B4G4R4A4_UNORM textureFormat = TextureFormat.ARGB4444; } else if (rgb && alphapixel && rbga4444) { textureFormat = TextureFormat.RGBA4444; } else if (!rgb && alpha != luminance) { // A8 format or Luminance 8 textureFormat = TextureFormat.Alpha8; } else { ok = false; Debug.Log("Only DXT1, DXT5, A8, RGB24, RGBA32, RGB565, ARGB4444 and RGBA4444 are supported"); } if (ok) { if (inPlace && !texture.isReadable) { //This is a small hack to re-load the texture, even when it isn't readable. Unfortnately, //we can't control compression, mipmaps, or anything else really, as the texture is still //marked as unreadable. This will update the size and pixel data however. Texture2D tmpTex = new Texture2D((int)newSize.x, (int)newSize.y, TextureFormat.ARGB32, mipmap); Texture2D tmpTexSrc = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, textureFormat, mipmap); tmpTexSrc.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position))); Color32[] colors = tmpTexSrc.GetPixels32(); colors = ResizePixels(colors, tmpTexSrc.width, tmpTexSrc.height, (int)newSize.x, (int)newSize.y); tmpTex.SetPixels32(colors); tmpTex.Apply(false); //size using JPG to force alpha-less byte[] file; if (alphapixel) { file = ImageConversion.EncodeToPNG(tmpTex); } else { file = ImageConversion.EncodeToPNG(tmpTex);//file = tmpTex.EncodeToJPG(); } if (cache != null) { Directory.GetParent(cache).Create(); System.IO.File.WriteAllBytes(cache, file); } texture.texture.LoadImage(file); GameDatabase.DestroyImmediate(tmpTex); GameDatabase.DestroyImmediate(tmpTexSrc); } else if (inPlace) { texture.texture.Resize((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, textureFormat, mipmap); texture.texture.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position))); texture.texture.Apply(false, !texture.isReadable); } else { GameDatabase.DestroyImmediate(texture.texture); texture.texture = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, textureFormat, mipmap); texture.texture.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position))); texture.texture.Apply(false, !texture.isReadable); } } } } else { Debug.Log("Bad DDS header."); } }
public SyncTexture BuildTexture(ObjParser.Types.Material mat) { // ストリップパスとか相対パスの場合を考慮する string filePath = System.IO.Path.GetDirectoryName(mat.map_Kd); if (filePath.Length == 0) { filePath = System.IO.Path.GetDirectoryName(fileName) + "\\" + mat.map_Kd; } string name = System.IO.Path.GetFileNameWithoutExtension(filePath); string ext = System.IO.Path.GetExtension(filePath); SyncTexture texture = new SyncTexture(new SyncId("TextureId_" + name), name); Console.WriteLine("\tTexture file: " + filePath); try { //System.Drawing.Image img = System.Drawing.Image.FromFile(filePath); #if false // 最初の案→なんかおかしい byte[] ary; using (MemoryStream ms = new MemoryStream()) { if (ext.ToLower() == ".jpg" || ext.ToLower() == ".jpeg") { img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); } else if (ext.ToLower() == ".png") { img.Save(ms, System.Drawing.Imaging.ImageFormat.Png); } else { Console.WriteLine("\t" + mat.map_Kd + " is unknown format"); return(null); } ary = ms.ToArray(); } texture.Source = ary.ToArray(); #else // 更に改善:解像度を2のN乗にする bool requireResize = false; Bitmap bmp = new Bitmap(filePath); int width = bmp.Width; int height = bmp.Height; if (!IsPow2(width)) { requireResize = true; int beki = 1; while (true) { if (width < beki) { width = beki / 2; // 1段階小さくする break; } beki *= 2; } } if (!IsPow2(bmp.Height)) { requireResize = true; int beki = 1; while (true) { if (height < beki) { height = beki / 2; // 1段階小さくする break; } beki *= 2; } } Bitmap bmpResize = new Bitmap(bmp, width, height); // ファイル名変更 string resizeFileName = filePath; if (requireResize) { resizeFileName.ToLower(); resizeFileName = resizeFileName.Replace(".jpg", "_resize.jpg"); // ファイル名差し替え bmpResize.Save(resizeFileName); // リサイズして画像出力 } bmpResize.Dispose(); bmp.Dispose(); // 2021.5.26の案 // UnityEditorで上手くいくのを確認した方法 // System.IO.FileStream fileStream = new System.IO.FileStream(resizeFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.BinaryReader bin = new System.IO.BinaryReader(fileStream); byte[] ary = bin.ReadBytes((int)bin.BaseStream.Length); bin.Close(); texture.Source = ary; /* * // こっちだとどうかな // [?]という画像に置き換わる現象が出た * List<byte> ary2 = new List<byte>(); * * Bitmap bmp = new Bitmap(filePath); * for (int x = 0; x < bmp.Width; x++) * { * for (int y = 0; y < bmp.Height; y++) * { * Color color = bmp.GetPixel(x, y); * ary2.Add(color.R); * ary2.Add(color.G); * ary2.Add(color.B); * ary2.Add(color.A); * } * } * texture.Source = ary2.ToArray(); */ #endif } catch (System.IO.FileNotFoundException e) { Console.WriteLine("FileNotFoundException: " + e.Message); } return(texture); }
public void Read(System.IO.BinaryReader br) { ByteOrder = br.ReadUInt16(); Version = br.ReadUInt16(); SystemIdentifier = br.ReadUInt32(); CLSID = new Guid(br.ReadBytes(16)); NumPropertySets = br.ReadUInt32(); FMTID0 = new Guid(br.ReadBytes(16)); Offset0 = br.ReadUInt32(); if (NumPropertySets == 2) { FMTID1 = new Guid(br.ReadBytes(16)); Offset1 = br.ReadUInt32(); } PropertySet0 = new PropertySet(); PropertySet0.Size = br.ReadUInt32(); PropertySet0.NumProperties = br.ReadUInt32(); // Read property offsets (P0) for (int i = 0; i < PropertySet0.NumProperties; i++) { PropertyIdentifierAndOffset pio = new PropertyIdentifierAndOffset(); pio.PropertyIdentifier = br.ReadUInt32(); pio.Offset = br.ReadUInt32(); PropertySet0.PropertyIdentifierAndOffsets.Add(pio); } PropertySet0.LoadContext((int)Offset0, br); //Read CodePage, Locale // Read properties (P0) for (int i = 0; i < PropertySet0.NumProperties; i++) { br.BaseStream.Seek(Offset0 + PropertySet0.PropertyIdentifierAndOffsets[i].Offset, System.IO.SeekOrigin.Begin); PropertySet0.Properties.Add(ReadProperty(PropertySet0.PropertyIdentifierAndOffsets[i].PropertyIdentifier, PropertySet0.PropertyContext.CodePage, br)); } if (NumPropertySets == 2) { br.BaseStream.Seek(Offset1, System.IO.SeekOrigin.Begin); PropertySet1 = new PropertySet(); PropertySet1.Size = br.ReadUInt32(); PropertySet1.NumProperties = br.ReadUInt32(); // Read property offsets for (int i = 0; i < PropertySet1.NumProperties; i++) { PropertyIdentifierAndOffset pio = new PropertyIdentifierAndOffset(); pio.PropertyIdentifier = br.ReadUInt32(); pio.Offset = br.ReadUInt32(); PropertySet1.PropertyIdentifierAndOffsets.Add(pio); } PropertySet1.LoadContext((int)Offset1, br); // Read properties for (int i = 0; i < PropertySet1.NumProperties; i++) { br.BaseStream.Seek(Offset1 + PropertySet1.PropertyIdentifierAndOffsets[i].Offset, System.IO.SeekOrigin.Begin); PropertySet1.Properties.Add(ReadProperty(PropertySet1.PropertyIdentifierAndOffsets[i].PropertyIdentifier, PropertySet1.PropertyContext.CodePage, br)); } } }
internal override void Read(System.IO.BinaryReader reader, BinaryReadInfo readInfo) { uint length = reader.ReadUInt32(); ID = reader.ReadUInt32(); uint numSections = reader.ReadUInt32(); string componentName = null; bool canResize = false; bool canFlip = false; double minSize = ComponentHelper.GridSize; List <ComponentProperty> properties = new List <ComponentProperty>(); List <ConnectionGroup> connections = new List <ConnectionGroup>(); List <RenderDescription> renderDescriptions = new List <RenderDescription>(); List <Conditional <FlagOptions> > flagOptions = new List <Conditional <FlagOptions> >(); ComponentDescriptionMetadata descriptionMetadata = new ComponentDescriptionMetadata(); uint?iconResourceId = null; for (uint sectionCounter = 0; sectionCounter < numSections; sectionCounter++) { ushort sectionType = reader.ReadUInt16(); uint sectionLength = reader.ReadUInt32(); #region Metadata if (sectionType == (uint)BinaryConstants.ComponentSectionType.Metadata) { componentName = reader.ReadString(); canResize = reader.ReadBoolean(); canFlip = reader.ReadBoolean(); minSize = reader.ReadDouble(); descriptionMetadata.Type = String.Format("Binary r{0} (*.cdcom)", readInfo.FormatVersion); descriptionMetadata.GUID = new Guid(reader.ReadBytes(16)); descriptionMetadata.Author = reader.ReadString(); if (readInfo.IsSignatureValid && readInfo.Certificate != null && readInfo.IsCertificateTrusted) { descriptionMetadata.Author = readInfo.Certificate.GetNameInfo(X509NameType.EmailName, false); } descriptionMetadata.Version = new Version(reader.ReadUInt16(), reader.ReadUInt16()); descriptionMetadata.AdditionalInformation = reader.ReadString(); descriptionMetadata.ImplementSet = reader.ReadString(); descriptionMetadata.ImplementItem = reader.ReadString(); descriptionMetadata.Signature.IsHashValid = readInfo.IsSignatureValid; descriptionMetadata.Signature.Certificate = readInfo.Certificate; descriptionMetadata.Signature.IsCertificateTrusted = readInfo.IsCertificateTrusted; int iconResource = reader.ReadInt32(); if (iconResource != -1) { iconResourceId = (uint)iconResource; } long created = reader.ReadInt64(); } #endregion #region Flags else if (sectionType == (uint)BinaryConstants.ComponentSectionType.Flags) { uint numFlagGroups = reader.ReadUInt32(); for (uint j = 0; j < numFlagGroups; j++) { IConditionTreeItem conditions; if (readInfo.FormatVersion > 1) { conditions = reader.ReadConditionTree(); } else { conditions = reader.ReadConditionCollection(); } FlagOptions value = (FlagOptions)reader.ReadUInt32(); flagOptions.Add(new Conditional <FlagOptions>(value, conditions)); } } #endregion #region Properties else if (sectionType == (uint)BinaryConstants.ComponentSectionType.Properties) { uint numProperties = reader.ReadUInt32(); for (uint j = 0; j < numProperties; j++) { string propertyName = reader.ReadString(); string serializedName = reader.ReadString(); string displayName = reader.ReadString(); BinaryType propType; object rawDefaultValue = reader.ReadType(out propType); PropertyUnion defaultValue = propType.ToPropertyUnion(rawDefaultValue); string[] enumOptions = null; if (propType == BinaryType.Enum) { enumOptions = new string[reader.ReadInt32()]; for (int k = 0; k < enumOptions.Length; k++) { enumOptions[k] = reader.ReadString(); } } // Format rules List <ComponentPropertyFormat> formatRules = new List <ComponentPropertyFormat>(); uint numFormatRules = reader.ReadUInt32(); for (uint k = 0; k < numFormatRules; k++) { IConditionTreeItem conditions; if (readInfo.FormatVersion > 1) { conditions = reader.ReadConditionTree(); } else { conditions = reader.ReadConditionCollection(); } string formatRule = reader.ReadString(); formatRules.Add(new ComponentPropertyFormat(formatRule, conditions)); } // Other conditions uint numOtherConditions = reader.ReadUInt32(); Dictionary <PropertyOtherConditionType, IConditionTreeItem> otherConditions = new Dictionary <PropertyOtherConditionType, IConditionTreeItem>((int)numOtherConditions); for (uint k = 0; k < numOtherConditions; k++) { uint uintConditionType = reader.ReadUInt32(); IConditionTreeItem conditions; if (readInfo.FormatVersion > 1) { conditions = reader.ReadConditionTree(); } else { conditions = reader.ReadConditionCollection(); } PropertyOtherConditionType conditionType = (PropertyOtherConditionType)uintConditionType; otherConditions.Add(conditionType, conditions); } properties.Add(new ComponentProperty(propertyName, serializedName, displayName, BinaryIOExtentions.BinaryTypeToPropertyType(propType), defaultValue, formatRules.ToArray(), otherConditions, enumOptions)); } } #endregion #region Configurations else if (sectionType == (uint)BinaryConstants.ComponentSectionType.Configurations) { uint numConfigurations = reader.ReadUInt32(); for (int j = 0; j < numConfigurations; j++) { string configurationName = reader.ReadString(); string implementationName = reader.ReadString(); int numSetters = reader.ReadInt32(); var setters = new Dictionary <string, PropertyUnion>(numSetters); for (int k = 0; k < numSetters; k++) { BinaryType tempType; string name = reader.ReadString(); var setterValue = reader.ReadType(out tempType); setters.Add(name, tempType.ToPropertyUnion(setterValue)); } int iconID = reader.ReadInt32(); var configuration = new ComponentConfiguration(implementationName, configurationName, setters); descriptionMetadata.Configurations.Add(configuration); if (iconID != -1) { iconResources.Add(configuration, (uint)iconID); } } } #endregion #region Connections else if (sectionType == (uint)BinaryConstants.ComponentSectionType.Connections) { uint numConnectionGroups = reader.ReadUInt32(); List <ConnectionGroup> connectionGroups = new List <ConnectionGroup>(); for (int j = 0; j < numConnectionGroups; j++) { IConditionTreeItem conditions; if (readInfo.FormatVersion > 1) { conditions = reader.ReadConditionTree(); } else { conditions = reader.ReadConditionCollection(); } List <ConnectionDescription> tConnections = new List <ConnectionDescription>(); uint numConnections = reader.ReadUInt32(); for (uint k = 0; k < numConnections; k++) { tConnections.Add(new ConnectionDescription(reader.ReadComponentPoint(), reader.ReadComponentPoint(), (ConnectionEdge)reader.ReadInt32(), reader.ReadString())); } connections.Add(new ConnectionGroup(conditions, tConnections.ToArray())); } } #endregion #region Render else if (sectionType == (uint)BinaryConstants.ComponentSectionType.Render) { uint numRenderGroups = reader.ReadUInt32(); for (uint j = 0; j < numRenderGroups; j++) { IConditionTreeItem conditions; if (readInfo.FormatVersion > 1) { conditions = reader.ReadConditionTree(); } else { conditions = reader.ReadConditionCollection(); } int numRenderCommands = (int)reader.ReadUInt32(); List <IRenderCommand> renderCommands = new List <IRenderCommand>(numRenderCommands); for (int k = 0; k < numRenderCommands; k++) { RenderCommandType commandType = (RenderCommandType)reader.ReadUInt32(); switch (commandType) { case RenderCommandType.Line: { ComponentPoint start = reader.ReadComponentPoint(); ComponentPoint end = reader.ReadComponentPoint(); double thickness = reader.ReadDouble(); renderCommands.Add(new Line(start, end, thickness)); } continue; case RenderCommandType.Rect: { ComponentPoint location = reader.ReadComponentPoint(); double width = reader.ReadDouble(); double height = reader.ReadDouble(); double thickness = reader.ReadDouble(); bool fill = (reader.ReadUInt32() == 0 ? false : true); renderCommands.Add(new Rectangle(location, width, height, thickness, fill)); } continue; case RenderCommandType.Ellipse: { ComponentPoint centre = reader.ReadComponentPoint(); double radiusX = reader.ReadDouble(); double radiusY = reader.ReadDouble(); double thickness = reader.ReadDouble(); bool fill = (reader.ReadUInt32() == 0 ? false : true); renderCommands.Add(new Ellipse(centre, radiusX, radiusY, thickness, fill)); } continue; case RenderCommandType.Path: { ComponentPoint start = reader.ReadComponentPoint(); double thickness = reader.ReadDouble(); bool fill = (reader.ReadUInt32() == 0 ? false : true); int numCommands = reader.ReadInt32(); List <IPathCommand> pathCommands = new List <IPathCommand>(numCommands); for (int l = 0; l < numCommands; l++) { CommandType pType = (CommandType)reader.ReadInt32(); IPathCommand theCommand = null; switch (pType) { case CommandType.MoveTo: theCommand = new MoveTo(); break; case CommandType.LineTo: theCommand = new LineTo(); break; case CommandType.CurveTo: theCommand = new CurveTo(); break; case CommandType.EllipticalArcTo: theCommand = new EllipticalArcTo(); break; case CommandType.QuadraticBeizerCurveTo: theCommand = new QuadraticBeizerCurveTo(); break; case CommandType.SmoothCurveTo: theCommand = new SmoothCurveTo(); break; case CommandType.SmoothQuadraticBeizerCurveTo: theCommand = new SmoothQuadraticBeizerCurveTo(); break; default: theCommand = new ClosePath(); break; } theCommand.Read(reader); pathCommands.Add(theCommand); } renderCommands.Add(new RenderPath(start, thickness, fill, pathCommands)); } continue; case RenderCommandType.Text: { byte formattedTextVersion = reader.ReadByte(); ComponentPoint location = reader.ReadComponentPoint(); TextAlignment alignment = (TextAlignment)reader.ReadUInt32(); uint numTextRuns = reader.ReadUInt32(); List <TextRun> textRuns = new List <TextRun>((int)numTextRuns); for (uint l = 0; l < numTextRuns; l++) { TextRunFormattingType formattingType = (TextRunFormattingType)reader.ReadUInt32(); double runSize = reader.ReadDouble(); string runText = reader.ReadString(); textRuns.Add(new TextRun(runText, new TextRunFormatting(formattingType, runSize))); } renderCommands.Add(new Text(location, alignment, textRuns)); } continue; } } renderDescriptions.Add(new RenderDescription(conditions, renderCommands.ToArray())); } } #endregion #region Skip else { // Unknown type - skip reader.BaseStream.Seek(sectionLength, SeekOrigin.Current); } #endregion } ComponentDescription = new ComponentDescription(ID.ToString(), componentName, canResize, canFlip, minSize, properties.ToArray(), connections.ToArray(), renderDescriptions.ToArray(), flagOptions.ToArray(), descriptionMetadata); if (iconResourceId.HasValue) { mainIconResource = iconResourceId.Value; } }
/// <summary> /// Get the SkipperRule associated with a given stream /// </summary> /// <param name="input">Name of the file to be checked</param> /// <param name="skipperName">Name of the skipper to be used, blank to find a matching skipper</param> /// <param name="logger">Logger object for file and console output</param> /// <param name="keepOpen">True if the underlying stream should be kept open, false otherwise</param> /// <returns>The SkipperRule that matched the file</returns> public static SkipperRule GetMatchingRule(Stream input, string skipperName, bool keepOpen = false) { SkipperRule skipperRule = new SkipperRule(); // If we have a null skipper name, we return since we're not matching skippers if (skipperName == null) { return(skipperRule); } // Loop through and find a Skipper that has the right name Globals.Logger.Verbose("Beginning search for matching header skip rules"); List <Skipper> tempList = new List <Skipper>(); tempList.AddRange(List); foreach (Skipper skipper in tempList) { // If we're searching for the skipper OR we have a match to an inputted one if (String.IsNullOrWhiteSpace(skipperName) || (!String.IsNullOrWhiteSpace(skipper.Name) && skipperName.ToLowerInvariant() == skipper.Name.ToLowerInvariant()) || (!String.IsNullOrWhiteSpace(skipper.Name) && skipperName.ToLowerInvariant() == skipper.SourceFile.ToLowerInvariant())) { // Loop through the rules until one is found that works BinaryReader br = new BinaryReader(input); foreach (SkipperRule rule in skipper.Rules) { // Always reset the stream back to the original place input.Seek(0, SeekOrigin.Begin); // For each rule, make sure it passes each test bool success = true; foreach (SkipperTest test in rule.Tests) { bool result = true; switch (test.Type) { case HeaderSkipTest.Data: // First seek to the correct position if (test.Offset == null) { input.Seek(0, SeekOrigin.End); } else if (test.Offset > 0 && test.Offset <= input.Length) { input.Seek((long)test.Offset, SeekOrigin.Begin); } else if (test.Offset < 0 && Math.Abs((long)test.Offset) <= input.Length) { input.Seek((long)test.Offset, SeekOrigin.End); } // Then read and compare bytewise result = true; for (int i = 0; i < test.Value.Length; i++) { try { if (br.ReadByte() != test.Value[i]) { result = false; break; } } catch { result = false; break; } } // Return if the expected and actual results match success &= (result == test.Result); break; case HeaderSkipTest.Or: case HeaderSkipTest.Xor: case HeaderSkipTest.And: // First seek to the correct position if (test.Offset == null) { input.Seek(0, SeekOrigin.End); } else if (test.Offset > 0 && test.Offset <= input.Length) { input.Seek((long)test.Offset, SeekOrigin.Begin); } else if (test.Offset < 0 && Math.Abs((long)test.Offset) <= input.Length) { input.Seek((long)test.Offset, SeekOrigin.End); } result = true; try { // Then apply the mask if it exists byte[] read = br.ReadBytes(test.Mask.Length); byte[] masked = new byte[test.Mask.Length]; for (int i = 0; i < read.Length; i++) { masked[i] = (byte)(test.Type == HeaderSkipTest.And ? read[i] & test.Mask[i] : (test.Type == HeaderSkipTest.Or ? read[i] | test.Mask[i] : read[i] ^ test.Mask[i]) ); } // Finally, compare it against the value for (int i = 0; i < test.Value.Length; i++) { if (masked[i] != test.Value[i]) { result = false; break; } } } catch { result = false; } // Return if the expected and actual results match success &= (result == test.Result); break; case HeaderSkipTest.File: // First get the file size from stream long size = input.Length; // If we have a null size, check that the size is a power of 2 result = true; if (test.Size == null) { // http://stackoverflow.com/questions/600293/how-to-check-if-a-number-is-a-power-of-2 result = (((ulong)size & ((ulong)size - 1)) == 0); } else if (test.Operator == HeaderSkipTestFileOperator.Less) { result = (size < test.Size); } else if (test.Operator == HeaderSkipTestFileOperator.Greater) { result = (size > test.Size); } else if (test.Operator == HeaderSkipTestFileOperator.Equal) { result = (size == test.Size); } // Return if the expected and actual results match success &= (result == test.Result); break; } } // If we still have a success, then return this rule if (success) { // If we're not keeping the stream open, dispose of the binary reader if (!keepOpen) { input.Dispose(); } Globals.Logger.User(" Matching rule found!"); return(rule); } } } } // If we're not keeping the stream open, dispose of the binary reader if (!keepOpen) { input.Dispose(); } // If we have a blank rule, inform the user if (skipperRule.Tests == null) { Globals.Logger.Verbose("No matching rule found!"); } return(skipperRule); }
protected override void Load(System.IO.BinaryReader reader) { m_data = reader.ReadBytes(88); }
public ActionResult EditPost(int?id, HttpPostedFileBase upload) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } var studentToUpdate = db.Students.Find(id); if (TryUpdateModel(studentToUpdate, "", new string[] { "LastName", "FirstMidName", "EnrollmentDate" })) { try { if (upload != null && upload.ContentLength > 0) { //string typeFile = Path.GetExtension(upload.FileName); CheckImage check = new CheckImage(); //getting the image string fileName = System.IO.Path.GetExtension(upload.FileName); //call of the verification Extension method bool extensionIsTrue = check.checkExtension(fileName); if (extensionIsTrue == false) { ViewBag.ErrorType = ErrorMessages.ErrorExtension(); Student student = db.Students.Include(s => s.Files).SingleOrDefault(s => s.ID == id); return(View(student)); } //call of the verfication Size method bool sizeIsCorrect = check.checkSize(upload.ContentLength); if (sizeIsCorrect == false) { ViewBag.ErrorSize = ErrorMessages.ErrorSize(); Student student = db.Students.Include(s => s.Files).SingleOrDefault(s => s.ID == id); return(View(student)); } //Remove the the previous image if (studentToUpdate.Files.Any(f => f.FileType == FileType.Avatar)) { db.Files.Remove(studentToUpdate.Files.First(f => f.FileType == FileType.Avatar)); } var avatar = new FileImage { FileName = System.IO.Path.GetFileName(upload.FileName), FileType = FileType.Avatar, ContentType = upload.ContentType }; using (var reader = new System.IO.BinaryReader(upload.InputStream)) { avatar.Content = reader.ReadBytes(upload.ContentLength); } studentToUpdate.Files = new List <FileImage> { avatar }; } db.Entry(studentToUpdate).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } catch (RetryLimitExceededException /* dex */) { //Log the error (uncomment dex variable name and add a line here to write a log. ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator."); } } return(View(studentToUpdate)); }
protected override void Load(System.IO.BinaryReader reader) { m_data = reader.ReadBytes(560); UpdateParticipants(); }
//public string suva_EventDatetimeDate; //public string suva_EventDatetimeHour; //public string suva_EventDatetimeMin; //public string suva_EventDatetimeWeekday; //public bool suva_CompanyMode1; //public bool suva_CompanyMode2; //public bool suva_CompanyMode3; //public string suva_CompanyName; //public string suva_CompanyAddress; //public string suva_CompanyZIP; //public string suva_CompanyCity; //public string suva_CompanySector; //public string suva_EmployerAccountNo; //public string suva_NumberOfEmployees; //public string suva_ContractorName; //public string suva_ContractorAddress; //public string suva_ContractorZIP; //public string suva_ContractorCity; //public string suva_ContractorAccountNo; //public string suva_ContractorContact; //public string suva_ContractorContactTel; //public string suva_VictimLastname; //public string suva_VictimFirstname; //public string suva_VictimAddress; //public string suva_VictimZIP; //public string suva_VictimCity; //public string suva_VictimInsuranceComp; //public string suva_VictimInsuranceNo; //public string suva_VictimBirthdateDay; //public string suva_VictimBirthdateMonth; //public string suva_VictimBirthdateYear; //public bool suva_VictimGender1; //public bool suva_VictimGender2; //public string suva_VictimNationality; //public string suva_VictimHiredate; //public string suva_VictimEmployedAs; //public string suva_VictimPersnr; //public string suva_VictimCostCenter; //public bool suva_EmploymentStatus1; //public bool suva_EmploymentStatus2; //public bool suva_EmploymentStatus3; //public bool suva_EmploymentStatus4; //public bool suva_EmploymentExtent1; //public bool suva_EmploymentExtent2; //public bool suva_EmploymentLimit0; //public bool suva_EmploymentLimit1; //public string suva_WorktimeStartHour; //public string suva_WorktimeStartMin; //public string suva_WorktimeEndHour; //public string suva_WorktimeEndMin; //public string suva_OvertimeStartHour; //public string suva_OvertimeStartMin; //public string suva_OvertimeEndHour; //public string suva_OvertimeEndMin; //public bool suva_AccidentLocation1; //public bool suva_AccidentLocation2; //public string suva_AccidentWorkplace; //public string suva_AccidentWorkplaceDet; //public string suva_TypeOfWork; //public string suva_CourseOfEvents; //public bool suva_ReportedBy1; //public bool suva_ReportedBy2; //public bool suva_ReportedBy4; //public bool suva_ReportedBy8; //public string suva_Bodypart; //public string suva_NatureOfInjury; //public bool suva_Attenders1; //public bool suva_Attenders2; //public bool suva_Attenders3; //public string suva_AttenderDetails; //public bool suva_TravelaccidentType1; //public bool suva_TravelaccidentType2; //public bool suva_TravelaccidentType3; //public bool suva_TravelaccidentType4; //public string suva_TravelaccidentPurpos; //public string suva_TravelaccidentOffset; //public string suva_TravelaccidentDest; //public bool suva_Ambulance1; //public bool suva_Ambulance2; //public bool suva_Ambulance3; //public string suva_AmbulanceOrganisat; //public bool suva_InvestigatorPolice; //public string suva_InvestigatorPoliceSt; //public bool suva_InvestAuthority; //public string suva_InvestAuthorityOff; //public bool suva_Workstopped1; //public bool suva_Workstopped2; //public bool suva_Workstopped3; //public string suva_WorkstoppedDate; //public string suva_WorkstoppedHour; //public string suva_WorkstoppedMin; //public bool suva_FatalityRelatives0; //public bool suva_FatalityRelatives1; //public bool suva_FatalityRelations1; //public bool suva_FatalityRelations2; //public bool suva_SickLeave0; //public bool suva_SickLeave1; //public bool suva_SickLeave2; //public string suva_SickLeaveEnded; //public bool suva_Hospital0; //public bool suva_Hospital1; //public bool suva_HospitalStay1; //public bool suva_HospitalStay2; //public string suva_HospitalEntry; //public string suva_HospitalName; //public string suva_Hospitaladdress; //public bool suva_DoctorTreatment0; //public bool suva_DoctorTreatment1; //public string suva_DoctorDate; //public string suva_DoctorName; //public string suva_DoctorAddress; //public bool suva_ObligationToTrain0; //public bool suva_ObligationToTrain1; //public string suva_TrainingText; //public string suva_ReporterNameFunction; //public string suva_BossNameFunction; //public string suva_ContactTel; //public string suva_ContactFax; //public string suva_ContactEMail; //public string suva_IssuedAt; //public string suva_Issued; /// <summary> /// Makes a doc file representing the filled-in SUVA form /// </summary> public bool Render(string rpt_temp_path, ref MemoryStream docstream) { #if LINUX return(false); #else DateTime nowtime = DateTime.UtcNow; const string temp_file_naming = "sherm-suva-temp-doc-template-{0}.doc"; const string dest_file_naming = "sherm-suva-temp-doc-complete-{0}.doc"; const string result_file_naming = "sherm-suva-temp-doc-result-{0}.{1}"; string temp_file_name = String.Format(temp_file_naming, nowtime.ToString("yyyyMMddHHmmss")); string dest_file_name = String.Format(dest_file_naming, nowtime.ToString("yyyyMMddHHmmss")); string result_file_name = String.Format(result_file_naming, nowtime.ToString("yyyyMMddHHmmss"), this.GetResultFileExtension()); object missing = System.Reflection.Missing.Value; object o_false = false; object o_true = true; string templateResourcePath = GetTemplateResourcePath(); try { if (docstream == null) { docstream = new MemoryStream(); } string tempPath = rpt_temp_path; /* [dlatikay 20121121] we do not bother the system, we have our own: was: Path.GetTempPath(); */ string temp_file_path = Path.Combine(tempPath, temp_file_name); string dest_file_path = Path.Combine(tempPath, dest_file_name); object result_file_path = Path.Combine(tempPath, result_file_name); /* 1. open the template */ using (var t_doc = new System.IO.BinaryReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(templateResourcePath))) { /* 1a. we must persist it in the temporary files folder */ using (var os = new FileStream(temp_file_path, FileMode.Create, FileAccess.Write)) { using (BinaryWriter t_doc_wr = new BinaryWriter(os)) { byte[] tempdoccontent = t_doc.ReadBytes((int)t_doc.BaseStream.Length); t_doc_wr.Write(tempdoccontent); } } } /* remove the read-only attribute */ FileAttributes attr = File.GetAttributes(temp_file_path); attr &= ~FileAttributes.ReadOnly; /* lovely */ File.SetAttributes(temp_file_path, attr); /* 1b. get us an instance of MS Word and open the template */ Word.Application word = null; try { object o_temp_file_path = temp_file_path; object o_dest_file_path = dest_file_path; word = new Word.Application(); Word.Document doc = word.Documents.Open(ref o_temp_file_path, ref o_false, ref o_true, ref o_false, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref o_false, ref o_false, ref missing, ref o_true, ref missing); doc.SaveAs(ref o_dest_file_path, ref missing, ref missing, ref missing, ref o_false, ref missing, ref o_false, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); /* set the standard (builtin) document properties */ object oBuiltInProps = doc.BuiltInDocumentProperties; Type tBuiltInProps = oBuiltInProps.GetType(); tBuiltInProps.InvokeMember("Item", BindingFlags.Default | BindingFlags.SetProperty, null, oBuiltInProps, new object[] { "Title", documenttitle }); tBuiltInProps.InvokeMember("Item", BindingFlags.Default | BindingFlags.SetProperty, null, oBuiltInProps, new object[] { "Subject", documentsubject }); tBuiltInProps.InvokeMember("Item", BindingFlags.Default | BindingFlags.SetProperty, null, oBuiltInProps, new object[] { "Author", documentauthor }); tBuiltInProps.InvokeMember("Item", BindingFlags.Default | BindingFlags.SetProperty, null, oBuiltInProps, new object[] { "Manager", documentmanager }); tBuiltInProps.InvokeMember("Item", BindingFlags.Default | BindingFlags.SetProperty, null, oBuiltInProps, new object[] { "Company", documentcompany }); tBuiltInProps.InvokeMember("Item", BindingFlags.Default | BindingFlags.SetProperty, null, oBuiltInProps, new object[] { "Category", documentcategory }); tBuiltInProps.InvokeMember("Item", BindingFlags.Default | BindingFlags.SetProperty, null, oBuiltInProps, new object[] { "Keywords", documentkeywords }); tBuiltInProps.InvokeMember("Item", BindingFlags.Default | BindingFlags.SetProperty, null, oBuiltInProps, new object[] { "Comments", documentcomments }); /* set the extended (custom) document properties */ /* now its time to set all the bookmarks */ //doc.Unprotect(ref missing); SetFormfieldText(doc, "VictimBirthDate", suva_VictimBirthdate); SetFormfieldText(doc, "VictimEmployedAs", suva_VictimEmployedAs); SetFormfieldText(doc, "Bodypart", suva_Bodypart); SetFormfieldText(doc, "Bodyside", suva_Bodyside); SetFormfieldCheck(doc, "WorkStoppedYes", suva_WorkStopped); SetFormfieldCheck(doc, "WorkStoppedNo", !suva_WorkStopped); SetFormfieldText(doc, "WorkStoppedDate", suva_WorkStoppedDatetime); SetFormfieldText(doc, "LastWorkDay", suva_LastWorkday); SetFormfieldText(doc, "ResumedWork", suva_ResumedWork); SetFormfieldText(doc, "HospitalName", suva_HospitalName); SetFormfieldText(doc, "HospitalName2", suva_HospitalName2); SetFormfieldText(doc, "HospitalAddress", suva_HosptialAddress); SetFormfieldText(doc, "HospitalAddress2", suva_HosptialAddress2); //SetFormfieldText(doc, "EventDatetimeDate", suva_EventDatetimeDate); //SetFormfieldText(doc, "EventDatetimeHour", suva_EventDatetimeHour); //SetFormfieldText(doc, "EventDatetimeMin", suva_EventDatetimeMin); //SetFormfieldText(doc, "EventDatetimeWeekday", suva_EventDatetimeWeekday); //SetFormfieldCheck(doc, "CompanyMode1", suva_CompanyMode1); //SetFormfieldCheck(doc, "CompanyMode2", suva_CompanyMode2); //SetFormfieldCheck(doc, "CompanyMode3", suva_CompanyMode3); //SetFormfieldText(doc, "CompanyName", suva_CompanyName); //SetFormfieldText(doc, "CompanyAddress", suva_CompanyAddress); //SetFormfieldText(doc, "CompanyZIP", suva_CompanyZIP); //SetFormfieldText(doc, "CompanyCity", suva_CompanyCity); //SetFormfieldText(doc, "CompanySector", suva_CompanySector); //SetFormfieldText(doc, "EmployerAccountNo", suva_EmployerAccountNo); //SetFormfieldText(doc, "NumberOfEmployees", suva_NumberOfEmployees); //SetFormfieldText(doc, "ContractorName", suva_ContractorName); //SetFormfieldText(doc, "ContractorAddress", suva_ContractorAddress); //SetFormfieldText(doc, "ContractorZIP", suva_ContractorZIP); //SetFormfieldText(doc, "ContractorCity", suva_ContractorCity); //SetFormfieldText(doc, "ContractorAccountNo", suva_ContractorAccountNo); //SetFormfieldText(doc, "ContractorContact", suva_ContractorContact); //SetFormfieldText(doc, "ContractorContactTel", suva_ContractorContactTel); //SetFormfieldText(doc, "VictimLastname", suva_VictimLastname); //SetFormfieldText(doc, "VictimFirstname", suva_VictimFirstname); //SetFormfieldText(doc, "VictimAddress", suva_VictimAddress); //SetFormfieldText(doc, "VictimZIP", suva_VictimZIP); //SetFormfieldText(doc, "VictimCity", suva_VictimCity); //SetFormfieldText(doc, "VictimInsuranceComp", suva_VictimInsuranceComp); //SetFormfieldText(doc, "VictimInsuranceNo", suva_VictimInsuranceNo); //SetFormfieldText(doc, "VictimBirthdateDay", suva_VictimBirthdateDay); //SetFormfieldText(doc, "VictimBirthdateMonth", suva_VictimBirthdateMonth); //SetFormfieldText(doc, "VictimBirthdateYear", suva_VictimBirthdateYear); //SetFormfieldCheck(doc, "VictimGender1", suva_VictimGender1); //SetFormfieldCheck(doc, "VictimGender2", suva_VictimGender2); //SetFormfieldText(doc, "VictimNationality", suva_VictimNationality); //SetFormfieldText(doc, "VictimHiredate", suva_VictimHiredate); //SetFormfieldText(doc, "VictimEmployedAs", suva_VictimEmployedAs); //SetFormfieldCheck(doc, "EmploymentStatus1", suva_EmploymentStatus1); //SetFormfieldCheck(doc, "EmploymentStatus2", suva_EmploymentStatus2); //SetFormfieldCheck(doc, "EmploymentStatus3", suva_EmploymentStatus3); //SetFormfieldCheck(doc, "EmploymentStatus4", suva_EmploymentStatus4); //SetFormfieldCheck(doc, "EmploymentExtent1", suva_EmploymentExtent1); //SetFormfieldCheck(doc, "EmploymentExtent2", suva_EmploymentExtent2); //SetFormfieldCheck(doc, "EmploymentLimit0", suva_EmploymentLimit0); //SetFormfieldCheck(doc, "EmploymentLimit1", suva_EmploymentLimit1); //SetFormfieldText(doc, "WorktimeStartHour", suva_WorktimeStartHour); //SetFormfieldText(doc, "WorktimeStartMin", suva_WorktimeStartMin); //SetFormfieldText(doc, "WorktimeEndHour", suva_WorktimeEndHour); //SetFormfieldText(doc, "WorktimeEndMin", suva_WorktimeEndMin); //SetFormfieldText(doc, "OvertimeStartHour", suva_OvertimeStartHour); //SetFormfieldText(doc, "OvertimeStartMin", suva_OvertimeStartMin); //SetFormfieldText(doc, "OvertimeEndHour", suva_OvertimeEndHour); //SetFormfieldText(doc, "OvertimeEndMin", suva_OvertimeEndMin); //SetFormfieldCheck(doc, "AccidentLocation1", suva_AccidentLocation1); //SetFormfieldCheck(doc, "AccidentLocation2", suva_AccidentLocation2); //SetFormfieldText(doc, "AccidentWorkplace", suva_AccidentWorkplace); //SetFormfieldText(doc, "AccidentWorkplaceDet", suva_AccidentWorkplaceDet); //SetFormfieldText(doc, "TypeOfWork", suva_TypeOfWork); //SetFormfieldText(doc, "CourseOfEvents", suva_CourseOfEvents); //SetFormfieldCheck(doc, "ReportedBy1", suva_ReportedBy1); //SetFormfieldCheck(doc, "ReportedBy2", suva_ReportedBy2); //SetFormfieldCheck(doc, "ReportedBy4", suva_ReportedBy4); //SetFormfieldCheck(doc, "ReportedBy8", suva_ReportedBy8); //SetFormfieldText(doc, "Bodypart", suva_Bodypart); //SetFormfieldText(doc, "NatureOfInjury", suva_NatureOfInjury); //SetFormfieldCheck(doc, "Attenders1", suva_Attenders1); //SetFormfieldCheck(doc, "Attenders2", suva_Attenders2); //SetFormfieldCheck(doc, "Attenders3", suva_Attenders3); //SetFormfieldText(doc, "AttenderDetails", suva_AttenderDetails); //SetFormfieldCheck(doc, "TravelaccidentType1", suva_TravelaccidentType1); //SetFormfieldCheck(doc, "TravelaccidentType2", suva_TravelaccidentType2); //SetFormfieldCheck(doc, "TravelaccidentType3", suva_TravelaccidentType3); //SetFormfieldCheck(doc, "TravelaccidentType4", suva_TravelaccidentType4); //SetFormfieldText(doc, "TravelaccidentPurpos", suva_TravelaccidentPurpos); //SetFormfieldText(doc, "TravelaccidentOffset", suva_TravelaccidentOffset); //SetFormfieldText(doc, "TravelaccidentDest", suva_TravelaccidentDest); //SetFormfieldCheck(doc, "Ambulance1", suva_Ambulance1); //SetFormfieldCheck(doc, "Ambulance2", suva_Ambulance2); //SetFormfieldCheck(doc, "Ambulance3", suva_Ambulance3); //SetFormfieldText(doc, "AmbulanceOrganisat", suva_AmbulanceOrganisat); //SetFormfieldCheck(doc, "InvestigatorPolice", suva_InvestigatorPolice); //SetFormfieldText(doc, "InvestigatorPoliceSt", suva_InvestigatorPoliceSt); //SetFormfieldCheck(doc, "InvestAuthority", suva_InvestAuthority); //SetFormfieldText(doc, "InvestAuthorityOff", suva_InvestAuthorityOff); //SetFormfieldCheck(doc, "Workstopped1", suva_Workstopped1); //SetFormfieldCheck(doc, "Workstopped2", suva_Workstopped2); //SetFormfieldCheck(doc, "Workstopped3", suva_Workstopped3); //SetFormfieldText(doc, "WorkstoppedDate", suva_WorkstoppedDate); //SetFormfieldText(doc, "WorkstoppedHour", suva_WorkstoppedHour); //SetFormfieldText(doc, "WorkstoppedMin", suva_WorkstoppedMin); //SetFormfieldCheck(doc, "FatalityRelatives0", suva_FatalityRelatives0); //SetFormfieldCheck(doc, "FatalityRelatives1", suva_FatalityRelatives1); //SetFormfieldCheck(doc, "FatalityRelations1", suva_FatalityRelations1); //SetFormfieldCheck(doc, "FatalityRelations2", suva_FatalityRelations2); //SetFormfieldCheck(doc, "SickLeave0", suva_SickLeave0); //SetFormfieldCheck(doc, "SickLeave1", suva_SickLeave1); //SetFormfieldCheck(doc, "SickLeave2", suva_SickLeave2); //SetFormfieldText(doc, "SickLeaveEnded", suva_SickLeaveEnded); //SetFormfieldCheck(doc, "Hospital0", suva_Hospital0); //SetFormfieldCheck(doc, "Hospital1", suva_Hospital1); //SetFormfieldCheck(doc, "HospitalStay1", suva_HospitalStay1); //SetFormfieldCheck(doc, "HospitalStay2", suva_HospitalStay2); //SetFormfieldText(doc, "HospitalEntry", suva_HospitalEntry); //SetFormfieldText(doc, "HospitalName", suva_HospitalName); //SetFormfieldText(doc, "Hospitaladdress", suva_Hospitaladdress); //SetFormfieldCheck(doc, "DoctorTreatment0", suva_DoctorTreatment0); //SetFormfieldCheck(doc, "DoctorTreatment1", suva_DoctorTreatment1); //SetFormfieldText(doc, "DoctorDate", suva_DoctorDate); //SetFormfieldText(doc, "DoctorName", suva_DoctorName); //SetFormfieldText(doc, "DoctorAddress", suva_DoctorAddress); //SetFormfieldCheck(doc, "ObligationToTrain0", suva_ObligationToTrain0); //SetFormfieldCheck(doc, "ObligationToTrain1", suva_ObligationToTrain1); //SetFormfieldText(doc, "TrainingText", suva_TrainingText); //SetFormfieldText(doc, "ReporterNameFunction", suva_ReporterNameFunction); //SetFormfieldText(doc, "BossNameFunction", suva_BossNameFunction); //SetFormfieldText(doc, "ContactTel", suva_ContactTel); //SetFormfieldText(doc, "ContactFax", suva_ContactFax); //SetFormfieldText(doc, "ContactEMail", suva_ContactEMail); //SetFormfieldText(doc, "IssuedAt", suva_IssuedAt); //SetFormfieldText(doc, "Issued", suva_Issued); /* set export type dependend bookmarks */ switch (this.SUVAExportType) { default: { break; } } doc.Protect(Microsoft.Office.Interop.Word.WdProtectionType.wdAllowOnlyFormFields, ref o_true, ref missing, ref o_false, ref o_false); /* persist it */ #pragma warning disable 0467 /* the pragma is for the event member */ doc.Save(); object fileFormat = missing; if (this.SUVAExportType != SUVAExportType.Default) { fileFormat = Word.WdSaveFormat.wdFormatPDF; } doc.SaveAs(ref result_file_path, ref fileFormat, ref missing, ref missing, ref o_false, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); doc.Close(ref o_false, ref missing, ref missing); #pragma warning restore 0467 } catch (Exception) { /* up the exception chain */ throw; } finally { /* cleanup word */ if (word != null) { try { #pragma warning disable 0467 /* the pragma is for the event member */ word.Quit(ref missing, ref missing, ref missing); #pragma warning restore 0467 } catch (Exception) { } try { System.Runtime.InteropServices.Marshal.FinalReleaseComObject(word); } catch (System.Exception) { } word = null; } } /* need to wait until the COM handles are really closed */ /* now we load the document into memory and deliver the stream. the file is deleted. */ using (FileStream ifs = new FileStream(result_file_path.ToString(), FileMode.Open, FileAccess.Read)) { using (BinaryReader rd = new BinaryReader(ifs)) { docstream.Write(rd.ReadBytes((int)rd.BaseStream.Length), 0, (int)rd.BaseStream.Length); rd.Close(); docstream.Seek(0, SeekOrigin.Begin); } } File.Delete(temp_file_path); File.Delete(dest_file_path); File.Delete(result_file_path.ToString()); /* succeeded */ return(true); } catch (Exception) { /* for debugging purposes */ throw; } #endif }
public override OricProgram LoadFile(string diskName, OricFileInfo oricFileInfo) { int index = 0; int totalDescriptors = 0; Byte dataTrack = 0; Byte dataSector = 0; Byte nextDescTrack = 0; Byte nextDescSector = 1; OricProgram loadedProgram = new OricProgram(); loadedProgram.New(); String diskPathname = Path.Combine(oricFileInfo.Folder, oricFileInfo.ParentName); if (base.LoadDisk(diskPathname)) { Byte[] fileDescriptor = GetFileDescriptor(oricFileInfo.ProgramName); loadedProgram.Format = GetFileFormat(fileDescriptor); loadedProgram.ProgramName = oricFileInfo.ProgramName; if (loadedProgram.ProgramName.ToUpper().EndsWith(".CHS")) { loadedProgram.Format = OricProgram.ProgramFormat.CharacterSet; } if (loadedProgram.ProgramName.ToUpper().EndsWith(".HRS")) { loadedProgram.Format = OricProgram.ProgramFormat.HiresScreen; } Byte formatFlag = fileDescriptor[0x03]; if ((formatFlag & 0x01) == 0x01) { loadedProgram.AutoRun = OricProgram.AutoRunFlag.Enabled; } else { loadedProgram.AutoRun = OricProgram.AutoRunFlag.Disabled; } UInt16 sectorsToLoad = (UInt16)(fileDescriptor[0x0A] + (fileDescriptor[0x0B] * 256)); // Get program header info switch (loadedProgram.Format) { case OricProgram.ProgramFormat.DirectAccessFile: loadedProgram.RecordCount = (UInt16)(fileDescriptor[0x04] + (fileDescriptor[0x05] * 256)); loadedProgram.RecordLength = (UInt16)(fileDescriptor[0x06] + (fileDescriptor[0x07] * 256)); loadedProgram.StartAddress = 0x0000; loadedProgram.EndAddress = (UInt16)(loadedProgram.RecordCount * loadedProgram.RecordLength); break; case OricProgram.ProgramFormat.SequentialFile: loadedProgram.RecordCount = 0; loadedProgram.RecordLength = 0; loadedProgram.StartAddress = 0x0000; loadedProgram.EndAddress = (UInt16)(sectorsToLoad * fileDescriptor.Length); break; default: loadedProgram.RecordCount = 0; loadedProgram.RecordLength = 0; loadedProgram.StartAddress = (UInt16)(fileDescriptor[0x04] + (fileDescriptor[0x05] * 256)); loadedProgram.EndAddress = (UInt16)(fileDescriptor[0x06] + (fileDescriptor[0x07] * 256)); break; } do { System.IO.MemoryStream stm = new System.IO.MemoryStream(fileDescriptor, 0, fileDescriptor.Length); System.IO.BinaryReader rdr = new System.IO.BinaryReader(stm); Byte[] byteArray = new Byte[32]; nextDescTrack = rdr.ReadByte(); nextDescSector = rdr.ReadByte(); Byte firstDescriptorFlag = rdr.ReadByte(); int descriptorIndex = 0; if (firstDescriptorFlag == 0xFF) { byteArray = rdr.ReadBytes(9); dataTrack = rdr.ReadByte(); dataSector = rdr.ReadByte(); totalDescriptors = 121; } else { dataTrack = firstDescriptorFlag; dataSector = rdr.ReadByte(); totalDescriptors = 126; } int programLength = (loadedProgram.EndAddress - loadedProgram.StartAddress) + 1; //loadedProgram.m_programData = new Byte[0xFFFF]; loadedProgram.m_programData = new Byte[programLength]; while (dataSector != 0 && descriptorIndex < totalDescriptors) { Byte[] programData = base.ReadSector(dataTrack, dataSector); System.IO.MemoryStream stm2 = new System.IO.MemoryStream(programData, 0, programData.Length); System.IO.BinaryReader rdr2 = new System.IO.BinaryReader(stm2); Byte tmpByte = 0; for (int loop = 0; loop < programData.Length; loop++) { tmpByte = rdr2.ReadByte(); if (index < programLength) { loadedProgram.m_programData[index] = tmpByte; } index++; } if (dataSector != 0) { dataTrack = rdr.ReadByte(); dataSector = rdr.ReadByte(); descriptorIndex++; } } if (nextDescSector != 0) { fileDescriptor.Initialize(); fileDescriptor = base.ReadSector(nextDescTrack, nextDescSector); } } while (nextDescSector != 0); } return(loadedProgram); }
public string ReadStr() { int c = IPAddress.NetworkToHostOrder(br.ReadInt32()); return((c > 0) ? encoding.GetString(br.ReadBytes(c)) : string.Empty); }
private OricFileInfo[] ReadSedOricDirectory() { OricFileInfo[] diskDirectory = null; //int noOfFiles = 0; System.Text.Encoding enc = System.Text.Encoding.ASCII; ArrayList diskCatalog = new ArrayList(); Byte bNextTrack = Convert.ToByte(20); Byte bNextSector = Convert.ToByte(4); Byte bCurrTrack = bNextTrack; Byte bCurrSector = bNextSector; Boolean MoreDirectories = true; while (MoreDirectories) { // Read the first directory sector Byte[] directory = base.ReadSector(bCurrTrack, bCurrSector); if (directory[0] == 0x00 && directory[1] == 0x00) { MoreDirectories = false; } else { bCurrTrack = directory[0]; bCurrSector = directory[1]; } // Scan thru all 15 entries to build the directory UInt16 DirectoryIndex = 0; System.IO.MemoryStream stm = new System.IO.MemoryStream(directory, 0, 256); System.IO.BinaryReader rdr = new System.IO.BinaryReader(stm); stm.Seek(0x10, SeekOrigin.Begin); do { if (rdr.PeekChar() != 0x00) { // Read the filename String Filename = enc.GetString(rdr.ReadBytes(9)).Trim(); // Read the file extension String FileExtension = enc.GetString(rdr.ReadBytes(3)).Trim(); // Read the file descriptor track Byte FileDescTrack = rdr.ReadByte(); // Read the file descriptor sector Byte FileDescSector = rdr.ReadByte(); // Read the no. of sectors used by file (includes file descriptor) Byte SectorsUsed = rdr.ReadByte(); // Read the files protection status Byte ProtectionStatus = rdr.ReadByte(); OricFileInfo diskFileInfo = new OricFileInfo(); diskFileInfo.MediaType = OricExplorer.MediaType.DiskFile; //diskFileInfo.m_bDosFormat = OricDisk.DOSFormat.SedOric; diskFileInfo.Folder = base.diskFolder; diskFileInfo.ParentName = base.diskPathname; diskFileInfo.ProgramName = Filename; diskFileInfo.Extension = FileExtension; if (FileExtension.Length > 0) { diskFileInfo.ProgramName = String.Format("{0}.{1}", Filename, FileExtension); } else { diskFileInfo.ProgramName = Filename; } diskFileInfo.FirstTrack = FileDescTrack; diskFileInfo.FirstSector = FileDescSector; diskFileInfo.LengthSectors = SectorsUsed; if (ProtectionStatus == 0xC0) { diskFileInfo.Protection = OricProgram.ProtectionStatus.Protected; } else if (ProtectionStatus == 0x40) { diskFileInfo.Protection = OricProgram.ProtectionStatus.Unprotected; } else { diskFileInfo.Protection = OricProgram.ProtectionStatus.Unprotected; } Byte[] FileDescriptor = base.ReadSector(FileDescTrack, FileDescSector); System.IO.MemoryStream stmFileDescriptor = new System.IO.MemoryStream(FileDescriptor, 0, FileDescriptor.Length); System.IO.BinaryReader rdrFileDescriptor = new System.IO.BinaryReader(stmFileDescriptor); stmFileDescriptor.Seek(0x03, SeekOrigin.Begin); Byte FileType = rdrFileDescriptor.ReadByte(); if ((FileType & 0x08) == 0x08) { // We have a direct access file diskFileInfo.m_ui16NoOfRecords = rdrFileDescriptor.ReadUInt16(); diskFileInfo.m_ui16RecordLength = rdrFileDescriptor.ReadUInt16(); diskFileInfo.StartAddress = 0x0000; diskFileInfo.EndAddress = (ushort)(diskFileInfo.m_ui16NoOfRecords * diskFileInfo.m_ui16RecordLength); } else if ((FileType & 0x10) == 0x10) { // We have a sequential file diskFileInfo.StartAddress = 0x0000; diskFileInfo.EndAddress = (ushort)((diskFileInfo.LengthSectors - 1) * 256); } else { diskFileInfo.StartAddress = rdrFileDescriptor.ReadUInt16(); diskFileInfo.EndAddress = rdrFileDescriptor.ReadUInt16(); } diskFileInfo.ExeAddress = rdrFileDescriptor.ReadUInt16(); if ((FileType & 0x08) == 0x08) { diskFileInfo.Format = OricProgram.ProgramFormat.DirectAccessFile; } else if ((FileType & 0x10) == 0x10) { diskFileInfo.Format = OricProgram.ProgramFormat.SequentialFile; } else if ((FileType & 0x20) == 0x20) { diskFileInfo.Format = OricProgram.ProgramFormat.WindowFile; } else if ((FileType & 0x40) == 0x40) { diskFileInfo.Format = OricProgram.ProgramFormat.CodeFile; } else if ((FileType & 0x80) == 0x80) { diskFileInfo.Format = OricProgram.ProgramFormat.BasicProgram; } else { diskFileInfo.Format = OricProgram.ProgramFormat.UnknownFile; } if (diskFileInfo.Format == OricProgram.ProgramFormat.CodeFile) { switch (diskFileInfo.StartAddress) { case 0xBB80: if (diskFileInfo.ProgramName.ToUpper().EndsWith(".HLP")) { diskFileInfo.Format = OricProgram.ProgramFormat.HelpFile; } else { diskFileInfo.Format = OricProgram.ProgramFormat.TextScreen; } break; case 0xBBA8: if (diskFileInfo.ProgramName.ToUpper().EndsWith(".HLP")) { diskFileInfo.Format = OricProgram.ProgramFormat.HelpFile; } else { diskFileInfo.Format = OricProgram.ProgramFormat.TextScreen; } break; case 0xA000: diskFileInfo.Format = OricProgram.ProgramFormat.HiresScreen; break; case 0xB500: diskFileInfo.Format = OricProgram.ProgramFormat.CharacterSet; break; default: diskFileInfo.Format = OricProgram.ProgramFormat.CodeFile; break; } if (diskFileInfo.StartAddress >= 0xA000 && diskFileInfo.StartAddress <= 0xBF3F) { // Possibly a HIRES screen if (diskFileInfo.ProgramName.ToUpper().EndsWith(".HRS")) { diskFileInfo.Format = OricProgram.ProgramFormat.HiresScreen; } } if (diskFileInfo.ProgramName.ToUpper().EndsWith(".CHS")) { diskFileInfo.Format = OricProgram.ProgramFormat.CharacterSet; } } if ((FileType & 0x01) == 0x01) { diskFileInfo.AutoRun = OricProgram.AutoRunFlag.Enabled; } else { diskFileInfo.AutoRun = OricProgram.AutoRunFlag.Disabled; } diskCatalog.Add(diskFileInfo); } DirectoryIndex++; } while (DirectoryIndex < 15); } diskDirectory = new OricFileInfo[diskCatalog.Count]; diskCatalog.CopyTo(diskDirectory); return(diskDirectory); }
private void BuildSedOricSectorMap2(UInt16[] sectorMap, String diskPathname) { int iFileNum = 1; UInt16 bNextTrack = 0; UInt16 bNextSector = 0; UInt16 bNextDescTrack; UInt16 bNextDescSector; Byte[] bByteArray = new Byte[10]; String strSectorKey = ""; OricFileInfo[] programList = ReadDirectory(diskPathname); foreach (OricFileInfo programInfo in programList) { UInt16 bTrack; UInt16 bSector; bTrack = programInfo.FirstTrack; bSector = programInfo.FirstSector; do { Byte[] bitmapSector = base.ReadSector(bTrack, bSector, ref bNextTrack, ref bNextSector); // Add file descriptor to the sector map UpdateSectorMap(sectorMap, bTrack, bSector, (UInt16)(0x1100 + Convert.ToByte(iFileNum))); bTrack = bNextTrack; bSector = bNextSector; // Safety net if (bTrack > tracksPerSide || bNextSector > sectorsPerTrack) { // Might have a problem bSector = 0; } } while (bSector != 0); strSectorKey = CreateKey(programInfo.FirstTrack, programInfo.FirstSector); bNextTrack = programInfo.FirstTrack; bNextSector = programInfo.FirstSector; do { // Read the file descriptor Byte[] sectorData = base.ReadSector(bNextTrack, bNextSector); System.IO.MemoryStream stm = new System.IO.MemoryStream(sectorData, 0, sectorData.Length); System.IO.BinaryReader rdr = new System.IO.BinaryReader(stm); bNextTrack = rdr.ReadByte(); bNextSector = rdr.ReadByte(); bNextDescTrack = bNextTrack; bNextDescSector = bNextSector; Byte bFirstDesc = rdr.ReadByte(); int iDescIndex = 0; Byte bDataTrack; Byte bDataSector; int iTotalDescriptors; if (bFirstDesc == 0xFF) { bByteArray = rdr.ReadBytes(9); bDataTrack = rdr.ReadByte(); bDataSector = rdr.ReadByte(); iTotalDescriptors = 121; } else { bDataTrack = bFirstDesc; bDataSector = rdr.ReadByte(); iTotalDescriptors = 126; } if (bDataSector != 0) { UpdateSectorMap(sectorMap, bDataTrack, bDataSector, (UInt16)(0x1000 + Convert.ToByte(iFileNum))); } while (bDataSector != 0 && iDescIndex < iTotalDescriptors) { if (bDataSector != 0) { bDataTrack = rdr.ReadByte(); bDataSector = rdr.ReadByte(); if (bDataSector != 0) { UpdateSectorMap(sectorMap, bDataTrack, bDataSector, (UInt16)(0x1000 + Convert.ToByte(iFileNum))); } iDescIndex++; } } strSectorKey = CreateKey(bNextDescTrack, bNextDescSector); } while (bNextDescSector != 0); iFileNum++; } }
private Boolean FindFile(String filename, ref Byte track, ref Byte sector, ref Byte index) { System.Text.Encoding enc = System.Text.Encoding.ASCII; Boolean fileMatchFound = false; Byte dirTrack = 20; Byte dirSector = 4; Byte nextDirTrack = 20; Byte nextDirSector = 4; while ((nextDirTrack != 0 && nextDirSector != 0) && fileMatchFound == false) { // Read current Directory Sector Byte[] directory = base.ReadSector(dirTrack, dirSector); nextDirTrack = directory[0x00]; nextDirSector = directory[0x01]; index = 0; // Scan thru each file in the current directory System.IO.MemoryStream memStream = new System.IO.MemoryStream(directory, 0, directory.Length); System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(memStream); // Move to first entry memStream.Seek(0x10, SeekOrigin.Begin); while (!fileMatchFound && index < 15) { if (binaryReader.PeekChar() != 0x00) { Byte[] fileName = binaryReader.ReadBytes(9); Byte[] extension = binaryReader.ReadBytes(3); String dirFilename = enc.GetString(fileName).Trim(); String dirExtension = enc.GetString(extension).Trim(); String pathname = String.Format("{0}.{1}", dirFilename, dirExtension); if (pathname == filename) { fileMatchFound = true; } else { index++; } } binaryReader.ReadBytes(4); } if (!fileMatchFound) { dirTrack = nextDirTrack; dirSector = nextDirSector; } else { track = dirTrack; sector = dirSector; index++; } } return(fileMatchFound); }
public static Grf grf_callback_open(string fname, string mode, GrfOpenCallback callback) { byte[] buf = new byte[GRF_HEADER_FULL_LEN]; uint i;//, zero_fcount = GrfSupport.ToLittleEndian32(7), create_ver = GrfSupport.ToLittleEndian32(0x0200); Grf grf; if (fname == null || mode == null) { throw new Exception("GE_BADARGS"); } /* Allocate memory for grf */ grf = new Grf(); /* Copy the filename */ grf.filename = fname; /* Open the file */ var fStream = FileManager.Load(grf.filename) as Stream; if (fStream == null) { throw new Exception("GE_ERRNO"); } using (var br = new System.IO.BinaryReader(fStream)) { grf.allowWrite = !mode.Contains("+") && mode.Contains("w"); //***skipped write***/ /* Read the header */ buf = br.ReadBytes(GRF_HEADER_FULL_LEN); /* Check the header */ string strA = Encoding.ASCII.GetString(buf); int v = string.Compare(strA, 0, GRF_HEADER, 0, GRF_HEADER_LEN); if (v != 0) { throw new Exception("GE_INVALID"); } /* Continued header check... * * GRF files that allow encryption of the files inside the archive * have a hex header following "Master of Magic" (not including * the nul-terminator) that looks like: * 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E * * GRF files that do not allow it have a hex header that looks like: * 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 * * GRF files that do not allow it are generally found after a * "Ragnarok.exe /repak" command has been issued */ if (buf[GRF_HEADER_LEN + 1] == 1) { grf.allowCrypt = 1; /* 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E */ for (i = 0; i < 0xF; i++) { if (buf[GRF_HEADER_LEN + i] != (int)i) { throw new Exception("GE_CORRUPTED"); } } } else if (buf[GRF_HEADER_LEN] == 0) { grf.allowCrypt = 0; /* 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */ for (i = 0; i < 0xF; i++) { if (buf[GRF_HEADER_LEN + i] != 0) { new Exception("GE_CORRUPTED"); } } } else { throw new Exception("GE_CORRUPTED"); } /* Okay, so we finally are sure that its a valid GRF/GPF file. * now its time to read info from it */ /* Set the type of archive this is */ grf.type = GRF_TYPE_GRF; /* Read the version */ grf.version = GrfSupport.LittleEndian32(buf, GRF_HEADER_MID_LEN + 0xC); /* Read the number of files */ grf.nfiles = GrfSupport.LittleEndian32(buf, GRF_HEADER_MID_LEN + 8); grf.nfiles -= GrfSupport.LittleEndian32(buf, GRF_HEADER_MID_LEN + 4) + 7; /* Create the array of files */ grf.files = new Hashtable(StringComparer.OrdinalIgnoreCase); /* Grab the filesize */ grf.len = (uint)fStream.Length; /* Seek to the offset of the file tables */ br.BaseStream.Seek(GrfSupport.LittleEndian32(buf, GRF_HEADER_MID_LEN) + GRF_HEADER_FULL_LEN, SeekOrigin.Begin); /* Run a different function to read the file information based on * the major version number */ switch (grf.version & 0xFF00) { case 0x0200: i = GRF_readVer2_info(br, grf, callback); break; default: throw new Exception("UNSUP_GRF_VERSION"); } if (i > 0) { return(null); } } return(grf); }
private void OnAcceptCommand() { if (_sVerificationCode == "") { return; } Log.DebugFormat("Sending verification code {0}", _sVerificationCode); // Create a collection object and populate it using the PFX file bool bResult = true; string sStationNumber = null; #if STAGINGUITEST sStationNumber = _sVerificationCode.Substring(0, 4); #else if (System.Diagnostics.Debugger.IsAttached && string.IsNullOrEmpty(ConfigurationManager.AppSettings["CertificateUrl"])) { sStationNumber = _sVerificationCode.Substring(0, 4); } else if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["CertificateUrl"])) { string url = ConfigurationManager.AppSettings["CertificateUrl"]; HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(url); ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); }; ASCIIEncoding encoding = new ASCIIEncoding(); string postData = "c=" + _sVerificationCode; byte[] data = encoding.GetBytes(postData); httpWReq.Method = "POST"; httpWReq.ContentType = "application/x-www-form-urlencoded"; httpWReq.ContentLength = data.Length; using (Stream stream = httpWReq.GetRequestStream()) { stream.Write(data, 0, data.Length); } HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse(); System.IO.Stream dataStream = response.GetResponseStream(); System.IO.BinaryReader streamReader = new System.IO.BinaryReader(dataStream); IList <byte[]> array = new List <byte[]>(); do { byte[] tmpfile = streamReader.ReadBytes(1024); array.Add(tmpfile); } while (array.Last().Length == 1024); byte[] file = new byte[array.Sum(x => x.Length)]; int i = 0; foreach (var bytese in array) { foreach (var b in bytese) { file[i++] = b; } } dataStream.Close(); streamReader.Close(); string certFilename = DateTime.Now.ToFileTime() + "cert.p12"; FileStream fs = new FileStream(certFilename, FileMode.CreateNew); BinaryWriter bw = new BinaryWriter(fs); for (int j = 0; j < file.Length; j++) { bw.Write(file[j]); } streamReader.Close(); response.Close(); fs.Flush(); fs.Close(); try { X509Certificate2 cert = new X509Certificate2(file, _sVerificationCode); var serviceRuntimeUserCertificateStore = new X509Store(StoreName.My); serviceRuntimeUserCertificateStore.Open(OpenFlags.ReadWrite); foreach (var certificate in serviceRuntimeUserCertificateStore.Certificates) { if (certificate.Subject.Contains("Sportradar AG")) { serviceRuntimeUserCertificateStore.Remove(certificate); break; } } var process = new Process(); var startInfo = new ProcessStartInfo(); startInfo.WindowStyle = ProcessWindowStyle.Hidden; startInfo.FileName = "certutil.exe"; startInfo.Arguments = " -f -user -p " + _sVerificationCode + " -importpfx " + certFilename; process.StartInfo = startInfo; process.Start(); serviceRuntimeUserCertificateStore.Close(); sStationNumber = cert.Subject.Substring(cert.Subject.IndexOf("CN=") + 3, cert.Subject.IndexOf(", ", cert.Subject.IndexOf("CN=")) - cert.Subject.IndexOf("CN=") - 3); sStationNumber = sStationNumber.Replace("terminal", ""); } catch (Exception e) { Log.Error(e.Message, e); ShowError(TranslationProvider.Translate(MultistringTags.CERTIFICATE_ERROR).ToString()); return; } } else { try { sStationNumber = WsdlRepository.GetStationByVerificationNumber(_sVerificationCode); } catch (Exception ex) { Log.Error("", ex); ShowError(ex.Message); return; } } #endif try { if (bResult) { Log.InfoFormat("Saving station number {0} to database", sStationNumber); StationRepository.SetStationAppConfigValue("StationNumber", sStationNumber); } } catch (Exception Ex) { Log.Error("", Ex); ShowError("Can't connect to database " + Ex.Message); return; } _sVerificationCode = ""; Log.Debug("Closing verification window"); /* ChangeTracker.VerifivationCancelled = false; * ChangeTracker.VerificationRestart = true;*/ Log.Debug("Exiting verification window"); Mediator.SendMessage <long>(0, MsgTag.RestartApplication); }
protected override sealed bool SendRequest_Internal(AstoriaRequest request, out AstoriaResponse response) { HttpWebRequest underlyingRequest = (HttpWebRequest)HttpWebRequest.Create(request.URI); WebResponse underlyingResponse; #region set up request // workaround: Protocol Violation in HttpWebRequest when receiving an immediate error response from server before sending request body // ideally, we would only flip this to false if we knew the request would have an error, // but we can't reliably tell at this point if (AstoriaTestProperties.Host == Host.IDSH || AstoriaTestProperties.Host == Host.IDSH2) { if (Environment.OSVersion.Version.Major < 6 || Environment.OSVersion.Version.Minor < 1) { underlyingRequest.ServicePoint.Expect100Continue = false; } } underlyingRequest.UseDefaultCredentials = AstoriaTestProperties.HostAuthenicationMethod.Equals("Windows", StringComparison.InvariantCultureIgnoreCase); underlyingRequest.Method = request.Verb.ToHttpMethod(); underlyingRequest.Accept = request.Accept; underlyingRequest.ContentType = request.ContentType; foreach (KeyValuePair <string, string> header in request.Headers) { switch (header.Key) { case "Accept": case "Content-Type": break; default: underlyingRequest.Headers.Add(header.Key, header.Value); break; } } underlyingRequest.ContentLength = 0; byte[] bytes = request.PayloadBytes; if (bytes != null) { underlyingRequest.ContentLength = bytes.Length; try { using (Stream os = underlyingRequest.GetRequestStream()) { os.Write(bytes, 0, bytes.Length); } } catch (WebException ex) { HandleWebException(ex, out underlyingResponse); response = null; return(false); } } else if (request.HttpStreamWriter != null) { // Call external stream writer. try { // Set ContentLength header. underlyingRequest.ContentLength = request.HttpStreamWriter(null); // Stream payload. using (Stream requestStream = underlyingRequest.GetRequestStream()) { request.HttpStreamWriter(requestStream); } } catch (WebException ex) { HandleWebException(ex, out underlyingResponse); response = null; return(false); } } #endregion try { underlyingResponse = underlyingRequest.GetResponse(); } catch (WebException webException) { if (HandleWebException(webException, out underlyingResponse)) { if (underlyingResponse == null) { response = null; return(false); } } else { throw webException; } } // This should not be possible if (underlyingResponse == null) { AstoriaTestLog.FailAndThrow("Somehow got a null underlying response"); } HttpWebResponse httpResponse = underlyingResponse as HttpWebResponse; response = new AstoriaResponse(request); #region populate response response.ContentType = underlyingResponse.ContentType; // hook everything up if (httpResponse != null) { response.ActualStatusCode = httpResponse.StatusCode; } else { response.ActualStatusCode = HttpStatusCode.Ambiguous; } // have to be careful and only mark ETag as found if it was actually sent // regardless of whether the value was null response.ETagHeaderFound = false; foreach (string header in underlyingResponse.Headers.AllKeys) { if (header == "ETag") { response.ETagHeaderFound = true; } if (underlyingResponse is HttpWebResponse) { response.Headers[header] = (underlyingResponse as HttpWebResponse).GetResponseHeader(header); } else { response.Headers[header] = string.Join(", ", underlyingResponse.Headers.GetValues(header)); } } // For Streamed/StreamedResponse, Transfer-Encoding is chunked and ContentLength could be -1 if ((underlyingResponse.Headers[HttpResponseHeader.TransferEncoding] == "chunked" || underlyingResponse.ContentLength > 0)) { Encoding encoding = Encoding.UTF8; using (Stream responseStream = underlyingResponse.GetResponseStream()) { if (request.HttpStreamReader != null) { // Call external stream reader. response.Payload = request.HttpStreamReader(responseStream); } else { if (underlyingResponse.ContentLength > 0 && response.ContentType == SerializationFormatKinds.MimeApplicationOctetStream) { using (System.IO.BinaryReader reader = new System.IO.BinaryReader(responseStream)) response.Bytes = reader.ReadBytes((int)underlyingResponse.ContentLength); } else { using (System.IO.TextReader reader = new System.IO.StreamReader(responseStream, encoding)) response.Payload = reader.ReadToEnd(); } } } } else { // only make an assignment to response.Payload if we're sure there was no content // if we set this prematurely, it can mess up the internal state of the response response.Payload = string.Empty; } #endregion return(true); }
public override System.Collections.Generic.Queue <Moonfish.Tags.BlamPointer> ReadFields(System.IO.BinaryReader binaryReader) { System.Collections.Generic.Queue <Moonfish.Tags.BlamPointer> pointerQueue = new System.Collections.Generic.Queue <Moonfish.Tags.BlamPointer>(base.ReadFields(binaryReader)); this.fieldskip = binaryReader.ReadBytes(6); return(pointerQueue); }
/// <summary> Receive the response from the server /// Message format : /// 8 bytes = lenght of the following message /// block = error no + "\001" + datas /// </summary> //UPGRADE_NOTE: Synchronized keyword was removed from method 'receive'. Lock expression was added. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1027"' private D3Buffer receive() { lock (this) { int length; byte[] buf; System.String stat; int status = D3Constants.D3_ERR; System.Collections.ArrayList inBuffer = new System.Collections.ArrayList(); try { buf = new byte[8]; // Reading the lenght //UPGRADE_TODO: Equivalent of method 'java.io.DataInputStream.readFully' may not have an optimal performance in C#. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1117"' //SupportClass.ReadInput(d3sIn.BaseStream, ref buf, 0, 8); buf = d3sIn.ReadBytes(8); char[] tmpChar; tmpChar = new char[buf.Length]; buf.CopyTo(tmpChar, 0); System.String slen = new System.String(tmpChar, 0, 8); length = System.Int32.Parse(slen); buf = new byte[length]; // reading datas with this lenght //UPGRADE_TODO: Equivalent of method 'java.io.DataInputStream.readFully' may not have an optimal performance in C#. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1117"' //SupportClass.ReadInput(d3sIn.BaseStream, ref buf, 0, length); buf = d3sIn.ReadBytes(length); } catch (System.Exception e) { throw new D3Exception("Could not receive response from " + this.server + " {" + e.Message + "}"); } // Converting into vector with "\001" as separator char[] tmpChar2; tmpChar2 = new char[buf.Length]; buf.CopyTo(tmpChar2, 0); //SupportClass.Tokenizer st = new SupportClass.Tokenizer(new System.String(tmpChar2), "\x0001"); char seps = '\x0001'; String[] st = (new System.String(tmpChar2)).Split(seps); // Error no is always the first //stat = st.NextToken(); int cnt = 0; stat = ""; foreach (String line in st) { if (cnt == 0) { stat = line; } else { if (line == String.Empty) { inBuffer.Add(""); } else { inBuffer.Add(line); } } cnt++; if (line == String.Empty) { continue; } } /* * if (st.HasMoreTokens()) * { * do * { * inBuffer.Add(st.NextToken()); * } * while (st.HasMoreTokens()); * } * else * { * // if there is no data, we must add an empty string * inBuffer.Add(""); * } * */ // get error code returned as first ASCII string try { status = System.Int32.Parse(stat); } catch { status = -1; } return(new D3Buffer(status, inBuffer)); } }
/// <summary> /// (INCOMPLETE) Retrieve file information for a RAR file /// </summary> /// TODO: Write the rest of this RAR file handling public void GetRarFileInfo() { if (!File.Exists(this.Filename)) { return; } BinaryReader br = new BinaryReader(Utilities.TryOpenRead(this.Filename)); // Check for the signature first (Skipping the SFX Module) byte[] signature = br.ReadBytes(8); int startpos = 0; while (startpos < Constants.MibiByte && !signature.StartsWith(Constants.RarSignature, exact: true) && !signature.StartsWith(Constants.RarFiveSignature, exact: true)) { startpos++; br.BaseStream.Position = startpos; signature = br.ReadBytes(8); } if (!signature.StartsWith(Constants.RarSignature, exact: true) && !signature.StartsWith(Constants.RarFiveSignature, exact: true)) { return; } CoreRarArchive cra = new CoreRarArchive(); if (startpos > 0) { br.BaseStream.Position = 0; cra.SFX = br.ReadBytes(startpos); } // Get all archive header information cra.HeaderCRC32 = br.ReadUInt32(); cra.HeaderSize = br.ReadUInt32(); uint headerType = br.ReadUInt32(); // Special encryption information bool hasEncryptionHeader = false; // If it's encrypted if (headerType == (uint)RarHeaderType.ArchiveEncryption) { hasEncryptionHeader = true; cra.EncryptionHeaderCRC32 = cra.HeaderCRC32; cra.EncryptionHeaderSize = cra.HeaderSize; cra.EncryptionHeaderFlags = (RarHeaderFlags)br.ReadUInt32(); cra.EncryptionVersion = br.ReadUInt32(); cra.EncryptionFlags = br.ReadUInt32(); cra.KDFCount = br.ReadByte(); cra.Salt = br.ReadBytes(16); cra.CheckValue = br.ReadBytes(12); cra.HeaderCRC32 = br.ReadUInt32(); cra.HeaderSize = br.ReadUInt32(); headerType = br.ReadUInt32(); } cra.HeaderFlags = (RarHeaderFlags)br.ReadUInt32(); if ((cra.HeaderFlags & RarHeaderFlags.ExtraAreaPresent) != 0) { cra.ExtraAreaSize = br.ReadUInt32(); } cra.ArchiveFlags = (RarArchiveFlags)br.ReadUInt32(); if ((cra.ArchiveFlags & RarArchiveFlags.VolumeNumberField) != 0) { cra.VolumeNumber = br.ReadUInt32(); } if (((cra.HeaderFlags & RarHeaderFlags.ExtraAreaPresent) != 0) && cra.ExtraAreaSize != 0) { cra.ExtraArea = br.ReadBytes((int)cra.ExtraAreaSize); } // Archive Comment Service Header // Now for file headers for (; ;) { CoreRarArchiveEntry crae = new CoreRarArchiveEntry(); crae.HeaderCRC32 = br.ReadUInt32(); crae.HeaderSize = br.ReadUInt32(); crae.HeaderType = (RarHeaderType)br.ReadUInt32(); if (crae.HeaderType == RarHeaderType.EndOfArchive) { break; } crae.HeaderFlags = (RarHeaderFlags)br.ReadUInt32(); if ((crae.HeaderFlags & RarHeaderFlags.ExtraAreaPresent) != 0) { crae.ExtraAreaSize = br.ReadUInt32(); } if ((crae.HeaderFlags & RarHeaderFlags.DataAreaPresent) != 0) { crae.DataAreaSize = br.ReadUInt32(); } crae.FileFlags = (RarFileFlags)br.ReadUInt32(); crae.UnpackedSize = br.ReadUInt32(); if ((crae.FileFlags & RarFileFlags.UnpackedSizeUnknown) != 0) { crae.UnpackedSize = 0; } crae.Attributes = br.ReadUInt32(); crae.mtime = br.ReadUInt32(); crae.DataCRC32 = br.ReadUInt32(); crae.CompressionInformation = br.ReadUInt32(); crae.HostOS = br.ReadUInt32(); crae.NameLength = br.ReadUInt32(); crae.Name = br.ReadBytes((int)crae.NameLength); if ((crae.HeaderFlags & RarHeaderFlags.ExtraAreaPresent) != 0) { uint extraSize = br.ReadUInt32(); switch (br.ReadUInt32()) // Extra Area Type { case 0x01: // File encryption information crae.EncryptionSize = extraSize; crae.EncryptionFlags = (RarEncryptionFlags)br.ReadUInt32(); crae.KDFCount = br.ReadByte(); crae.Salt = br.ReadBytes(16); crae.IV = br.ReadBytes(16); crae.CheckValue = br.ReadBytes(12); break; case 0x02: // File data hash crae.HashSize = extraSize; crae.HashType = br.ReadUInt32(); crae.HashData = br.ReadBytes(32); break; case 0x03: // High precision file time crae.TimeSize = extraSize; crae.TimeFlags = (RarTimeFlags)br.ReadUInt32(); if ((crae.TimeFlags & RarTimeFlags.TimeInUnixFormat) != 0) { if ((crae.TimeFlags & RarTimeFlags.ModificationTimePresent) != 0) { crae.TimeMtime64 = br.ReadUInt64(); } if ((crae.TimeFlags & RarTimeFlags.CreationTimePresent) != 0) { crae.TimeCtime64 = br.ReadUInt64(); } if ((crae.TimeFlags & RarTimeFlags.LastAccessTimePresent) != 0) { crae.TimeLtime64 = br.ReadUInt64(); } } else { if ((crae.TimeFlags & RarTimeFlags.ModificationTimePresent) != 0) { crae.TimeMtime = br.ReadUInt32(); } if ((crae.TimeFlags & RarTimeFlags.CreationTimePresent) != 0) { crae.TimeCtime = br.ReadUInt32(); } if ((crae.TimeFlags & RarTimeFlags.LastAccessTimePresent) != 0) { crae.TimeLtime = br.ReadUInt32(); } } break; case 0x04: // File version number crae.VersionSize = extraSize; /* crae.VersionFlags = */ br.ReadUInt32(); crae.VersionNumber = br.ReadUInt32(); break; case 0x05: // File system redirection crae.RedirectionSize = extraSize; crae.RedirectionType = (RarRedirectionType)br.ReadUInt32(); crae.RedirectionFlags = br.ReadUInt32(); crae.RedirectionNameLength = br.ReadUInt32(); crae.RedirectionName = br.ReadBytes((int)crae.RedirectionNameLength); break; case 0x06: // Unix owner and group information crae.UnixOwnerSize = extraSize; crae.UnixOwnerFlags = (RarUnixOwnerRecordFlags)br.ReadUInt32(); if ((crae.UnixOwnerFlags & RarUnixOwnerRecordFlags.UserNameStringIsPresent) != 0) { crae.UnixOwnerUserNameLength = br.ReadUInt32(); crae.UnixOwnerUserName = br.ReadBytes((int)crae.UnixOwnerUserNameLength); } if ((crae.UnixOwnerFlags & RarUnixOwnerRecordFlags.GroupNameStringIsPresent) != 0) { crae.UnixOwnerGroupNameLength = br.ReadUInt32(); crae.UnixOwnerGroupName = br.ReadBytes((int)crae.UnixOwnerGroupNameLength); } if ((crae.UnixOwnerFlags & RarUnixOwnerRecordFlags.NumericUserIdIsPresent) != 0) { crae.UnixOwnerUserId = br.ReadUInt32(); } if ((crae.UnixOwnerFlags & RarUnixOwnerRecordFlags.NumericGroupIdIsPresent) != 0) { crae.UnixOwnerGroupId = br.ReadUInt32(); } break; case 0x07: // Service header data array break; } } if ((crae.HeaderFlags & RarHeaderFlags.DataAreaPresent) != 0) { crae.DataArea = br.ReadBytes((int)crae.DataAreaSize); } } }
public override System.Collections.Generic.Queue <Moonfish.Tags.BlamPointer> ReadFields(System.IO.BinaryReader binaryReader) { System.Collections.Generic.Queue <Moonfish.Tags.BlamPointer> pointerQueue = new System.Collections.Generic.Queue <Moonfish.Tags.BlamPointer>(base.ReadFields(binaryReader)); this.fieldpad = binaryReader.ReadBytes(8); this.EnglishStringCount = binaryReader.ReadInt32(); this.EnglishStringTableLength = binaryReader.ReadInt32(); this.EnglishStringIndexAddress = binaryReader.ReadInt32(); this.EnglishStringTableAddress = binaryReader.ReadInt32(); this.fieldpad0 = binaryReader.ReadBytes(4); this.fieldpad1 = binaryReader.ReadBytes(8); this.JapaneseStringCount = binaryReader.ReadInt32(); this.JapaneseStringTableLength = binaryReader.ReadInt32(); this.JapaneseStringIndexAddress = binaryReader.ReadInt32(); this.JapaneseStringTableAddress = binaryReader.ReadInt32(); this.fieldpad2 = binaryReader.ReadBytes(4); this.fieldpad3 = binaryReader.ReadBytes(8); this.DutchStringCount = binaryReader.ReadInt32(); this.DutchStringTableLength = binaryReader.ReadInt32(); this.DutchStringIndexAddress = binaryReader.ReadInt32(); this.DutchStringTableAddress = binaryReader.ReadInt32(); this.fieldpad4 = binaryReader.ReadBytes(4); this.fieldpad5 = binaryReader.ReadBytes(8); this.FrenchStringCount = binaryReader.ReadInt32(); this.FrenchStringTableLength = binaryReader.ReadInt32(); this.FrenchStringIndexAddress = binaryReader.ReadInt32(); this.FrenchStringTableAddress = binaryReader.ReadInt32(); this.fieldpad6 = binaryReader.ReadBytes(4); this.fieldpad7 = binaryReader.ReadBytes(8); this.SpanishStringCount = binaryReader.ReadInt32(); this.SpanishStringTableLength = binaryReader.ReadInt32(); this.SpanishStringIndexAddress = binaryReader.ReadInt32(); this.SpanishStringTableAddress = binaryReader.ReadInt32(); this.fieldpad8 = binaryReader.ReadBytes(4); this.fieldpad9 = binaryReader.ReadBytes(8); this.ItalianStringCount = binaryReader.ReadInt32(); this.ItalianStringTableLength = binaryReader.ReadInt32(); this.ItalianStringIndexAddress = binaryReader.ReadInt32(); this.ItalianStringTableAddress = binaryReader.ReadInt32(); this.fieldpad10 = binaryReader.ReadBytes(4); this.fieldpad11 = binaryReader.ReadBytes(8); this.KoreanStringCount = binaryReader.ReadInt32(); this.KoreanStringTableLength = binaryReader.ReadInt32(); this.KoreanStringIndexAddress = binaryReader.ReadInt32(); this.KoreanStringTableAddress = binaryReader.ReadInt32(); this.fieldpad12 = binaryReader.ReadBytes(4); this.fieldpad13 = binaryReader.ReadBytes(8); this.ChineseStringCount = binaryReader.ReadInt32(); this.ChineseStringTableLength = binaryReader.ReadInt32(); this.ChineseStringIndexAddress = binaryReader.ReadInt32(); this.ChineseStringTableAddress = binaryReader.ReadInt32(); this.fieldpad14 = binaryReader.ReadBytes(4); this.fieldpad15 = binaryReader.ReadBytes(8); this.PortugueseStringCount = binaryReader.ReadInt32(); this.PortugueseStringTableLength = binaryReader.ReadInt32(); this.PortugueseStringIndexAddress = binaryReader.ReadInt32(); this.PortugueseStringTableAddress = binaryReader.ReadInt32(); this.fieldpad16 = binaryReader.ReadBytes(4); return(pointerQueue); }