Esempio n. 1
0
        /// <summary>
        /// 根据文件的前2个字节进行判断文件类型  ---说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
        /// </summary>
        /// <param name="hpf"></param>
        /// <param name="code">文件的前2个字节转化出来的小数</param>
        /// <returns></returns>
        public bool CheckUploadByTwoByte(HttpPostedFile hpf, Int64 code)
        {
            System.IO.FileStream fs = new System.IO.FileStream(hpf.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
            string fileclass = "";
            byte buffer;
            try
            {
                buffer = r.ReadByte();
                fileclass = buffer.ToString();
                buffer = r.ReadByte();
                fileclass += buffer.ToString();

            }
            catch
            {

            }
            r.Close();
            fs.Close();
            //
            //if (fileclass == code.ToString())
            //{
            //    return true;
            //}
            //else
            //{
            //    return false;
            //}
            return (fileclass == code.ToString());
        }
Esempio n. 2
0
        public void Parse(Header header, byte[] data)
        {
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data))
            {
                using (System.IO.BinaryReader br = new System.IO.BinaryReader(ms))
                {
                    _authCode = br.ReadInt32();
                    _accountId = br.ReadUInt32();
                    _userLevel = br.ReadUInt32();
                    _lastLoginIP = br.ReadUInt32();
                    _lastLoginTime = br.ReadBytes(26);
                    _sex = br.ReadByte();

                    _serverList = new Dictionary<string, Server>();
                    for (int i = (int)ms.Position; i < header.Size; i += 32)
                    {
                        Server s = new Server();
                        s.IP = string.Format("{0}.{1}.{2}.{3}", br.ReadByte(), br.ReadByte(), br.ReadByte(), br.ReadByte());
                        s.Port = br.ReadInt16();
                        s.Name = br.ReadBytes(22).NullByteTerminatedString();
                        s.Type = br.ReadInt16();
                        s.UserCount = br.ReadInt16();
                        _serverList.Add(s.Name, s);
                    }
                }
            }
        }
Esempio n. 3
0
        static void ExtractSPR(string filename)
        {
            using (System.IO.BinaryReader reader = new System.IO.BinaryReader(System.IO.File.OpenRead("TIBIA.SPR"))) {
                ushort count = reader.ReadUInt16();
                reader.BaseStream.Seek(6, System.IO.SeekOrigin.Current);

                for (int a = 1; a < count; a++) {
                    Bitmap bmp = new Bitmap(32, 32, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
                    bmp.Palette = colorPalette;
                    System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, 32, 32), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
                    byte[] byteArray = new byte[1024];

                    for (int b = 0; b < 1024; b++) {
                        byteArray[b] = 0xFF;
                    }

                    long size = reader.ReadUInt16();
                    size += reader.BaseStream.Position - 1;
                    int i = 0;

                    while (reader.BaseStream.Position <= size) {
                        if (reader.BaseStream.Position >= reader.BaseStream.Length) {
                            break;
                        }

                        ushort tPixels = reader.ReadUInt16();
                        i += tPixels;

                        if (reader.BaseStream.Position > size) {
                            break;
                        }

                        byte cPixels = reader.ReadByte();

                        for (int c = 0; c < cPixels; c++) {
                            byte color = reader.ReadByte();
                            byteArray[i] = color;
                            i++;
                        }
                    }

                    System.Runtime.InteropServices.Marshal.Copy(byteArray, 0, bmpData.Scan0, 1024);
                    bmp.UnlockBits(bmpData);
                    bmp.RotateFlip(RotateFlipType.RotateNoneFlipY);

                    if (!System.IO.Directory.Exists(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(filename), "Sprites\\"))) {
                        System.IO.Directory.CreateDirectory(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(filename), "Sprites\\"));
                    }

                    bmp.Save(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(filename), "Sprites\\" + a.ToString() + ".bmp"));
                    bmp.Dispose();
                }
            }
        }
Esempio n. 4
0
        public static void Load()
        {
            IO.Log.Write("    Loading CampaingProgresss...");
            levelsCompleted.Clear();

            System.IO.BinaryReader br = new System.IO.BinaryReader(new System.IO.FileStream("Saves/progress.lpg",
                System.IO.FileMode.Open));

            String s = "";
            int l = 0;
            while (br.PeekChar() > -1)
            {
                s = br.ReadString();
                l = br.ReadInt32();
                byte[] d = new byte[l];
                for (int j = 0; j < l; j++)
                {
                    d[j] = br.ReadByte();
                }
                levelsCompleted.Add(s, d);
            }

            br.Close();
            IO.Log.Write("    Loading complete");
        }
Esempio n. 5
0
 public void Parse(Header header, byte[] data)
 {
     using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data))
     {
         using (System.IO.BinaryReader br = new System.IO.BinaryReader(ms))
         {
             _errorCode = br.ReadByte();
             _blockDate = br.ReadBytes(20).NullByteTerminatedString();
         }
     }
 }
Esempio n. 6
0
       public static byte[] ReturnBinaryByteFromFile(string path)
       {
           var stream = System.IO.File.OpenRead(path);
           System.IO.BinaryReader br = new System.IO.BinaryReader(stream);
           byte[] binary = new byte[br.BaseStream.Length];
           for (int i = 0; i < binary.Length; i++)
           {
               binary[i] = br.ReadByte();
           }
           return binary;

       }
Esempio n. 7
0
        static void ExtractPIC(string filename)
        {
            using (System.IO.BinaryReader reader = new System.IO.BinaryReader(System.IO.File.OpenRead(filename))) {
                ushort width = (ushort)(reader.ReadUInt16() + 2);
                ushort height = (ushort)(reader.ReadUInt16() + 2);
                Bitmap bmp = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
                bmp.Palette = colorPalette;
                System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, width, height), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
                byte[] byteArray = new byte[width * height];

                for (int x = 1; x < (height - 1); x++) {
                    for (int y = 1; y < (width - 1); y++) {
                        byteArray[(width * x) + y] = reader.ReadByte();
                    }
                }

                System.Runtime.InteropServices.Marshal.Copy(byteArray, 0, bmpData.Scan0, width * height);
                bmp.UnlockBits(bmpData);
                bmp.Save(filename.Substring(0, filename.IndexOf(".")) + ".bmp");
                bmp.Dispose();
            }
        }
Esempio n. 8
0
        public static System.Windows.Forms.TreeNode ParseFile(string path)
        {
            // Read archive tree
            uint nFiles, baseOffset;
            System.Windows.Forms.TreeNode node = new System.Windows.Forms.TreeNode();

            System.IO.BinaryReader stream = new System.IO.BinaryReader(System.IO.File.OpenRead(path));
            stream.ReadUInt32();
            nFiles = stream.ReadUInt32();
            baseOffset = stream.ReadUInt32();

            for (int i = 0; i < nFiles; i++)
            {
                char b;
                FileEntry f = new FileEntry();
                do
                {
                    b = (char)stream.ReadByte();
                    if (b != 0)
                        f.name += b;
                } while (b != 0);
                f.length = stream.ReadUInt32();
                stream.ReadUInt32();

                f.offset = baseOffset;
                baseOffset += f.length;

                f.idx = (uint)i;

                System.Windows.Forms.TreeNode n = new System.Windows.Forms.TreeNode(f.name);
                n.Tag = f;

                node.Nodes.Add(n);
            }

            return node;
        }
Esempio n. 9
0
        public WaveFile(short bitDepth, short channels, int sampleRate, byte[] data)
        {
            this.bitDepth = bitDepth;
            this.channels = channels;
            this.sampleRate = sampleRate;
            path = null;
            name = "[Untitled Recording]";

            System.IO.MemoryStream ms = new System.IO.MemoryStream(data);
            System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
            int numSamples = data.Length / (channels * (bitDepth / 8));
            samples = new double[channels][];
            for (int c = 0; c < channels; c++) {
                samples[c] = new double[numSamples];
            }

            if (bitDepth == 16) {
                for (int i = 0; i < numSamples; i++) {
                    for (int c = 0; c < channels; c++) {
                        //assuming signed
                        //normalized to -1.0..+1.0
                        samples[c][i] = (double)br.ReadInt16() / 32768.0;
                    }
                }
            } else if (bitDepth == 8) {
                for (int i = 0; i < numSamples; i++) {
                    for (int c = 0; c < channels; c++) {
                        //assuming unsigned
                        //normalized to -1.0..+1.0
                        samples[c][i] = (double)br.ReadByte() / 128.0 - 1.0;
                    }
                }
            } else {
                throw new FormatException("Bit depth must be one of 8 or 16 bits.");
            }
        }
Esempio n. 10
0
        public void Populate(int iOffset, int iIndexedReflexiveOffset)
        {
            this.isNulledOutReflexive = false;
            System.IO.BinaryReader BR = new System.IO.BinaryReader(meta.MS);

            int mapMetaOffset = meta.offset;

            if (this._EntIndex.reflexiveTagType + this._EntIndex.reflexiveTagName != string.Empty)
            {
                int tagNum = map.Functions.ForMeta.FindByNameAndTagType(this._EntIndex.reflexiveTagType, this._EntIndex.reflexiveTagName);
                if (tagNum != -1)
                {
                    Meta meta2 = new Meta(map);
                    map.OpenMap(MapTypes.Internal);
                    meta2.ReadMetaFromMap(tagNum, true);
                    map.CloseMap();
                    mapMetaOffset = meta2.offset;
                    this._EntIndex.reflexiveLayer = "root";
                }
            }

            if (this._EntIndex.reflexiveLayer.ToLower() == "root")
                this._IndexedReflexiveOffset = mapMetaOffset + this._EntIndex.ReflexiveOffset;
            else if (this._EntIndex.reflexiveLayer.ToLower() == "oneup")
                this._IndexedReflexiveOffset = iIndexedReflexiveOffset + this._EntIndex.ReflexiveOffset;

            /*
            bool openedMap = false;
            if (map.isOpen == false)
            {
                map.OpenMap(MapTypes.Internal);
                openedMap = true;
            }
            map.BA.Position = iOffset + this.chunkOffset;
            */
            BR.BaseStream.Position = iOffset + this.chunkOffset;
            this.offsetInMap = meta.offset + iOffset + this.chunkOffset;

            switch (_ValueType)
            {
                case IFPIO.ObjectEnum.Short:
                    {
                        this.Value = (int)BR.ReadInt16();
                        break;
                    }
                case IFPIO.ObjectEnum.Int:
                    {
                        this.Value = BR.ReadInt32();
                        break;
                    }
                case IFPIO.ObjectEnum.UShort:
                    {
                        this.Value = (int)BR.ReadUInt16();
                        break;
                    }
                case IFPIO.ObjectEnum.UInt:
                    {
                        this.Value = (int)BR.ReadUInt32();
                        break;
                    }
                case IFPIO.ObjectEnum.Byte:
                    {
                        this.Value = (int)BR.ReadByte();
                        break;
                    }
            }
            UpdateSelectionList(false);
            /*
            if (openedMap == true)
                map.CloseMap();
            */
        }
Esempio n. 11
0
        void OnReceiveMessage(DebugMessageType type, byte[] buffer)
        {
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer))
            {
                using (System.IO.BinaryReader br = new System.IO.BinaryReader(ms))
                {
                    switch (type)
                    {
                    case DebugMessageType.SCAttachResult:
                    {
                        SCAttachResult result = new SCAttachResult();
                        result.Result             = (AttachResults)br.ReadByte();
                        result.DebugServerVersion = br.ReadInt32();
                        RemoteDebugVersion        = result.DebugServerVersion;
                        waitingAttach             = false;
                    }
                    break;

                    case DebugMessageType.SCBindBreakpointResult:
                    {
                        SCBindBreakpointResult msg = new SCBindBreakpointResult();
                        msg.BreakpointHashCode = br.ReadInt32();
                        msg.Result             = (BindBreakpointResults)br.ReadByte();
                        OnReceivSendSCBindBreakpointResult(msg);
                    }
                    break;

                    case DebugMessageType.SCBreakpointHit:
                    {
                        SCBreakpointHit msg = new SCBreakpointHit();
                        msg.BreakpointHashCode = br.ReadInt32();
                        msg.ThreadHashCode     = br.ReadInt32();
                        msg.StackFrame         = ReadStackFrames(br);

                        OnReceiveSCBreakpointHit(msg);
                    }
                    break;

                    case DebugMessageType.SCStepComplete:
                    {
                        SCStepComplete msg = new SCStepComplete();
                        msg.ThreadHashCode = br.ReadInt32();
                        msg.StackFrame     = ReadStackFrames(br);
                        OnReceiveSCStepComplete(msg);
                    }
                    break;

                    case DebugMessageType.SCThreadStarted:
                    {
                        SCThreadStarted msg = new SCThreadStarted();
                        msg.ThreadHashCode = br.ReadInt32();
                        OnReceiveSCThreadStarted(msg);
                    }
                    break;

                    case DebugMessageType.SCThreadEnded:
                    {
                        SCThreadEnded msg = new SCThreadEnded();
                        msg.ThreadHashCode = br.ReadInt32();
                        OnReceiveSCThreadEnded(msg);
                    }
                    break;

                    case DebugMessageType.SCModuleLoaded:
                    {
                        SCModuleLoaded msg = new SCModuleLoaded();
                        msg.ModuleName = br.ReadString();

                        OnReceiveSCModuleLoaded(msg);
                    }
                    break;

                    case DebugMessageType.SCResolveVariableResult:
                    {
                        resolved = ReadVariableInfo(br);
                    }
                    break;
                    }
                }
            }
        }
Esempio n. 12
0
        public void Populate(int iOffset, int iIndexedReflexiveOffset)
        {
            this.isNulledOutReflexive = false;
            System.IO.BinaryReader BR = new System.IO.BinaryReader(meta.MS);

            int mapMetaOffset = meta.offset;

            if (this.EntIndex.reflexiveTagType + this.EntIndex.reflexiveTagName != string.Empty)
            {
                int tagNum = map.Functions.ForMeta.FindByNameAndTagType(this.EntIndex.reflexiveTagType, this.EntIndex.reflexiveTagName);
                if (tagNum != -1)
                {
                    Meta meta2 = new Meta(map);
                    map.OpenMap(MapTypes.Internal);
                    meta2.ReadMetaFromMap(tagNum, true);
                    map.CloseMap();
                    mapMetaOffset = meta2.offset;
                    this.EntIndex.reflexiveLayer = "root";
                }
            }

            if (this.EntIndex.reflexiveLayer.ToLower() == "root")
            {
                this.indexedReflexiveOffset = mapMetaOffset + this.EntIndex.ReflexiveOffset;
            }
            else if (this.EntIndex.reflexiveLayer.ToLower() == "oneup")
            {
                this.indexedReflexiveOffset = iIndexedReflexiveOffset + this.EntIndex.ReflexiveOffset;
            }

            /*
             * bool openedMap = false;
             * if (map.isOpen == false)
             * {
             *  map.OpenMap(MapTypes.Internal);
             *  openedMap = true;
             * }
             * map.BA.Position = iOffset + this.chunkOffset;
             */
            BR.BaseStream.Position = iOffset + this.chunkOffset;
            this.offsetInMap       = meta.offset + iOffset + this.chunkOffset;

            switch (ValueType)
            {
            case IFPIO.ObjectEnum.Short:
            {
                this.Value = (int)BR.ReadInt16();
                break;
            }

            case IFPIO.ObjectEnum.Int:
            {
                this.Value = BR.ReadInt32();
                break;
            }

            case IFPIO.ObjectEnum.UShort:
            {
                this.Value = (int)BR.ReadUInt16();
                break;
            }

            case IFPIO.ObjectEnum.UInt:
            {
                this.Value = (int)BR.ReadUInt32();
                break;
            }

            case IFPIO.ObjectEnum.Byte:
            {
                this.Value = (int)BR.ReadByte();
                break;
            }
            }
            UpdateSelectionList(false);

            /*
             * if (openedMap == true)
             *  map.CloseMap();
             */
        }
    /// <summary>
    /// Imports a Galactic SPC file into a x and an y array. The file must not be a multi spectrum file (an exception is thrown in this case).
    /// </summary>
    /// <param name="xvalues">The x values of the spectrum.</param>
    /// <param name="yvalues">The y values of the spectrum.</param>
    /// <param name="filename">The filename where to import from.</param>
    /// <returns>Null if successful, otherwise an error description.</returns>
    public static string ToArrays(string filename, out double [] xvalues, out double [] yvalues)
    {
      System.IO.Stream stream=null;

      SPCHDR hdr = new SPCHDR();
      SUBHDR subhdr = new SUBHDR();

      try
      {
        stream = new System.IO.FileStream(filename,System.IO.FileMode.Open,System.IO.FileAccess.Read,System.IO.FileShare.Read);
        System.IO.BinaryReader binreader = new System.IO.BinaryReader(stream);


        hdr.ftflgs = binreader.ReadByte(); // ftflgs : not-evenly spaced data
        hdr.fversn = binreader.ReadByte(); // fversn : new version
        hdr.fexper = binreader.ReadByte(); // fexper : general experimental technique
        hdr.fexp   = binreader.ReadByte(); // fexp   : fractional scaling exponent (0x80 for floating point)

        hdr.fnpts  = binreader.ReadInt32(); // fnpts  : number of points

        hdr.ffirst = binreader.ReadDouble(); // ffirst : first x-value
        hdr.flast  = binreader.ReadDouble(); // flast : last x-value
        hdr.fnsub  = binreader.ReadInt32(); // fnsub : 1 (one) subfile only
      
        binreader.ReadByte(); //  Type of X axis units (see definitions below) 
        binreader.ReadByte(); //  Type of Y axis units (see definitions below) 
        binreader.ReadByte(); // Type of Z axis units (see definitions below)
        binreader.ReadByte(); // Posting disposition (see GRAMSDDE.H)

        binreader.Read(new byte[0x1E0],0,0x1E0); // rest of SPC header


        // ---------------------------------------------------------------------
        //   following the x-values array
        // ---------------------------------------------------------------------

        if(hdr.fversn!=0x4B)
        {
          if(hdr.fversn==0x4D)
            throw new System.FormatException(string.Format("This SPC file has the old format version of {0}, the only version supported here is the new version {1}",hdr.fversn,0x4B));
          else
            throw new System.FormatException(string.Format("This SPC file has a version of {0}, the only version recognized here is {1}",hdr.fversn,0x4B));
        }

        if(0!=(hdr.ftflgs & 0x80))
        {
          xvalues = new double[hdr.fnpts];
          for(int i=0;i<hdr.fnpts;i++)
            xvalues[i] = binreader.ReadSingle();
        }
        else if(0==hdr.ftflgs) // evenly spaced data
        {
          xvalues = new double[hdr.fnpts];
          for(int i=0;i<hdr.fnpts;i++)
            xvalues[i] = hdr.ffirst + i*(hdr.flast-hdr.ffirst)/(hdr.fnpts-1);
        }
        else
        {
          throw new System.FormatException("The SPC file must not be a multifile; only single file format is accepted!");
        }



        // ---------------------------------------------------------------------
        //   following the y SUBHEADER
        // ---------------------------------------------------------------------

        subhdr.subflgs = binreader.ReadByte(); // subflgs : always 0
        subhdr.subexp  = binreader.ReadByte(); // subexp : y-values scaling exponent (set to 0x80 means floating point representation)
        subhdr.subindx = binreader.ReadInt16(); // subindx :  Integer index number of trace subfile (0=first)

        subhdr.subtime = binreader.ReadSingle(); // subtime;   Floating time for trace (Z axis corrdinate) 
        subhdr.subnext = binreader.ReadSingle(); // subnext;   Floating time for next trace (May be same as beg) 
        subhdr.subnois = binreader.ReadSingle(); // subnois;   Floating peak pick noise level if high byte nonzero 

        subhdr.subnpts = binreader.ReadInt32(); // subnpts;  Integer number of subfile points for TXYXYS type 
        subhdr.subscan = binreader.ReadInt32(); // subscan; Integer number of co-added scans or 0 (for collect) 
        subhdr.subwlevel = binreader.ReadSingle();        // subwlevel;  Floating W axis value (if fwplanes non-zero) 
        subhdr.subresv   = binreader.ReadInt32(); // subresv[4];   Reserved area (must be set to zero) 


        // ---------------------------------------------------------------------
        //   following the y-values array
        // ---------------------------------------------------------------------
        yvalues = new double[hdr.fnpts];
        
        if(hdr.fexp==0x80) //floating point format
        {
          for(int i=0;i<hdr.fnpts;i++)
            yvalues[i] = binreader.ReadSingle();
        }
        else // fixed exponent format
        {
          for(int i=0;i<hdr.fnpts;i++)
            yvalues[i] = binreader.ReadInt32()*Math.Pow(2,hdr.fexp-32);
        }
      }
      catch(Exception e)
      {
        xvalues = null;
        yvalues = null;
        return e.ToString();
      }
      finally
      {
        if(null!=stream)
          stream.Close();
      }
      
      return null;
    }
Esempio n. 14
0
        public override IEnumerable <Tone> ImportToneFile(string fileName)
        {
            string      ext    = System.IO.Path.GetExtension(fileName);
            var         Option = new Option();
            List <Tone> tones  = new List <Tone>();

            try
            {
                switch (ext.ToUpper(CultureInfo.InvariantCulture))
                {
                case ".OPL":
                {
                    List <Head> list          = new List <Head>();
                    byte        maxBankNumber = 0;

                    using (var file = new System.IO.BinaryReader(new System.IO.FileStream(fileName, System.IO.FileMode.Open)))
                    {
                        while (true)
                        {
                            //read head
                            Head p = new Head();
                            p.Patch  = file.ReadByte();
                            p.Bank   = file.ReadByte();
                            p.Offset = file.ReadUInt32();

                            if (p.Patch == 0xff && p.Bank == 0xff)
                            {
                                break;
                            }

                            if ((p.Bank != 0x7F) && (p.Bank > maxBankNumber))
                            {
                                maxBankNumber = p.Bank;
                            }

                            list.Add(p);
                        }
                        ;

                        for (int i = 0; i < list.Count; i++)
                        {
                            var p = list[i];
                            file.BaseStream.Seek(p.Offset, System.IO.SeekOrigin.Begin);

                            bool isPerc    = (p.Bank == 0x7F);
                            int  gmPatchId = isPerc ? p.Patch : (p.Patch + (p.Bank * 128));

                            ushort insLen = file.ReadUInt16();
                            insLen -= 2;

                            byte[] idata = new byte[24];
                            if (insLen < 24)
                            {
                                idata = file.ReadBytes(insLen);
                            }
                            else
                            {
                                idata = file.ReadBytes(24);
                                file.BaseStream.Seek(insLen - 24, System.IO.SeekOrigin.Current);
                            }

                            //var tim = Timbres[p.Patch + (isPerc ? 128 : 0)];
                            Tone tone = new Tone();
                            tone.Number = i;
                            tone.Name   = i.ToString();

                            //ins.percNoteNum = (isPerc) ? idata[0] : 0;
                            //ins.note_offset1 = (isPerc) ? 0 : idata[0];
                            //if (isPerc)
                            //{
                            //    var t = DrumTimbres[p.Patch];
                            //    t.BaseNote = (NoteNames)idata[0];
                            //    t.TimbreNumber = (ProgramAssignmentNumber)(p.Patch + 128);
                            //}

                            tone.aOp[0].AM  = (byte)((idata[1] >> 7) & 0x1);
                            tone.aOp[0].VIB = (byte)((idata[1] >> 6) & 0x1);
                            tone.aOp[0].EG  = (byte)((idata[1] >> 5) & 0x1);
                            tone.aOp[0].KSR = (byte)((idata[1] >> 4) & 0x1);
                            tone.aOp[0].ML  = (byte)((idata[1]) & 0xf);

                            tone.aOp[0].KS = (byte)((idata[2] >> 6) & 0x03);
                            tone.aOp[0].TL = (byte)((idata[2]) & 0x3f);

                            tone.aOp[0].AR = (byte)((idata[3] >> 4) & 0x0f);
                            tone.aOp[0].DR = (byte)((idata[3]) & 0x0f);

                            tone.aOp[0].SL = (byte)((idata[4] >> 4) & 0x0f);
                            tone.aOp[0].RR = (byte)((idata[4]) & 0x0f);
                            tone.aOp[0].SR = -1;

                            tone.aOp[0].WS = (byte)((idata[5]) & 0x07);

                            tone.aOp[1].AM  = (byte)((idata[7] >> 7) & 0x1);
                            tone.aOp[1].VIB = (byte)((idata[7] >> 6) & 0x1);
                            tone.aOp[1].EG  = (byte)((idata[7] >> 5) & 0x1);
                            tone.aOp[1].KSR = (byte)((idata[7] >> 4) & 0x1);
                            tone.aOp[1].ML  = (byte)((idata[7]) & 0xf);

                            tone.aOp[1].KS = (byte)((idata[8] >> 6) & 0x03);
                            tone.aOp[1].TL = (byte)((idata[8]) & 0x3f);

                            tone.aOp[1].AR = (byte)((idata[9] >> 4) & 0x0f);
                            tone.aOp[1].DR = (byte)((idata[9]) & 0x0f);

                            tone.aOp[1].SL = (byte)((idata[10] >> 4) & 0x0f);
                            tone.aOp[1].RR = (byte)((idata[10]) & 0x0f);
                            tone.aOp[1].SR = -1;

                            tone.aOp[1].WS = (byte)((idata[11]) & 0x07);

                            tone.CNT = (byte)((idata[6]) & 0x01);
                            tone.FB  = (byte)((idata[6] >> 1) & 0x07);

                            tones.Add(tone);
                        }
                    }
                }
                break;

                default:
                    return(base.ImportToneFile(fileName));
                }
            }
            catch (Exception ex)
            {
                if (ex.GetType() == typeof(Exception))
                {
                    throw;
                }
                else if (ex.GetType() == typeof(SystemException))
                {
                    throw;
                }

                MessageBox.Show(Resources.FailedLoadFile + "\r\n" + ex.Message);
            }
            return(tones);
        }
Esempio n. 15
0
 public override void LoadState(System.IO.BinaryReader stream)
 {
     base.LoadState(stream);
     prg_mode = stream.ReadBoolean();
     prg_reg0 = stream.ReadByte();
 }
Esempio n. 16
0
        void OnReceive(DebugMessageType type, byte[] buffer)
        {
            if (clientSocket == null || clientSocket.Disconnected)
            {
                return;
            }
            System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer);
            System.IO.BinaryReader br = new System.IO.BinaryReader(ms);

            switch (type)
            {
            case DebugMessageType.CSAttach:
            {
                SendAttachResult();
            }
            break;

            case DebugMessageType.CSBindBreakpoint:
            {
                CSBindBreakpoint msg = new Protocol.CSBindBreakpoint();
                msg.BreakpointHashCode = br.ReadInt32();
                msg.IsLambda           = br.ReadBoolean();
                msg.TypeName           = br.ReadString();
                msg.MethodName         = br.ReadString();
                msg.StartLine          = br.ReadInt32();
                msg.EndLine            = br.ReadInt32();
                TryBindBreakpoint(msg);
            }
            break;

            case DebugMessageType.CSDeleteBreakpoint:
            {
                CSDeleteBreakpoint msg = new Protocol.CSDeleteBreakpoint();
                msg.BreakpointHashCode = br.ReadInt32();
                ds.DeleteBreakpoint(msg.BreakpointHashCode);
            }
            break;

            case DebugMessageType.CSExecute:
            {
                CSExecute msg = new Protocol.CSExecute();
                msg.ThreadHashCode = br.ReadInt32();
                ds.ExecuteThread(msg.ThreadHashCode);
            }
            break;

            case DebugMessageType.CSStep:
            {
                CSStep msg = new CSStep();
                msg.ThreadHashCode = br.ReadInt32();
                msg.StepType       = (StepTypes)br.ReadByte();
                ds.StepThread(msg.ThreadHashCode, msg.StepType);
            }
            break;

            case DebugMessageType.CSResolveVariable:
            {
                CSResolveVariable msg = new CSResolveVariable();
                msg.ThreadHashCode = br.ReadInt32();
                msg.Variable       = ReadVariableReference(br);
                VariableInfo info;
                try
                {
                    object res;
                    info = ds.ResolveVariable(msg.ThreadHashCode, msg.Variable, out res);
                }
                catch (Exception ex)
                {
                    info = VariableInfo.GetException(ex);
                }
                if (info.Type != VariableTypes.Pending)
                {
                    SendSCResolveVariableResult(info);
                }
            }
            break;

            case DebugMessageType.CSResolveIndexAccess:
            {
                CSResolveIndexer msg = new CSResolveIndexer();
                msg.ThreadHashCode = br.ReadInt32();
                msg.Body           = ReadVariableReference(br);
                msg.Index          = ReadVariableReference(br);

                VariableInfo info;
                try
                {
                    object res;
                    info = ds.ResolveIndexAccess(msg.ThreadHashCode, msg.Body, msg.Index, out res);
                }
                catch (Exception ex)
                {
                    info = VariableInfo.GetException(ex);
                }
                if (info.Type != VariableTypes.Pending)
                {
                    SendSCResolveVariableResult(info);
                }
            }
            break;

            case DebugMessageType.CSEnumChildren:
            {
                int thId   = br.ReadInt32();
                var parent = ReadVariableReference(br);

                VariableInfo[] info = null;
                try
                {
                    info = ds.EnumChildren(thId, parent);
                }
                catch (Exception ex)
                {
                    info = new VariableInfo[] { VariableInfo.GetException(ex) };
                }
                if (info != null)
                {
                    SendSCEnumChildrenResult(info);
                }
            }
            break;
            }
        }
Esempio n. 17
0
        public void Load(string filename)
        {
            // Open the file
            System.IO.BinaryReader file = new System.IO.BinaryReader(System.IO.File.Open(filename, System.IO.FileMode.Open));

            // Start loading at LOAD_ADDR
            ushort offset = LOAD_ADDR;

            // Load Byte for Byte
            while (true)
            {
                try
                {
                    memory[offset++] = file.ReadByte();
                }
                catch (System.IO.EndOfStreamException)
                {
                    break;
                }
            }
        }
Esempio n. 18
0
        public void Load(System.IO.BinaryReader br)
        {
            //Read tile definition mapper (oldId -> newId)
            byte[] mapTileDefinitionMapper = new byte[byte.MaxValue];

            int definitions = br.ReadInt32();

            for (int i = 0; i < definitions; i++)
            {
                byte   oldType = br.ReadByte();
                string id      = br.ReadString();
                byte   newType = 0;

                foreach (TileDefinition td in tileDefinitions)
                {
                    if (td.id == id)
                    {
                        newType = td.tileType;
                        break;
                    }
                }

                mapTileDefinitionMapper[oldType] = newType;
            }

            //Read map size
            //This is read in CubeWorld.Load()
            //int sizeXbits = br.ReadInt32();
            //int sizeYbits = br.ReadInt32();
            //int sizeZbits = br.ReadInt32();

            //Create empty world
            //The world is already created in CubeLoad.Load()
            //Create(tileDefinitions, sizeXbits, sizeYbits, sizeZbits);

            //Read tiles
            byte[] tileBytes = br.ReadBytes(sizeX * sizeY * sizeZ * 4);
            Tile   tile      = new Tile();

            for (int n = tiles.Length - 1; n >= 0; n--)
            {
                tile.tileType  = mapTileDefinitionMapper[tileBytes[(n << 2) | 0]];
                tile.luminance = tileBytes[(n << 2) | 1];
                tile.extra     = tileBytes[(n << 2) | 2];
                tile.extra2    = tileBytes[(n << 2) | 3];

                tiles[n] = tile;
            }

            //Read dynamic tiles
            int nDyanamicTiles = br.ReadInt32();

            for (int n = 0; n < nDyanamicTiles; n++)
            {
                int          objectId = br.ReadInt32();
                TilePosition pos      = SerializationUtils.ReadTilePosition(br);
                int          timeout  = br.ReadInt32();

                DynamicTile dynamicTile = new DynamicTile(world, pos, true, objectId);

                //TODO: Get gravity attribute from somewhere
                if (true)
                {
                    dynamicTile.AddComponent(new TileComponentGravity());
                }

                dynamicTiles[pos] = dynamicTile;

                if (timeout > 0)
                {
                    dynamicTile.timeout      = timeout;
                    dynamicTilesTimeout[pos] = dynamicTile;
                }

                world.cwListener.CreateObject(dynamicTile);
            }

            //Read top positions
            topPositions = br.ReadBytes(sizeX * sizeZ);

            if (world.gameplay.useEnqueueTileUpdates)
            {
                EnqueueTilesWithRules();
            }

            enqueueTileUpdates    = world.gameplay.useEnqueueTileUpdates;
            updateLighting        = true;
            reportTileInvalidated = true;

            if (world.gameplay.useEnqueueTileUpdates)
            {
                UpdateTiles();
            }

            //The read tiles already have the light information updated
            //LightModelAmbient.InitLuminance(this);
            //LightModelLightSource.InitLuminance(this);
        }
Esempio n. 19
0
        internal void Unserialize(System.IO.BinaryReader reader)
        {
            contants.Clear();
            functions.Clear();
            codes.Clear();
            srcln.Clear();
            local.Clear();
            upval.Clear();

            name = ObjLua.ReadString(reader);

            linedef = reader.ReadUInt32();
            nups    = reader.ReadByte();
            argc    = reader.ReadByte();
            isinout = reader.ReadByte();
            stacksz = reader.ReadByte();

            uint linenfosz = reader.ReadUInt32();

            for (uint i = 0; i < linenfosz; i++)
            {
                ObjLuaSourceLine item = new ObjLuaSourceLine(this);
                item.Unserialize(reader);

                srcln.Add(item);
            }

            uint locvarsz = reader.ReadUInt32();

            for (uint i = 0; i < locvarsz; i++)
            {
                ObjLuaLocalVar item = new ObjLuaLocalVar(this);
                item.Unserialize(reader);

                local.Add(item);
            }

            uint upvalsz = reader.ReadUInt32();

            for (uint i = 0; i < upvalsz; i++)
            {
                ObjLuaUpValue item = new ObjLuaUpValue(this);
                item.Unserialize(reader);

                upval.Add(item);
            }

            uint constsz = reader.ReadUInt32();

            for (uint i = 0; i < constsz; i++)
            {
                ObjLuaConstant item = new ObjLuaConstant(this);
                item.Unserialize(reader);

                contants.Add(item);
            }

            uint fncsz = reader.ReadUInt32();

            for (uint i = 0; i < fncsz; i++)
            {
                ObjLuaFunction item = new ObjLuaFunction(this.parent);
                item.Unserialize(reader);

                functions.Add(item);
            }

            uint codesz = reader.ReadUInt32();

            for (uint i = 0; i < codesz; i++)
            {
                ObjLuaCode item = ObjLuaCode.Unserialize(reader, this);

                codes.Add(item);
            }
        }
Esempio n. 20
0
        /// <summary>
        /// 获取图片尺寸。
        /// </summary>
        /// <param name="input">图片数据输入流。</param>
        /// <returns>图片尺寸。</returns>
        public static System.Drawing.Size GetImageSize(System.IO.Stream input)
        {
            System.Drawing.Size GetImageSize = new System.Drawing.Size();
            byte[] bTemp = new byte[4];
            long   lFlen;
            long   lPos;
            byte   bHmsb;
            byte   bHlsb;
            byte   bWmsb;
            byte   bWlsb;

            byte[] bBuf  = new byte[8];
            byte   bDone = 0;
            int    iCount;

            System.IO.BinaryReader br = new System.IO.BinaryReader(input);
            lFlen = input.Length;
            //iFN = FreeFile
            //Open sFileName For Binary As iFN
            input.Read(bTemp, 0, bTemp.Length);//Get #iFN, 1, bTemp()

            //PNG file
            if (bTemp[0] == 0x89 && bTemp[1] == 0x50 && bTemp[2] == 0x4E && bTemp[3] == 0x47)
            {
                //Get #iFN, 19, bWmsb
                //Get #iFN, 20, bWlsb
                //Get #iFN, 23, bHmsb
                //Get #iFN, 24, bHlsb
                //GetImageSize.Width = CombineBytes(bWlsb, bWmsb)
                //GetImageSize.Height = CombineBytes(bHlsb, bHmsb)
                input.Seek(18, System.IO.SeekOrigin.Begin);
                bWmsb = br.ReadByte();
                bWlsb = br.ReadByte();
                input.Seek(22, System.IO.SeekOrigin.Begin);
                bHmsb = br.ReadByte();
                bHlsb = br.ReadByte();
                GetImageSize.Width  = CombineBytes(bWlsb, bWmsb);
                GetImageSize.Height = CombineBytes(bHlsb, bHmsb);
            }

            //GIF file
            else if (bTemp[0] == 0x47 && bTemp[1] == 0x49 && bTemp[2] == 0x46 && bTemp[3] == 0x38)
            {
                //Get #iFN, 7, bWlsb
                //Get #iFN, 8, bWmsb
                //Get #iFN, 9, bHlsb
                //Get #iFN, 10, bHmsb
                //GetImageSize.Width = CombineBytes(bWlsb, bWmsb)
                //GetImageSize.Height = CombineBytes(bHlsb, bHmsb)
                input.Seek(6, System.IO.SeekOrigin.Begin);
                bWlsb = br.ReadByte();
                bWmsb = br.ReadByte();
                bHlsb = br.ReadByte();
                bHmsb = br.ReadByte();
                GetImageSize.Width  = CombineBytes(bWlsb, bWmsb);
                GetImageSize.Height = CombineBytes(bHlsb, bHmsb);
            }


            //JPEG file
            else if (bTemp[0] == 0xFF && bTemp[1] == 0xD8 && bTemp[2] == 0xFF)
            {
                //Debug.Print "JPEG"
                //    lPos = 3
                //    Do
                //        Do
                //            Get #iFN, lPos, bBuf(1)
                //            Get #iFN, lPos + 1, bBuf(2)
                //            lPos = lPos + 1
                //        Loop Until (bBuf(1) = 0xFF && bBuf(2) <> 0xFF) Or lPos > lFlen

                //        For iCount = 0 To 7
                //            Get #iFN, lPos + iCount, bBuf(iCount)
                //        Next iCount
                //        If bBuf(0) >= 0xC0 && bBuf(0) <= 0xC3 Then
                //            bHmsb = bBuf(4)
                //            bHlsb = bBuf(5)
                //            bWmsb = bBuf(6)
                //            bWlsb = bBuf(7)
                //            bDone = 1
                //        Else
                //            lPos = lPos + (CombineBytes(bBuf(2), bBuf(1))) + 1
                //        End If
                //    Loop While lPos < lFlen && bDone = 0
                //    GetImageSize.Width = CombineBytes(bWlsb, bWmsb)
                //    GetImageSize.Height = CombineBytes(bHlsb, bHmsb)

                bWlsb = 0;
                bWmsb = 0;
                bHlsb = 0;
                bHmsb = 0;

                lPos = 2;
                do
                {
                    do
                    {
                        input.Seek(lPos, System.IO.SeekOrigin.Begin);
                        bBuf[1] = br.ReadByte();
                        input.Seek(lPos + 1, System.IO.SeekOrigin.Begin);
                        bBuf[2] = br.ReadByte();
                        lPos++;
                    } while ((bBuf[1] == 0xFF && bBuf[2] != 0xFF) == false && lPos < lFlen);

                    for (iCount = 0; iCount < bBuf.Length; iCount++)
                    {
                        input.Seek(lPos + iCount, System.IO.SeekOrigin.Begin);
                        bBuf[iCount] = br.ReadByte();
                    }

                    if (bBuf[0] >= 0xC0 && bBuf[0] <= 0xC3)
                    {
                        bHmsb = bBuf[4];
                        bHlsb = bBuf[5];
                        bWmsb = bBuf[6];
                        bWlsb = bBuf[7];
                        bDone = 1;
                    }
                    else
                    {
                        lPos = lPos + (CombineBytes(bBuf[2], bBuf[1])) + 1;
                    }
                } while (lPos < lFlen && bDone == 0);

                GetImageSize.Width  = CombineBytes(bWlsb, bWmsb);
                GetImageSize.Height = CombineBytes(bHlsb, bHmsb);
            }

            //BMP 文件
            else if (bTemp[0] == 0x42 && bTemp[1] == 0x4D)
            {
                //Get #iFN, 19, bWlsb
                //Get #iFN, 20, bWmsb
                //Get #iFN, 23, bHlsb
                //Get #iFN, 24, bHmsb
                //GetImageSize.Width = CombineBytes(bWlsb, bWmsb)
                //GetImageSize.Height = CombineBytes(bHlsb, bHmsb)
                input.Seek(18, System.IO.SeekOrigin.Begin);
                bWmsb = br.ReadByte();
                bWlsb = br.ReadByte();
                input.Seek(22, System.IO.SeekOrigin.Begin);
                bHmsb = br.ReadByte();
                bHlsb = br.ReadByte();
                GetImageSize.Width  = CombineBytes(bWmsb, bWlsb);
                GetImageSize.Height = CombineBytes(bHmsb, bHlsb);
            }
            else
            {
                input.Seek(0, System.IO.SeekOrigin.Begin);
                System.Drawing.Image img = System.Drawing.Bitmap.FromStream(input);
                GetImageSize = img.Size;
            }
            return(GetImageSize);
        }
Esempio n. 21
0
        private void OpenFile(string filename)
        {
#if !DEBUG
            try
            {
#endif
            _filename = filename;
            fileIn    = new System.IO.BinaryReader(System.IO.File.Open(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read));

            string startFileSig = "";
            for (int i = 0; i < 4; i++)     // 4 bytes
            {
                startFileSig += fileIn.ReadChar();
            }
            if (startFileSig != "#PES")
            {
                // This is not a file that we can read
                readyStatus = statusEnum.ParseError;
                lastError   = "Missing #PES at beginning of file";
                fileIn.Close();
                return;
            }

            // PES version
            string versionString = "";
            for (int i = 0; i < 4; i++)     // 4 bytes
            {
                versionString += fileIn.ReadChar();
            }
            pesVersion = Convert.ToUInt16(versionString);

            int pecstart = fileIn.ReadInt32();

            // Read number of colors in this design
            fileIn.BaseStream.Position = pecstart + 48;
            int numColors         = fileIn.ReadByte() + 1;
            List <byte> colorList = new List <byte>();
            for (int x = 0; x < numColors; x++)
            {
                colorList.Add(fileIn.ReadByte());
            }

            // Read stitch data
            fileIn.BaseStream.Position = pecstart + 532;
            bool thisPartIsDone = false;
            StitchBlock curBlock;
            int prevX                  = 0;
            int prevY                  = 0;
            int maxX                   = 0;
            int minX                   = 0;
            int maxY                   = 0;
            int minY                   = 0;
            int colorNum               = -1;
            int colorIndex             = 0;
            List <Stitch> tempStitches = new List <Stitch>();
            while (!thisPartIsDone)
            {
                byte val1;
                byte val2;
                val1 = fileIn.ReadByte();
                val2 = fileIn.ReadByte();
                if (val1 == 0xff && val2 == 0x00)
                {
                    //end of stitches
                    thisPartIsDone = true;

                    //add the last block
                    curBlock          = new StitchBlock();
                    curBlock.stitches = new Stitch[tempStitches.Count];
                    tempStitches.CopyTo(curBlock.stitches);
                    curBlock.stitchesTotal = tempStitches.Count;
                    colorNum++;
                    colorIndex          = colorList[colorNum];
                    curBlock.colorIndex = colorIndex;
                    curBlock.color      = getColorFromIndex(colorIndex);
                    blocks.Add(curBlock);
                }
                else if (val1 == 0xfe && val2 == 0xb0)
                {
                    //color switch, start a new block

                    curBlock          = new StitchBlock();
                    curBlock.stitches = new Stitch[tempStitches.Count];
                    tempStitches.CopyTo(curBlock.stitches);
                    curBlock.stitchesTotal = tempStitches.Count;
                    colorNum++;
                    colorIndex          = colorList[colorNum];
                    curBlock.colorIndex = colorIndex;
                    curBlock.color      = getColorFromIndex(colorIndex);
                    //read useless(?) byte
                    // The value of this 'useless' byte seems to alternate
                    // between 2 and 1 for every other block. The only
                    // exception I've noted is the last block which appears
                    // to always be 0.
                    curBlock.unknownStartByte = fileIn.ReadByte();
                    blocks.Add(curBlock);

                    tempStitches = new List <Stitch>();
                }
                else
                {
                    int deltaX = 0;
                    int deltaY = 0;
                    if ((val1 & 0x80) == 0x80)
                    {
                        // This is a 12-bit int. Allows for needle movement
                        // of up to +2047 or -2048.
                        deltaX = get12Bit2sComplement(val1, val2);

                        // The X value used both bytes, so read next byte
                        // for Y value.
                        val1 = fileIn.ReadByte();
                    }
                    else
                    {
                        // This is a 7-bit int. Allows for needle movement
                        // of up to +63 or -64.
                        deltaX = get7Bit2sComplement(val1);

                        // The X value only used 1 byte, so copy the second
                        // to to the first for Y value.
                        val1 = val2;
                    }

                    if ((val1 & 0x80) == 0x80)
                    {
                        // This is a 12-bit int. Allows for needle movement
                        // of up to +2047 or -2048.
                        // Read in the next byte to get the full value
                        val2   = fileIn.ReadByte();
                        deltaY = get12Bit2sComplement(val1, val2);
                    }
                    else
                    {
                        // This is a 7-bit int. Allows for needle movement
                        // of up to +63 or -64.
                        deltaY = get7Bit2sComplement(val1);
                        // Finished reading data for this stitch, no more
                        // bytes needed.
                    }
                    tempStitches.Add(
                        new Stitch(
                            new Point(prevX, prevY),
                            new Point(prevX + deltaX, prevY + deltaY)
                            )
                        );
                    prevX = prevX + deltaX;
                    prevY = prevY + deltaY;
                    if (prevX > maxX)
                    {
                        maxX = prevX;
                    }
                    else if (prevX < minX)
                    {
                        minX = prevX;
                    }

                    if (prevY > maxY)
                    {
                        maxY = prevY;
                    }
                    else if (prevY < minY)
                    {
                        minY = prevY;
                    }
                }
            }
            imageWidth       = maxX - minX;
            imageHeight      = maxY - minY;
            translateStart.X = -minX;
            translateStart.Y = -minY;
            readyStatus      = statusEnum.Ready;

            // Close the file
            fileIn.Close();

#if !DEBUG
        }

        catch (System.IO.IOException ioex)
        {
            readyStatus = statusEnum.IOError;
            lastError   = ioex.Message;
            if (fileIn != null)
            {
                fileIn.Close();
            }
        }
        catch (Exception ex)
        {
            readyStatus = statusEnum.ParseError;
            lastError   = ex.Message;
            if (fileIn != null)
            {
                fileIn.Close();
            }
        }
#endif
        }
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();

            //Alimenta a variável das datas
            dataInicio = dateTimePickerInicio.Value.ToString("dd-MM-yyyy");
            dataFinal = dateTimePickerFinal.Value.ToString("dd-MM-yyyy");

            SqlConnection conn = new ConnectionFactory().getConnection();

            SqlCommand cmd = new SqlCommand(@"select distinct(codpromotor) as codpromotor from movpromotores
                                              where data between @dataini and @datafim", conn);

            cmd.Parameters.AddWithValue("@dataini", dateTimePickerInicio.Value);
            cmd.Parameters.AddWithValue("@datafim", dateTimePickerFinal.Value);

            try
            {
                cxTotal.Text = getQuantidade().ToString();

                SqlDataReader reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    ReportDocument rpDocument =
                            new CarregaRelatorio().carregarRelatorio(montaQuery(reader["codpromotor"].ToString()), "T:\\rel\\relatorioDisparo.rpt");

                   //Cria um stream do pdf
                   System.IO.Stream st =
                       rpDocument.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);

                    //Faz a leitura do stream para byte
                   System.IO.BinaryReader br = new System.IO.BinaryReader(st);

                   byte[] pdfByte = new byte[st.Length];

                   for (int i = 0; i < st.Length; ++i)
                   {
                       pdfByte[i] = br.ReadByte();
                   }

                    //Fecha o stream e o byte reader
                   st.Close();
                   br.Close();

                   //Grava o email na fila de envio
                   if (gravaLogEMail(reader["codpromotor"].ToString(), pdfByte))
                   {
                       listBox1.Items.Add("Promotor "+ reader["codpromotor"].ToString() + " -> Gerou com sucesso!");
                   }
                   else
                   {
                       listBox1.Items.Add("Promotor " + reader["codpromotor"].ToString() + " -> Falha ao gerar");
                   }

                   listBox1.SelectedIndex = listBox1.Items.Count-1;

                   quantidade.Text = (listBox1.Items.Count).ToString();

                   if (listBox1.Items.Count == Convert.ToInt64(cxTotal.Text))
                       MessageBox.Show("O processo foi finalizado com sucesso!");

                   rpDocument.Close();

                    Application.DoEvents();

                }

                reader.Close();
            }catch(Exception exc)
            {
                MessageBox.Show("Erro ao gerar relatório\n"+ exc);
            }
            finally
            {
                conn.Close();
            }
        }
Esempio n. 23
0
        internal bool Run(string uuid, string mode)
        {
            bool run = false;
            XcDiagProcessInfo xcdiagProcessInfo = GetXcDiagProcessInfo(mode);

            if (xcdiagProcessInfo != null) // If got xcdiag process info
            {
                this.log.Info("Received xcdiag request");
                xcdiagProcessInfo.processStartInfo.CreateNoWindow = true;
                xcdiagProcessInfo.processStartInfo.ErrorDialog = false;
                xcdiagProcessInfo.processStartInfo.RedirectStandardError = true;
                xcdiagProcessInfo.processStartInfo.RedirectStandardOutput = true;
                xcdiagProcessInfo.processStartInfo.UseShellExecute = false;
                xcdiagProcessInfo.processStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

                System.Diagnostics.Process xcdiagProcess = null;
                try
                {
                    xcdiagProcess = System.Diagnostics.Process.Start(xcdiagProcessInfo.processStartInfo);
                    if (xcdiagProcess == null)
                    {
                        log.Info("xcdiag process already running in: \"{0}\"", xcdiagProcessInfo.processStartInfo.FileName);
                    }
                }
                catch (System.IO.FileNotFoundException filenotfoundEx)
                {
                    log.Exception("Cannot launch xcdiag (file not found)", filenotfoundEx);
                }
                catch (System.ObjectDisposedException objdisposedEx)
                {
                    log.Exception("Cannot launch xcdiag (object disposed)", objdisposedEx);
                }
                catch (System.InvalidOperationException invalidopEx)
                {
                    log.Exception("Cannot launch xcdiag (invalid operation)", invalidopEx);
                }
                catch (System.ComponentModel.Win32Exception win32Ex)
                {
                    log.Exception("Cannot launch xcdiag (win32 error)", win32Ex);
                }
                catch (System.Exception ex)
                {
                    log.Exception("Cannot launch xcdiag", ex);
                }

                if (xcdiagProcess != null) // If launched xcdiag
                {
                    // Tends to block until process finishes.
                    string xcdiagError = xcdiagProcess.StandardError.ReadToEnd();
                    if (!string.IsNullOrEmpty(xcdiagError))
                    {
                        log.Error("xcdiag produced error output: {0}", xcdiagError);
                    }

                    xcdiagProcess.WaitForExit(); // Oooooh.

                    if (xcdiagProcess.ExitCode != 0) // If xcdiag reported an error
                    {
                        log.Error("xcdiag exited with error code '{0}'", xcdiagProcess.ExitCode);

                    } // Ends if xcdiag reported an error
                    else // else xcdiag ran ok
                    {
                        System.Text.StringBuilder dataBuffer = null;
                        // Make a big ol' string containing the data, encoding each byte as 2-digit ASCII hex.
            #if MEMORYMAPFILE_SUPPORTED
                        using(System.IO.MemoryMappedFiles.MemoryMappedFile memmapXcDiag = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateFromFile(xcdiagProcessInfo.xcDiagOutputPath))
            #else // !MEMORYMAPFILE_SUPPORTED
                        //// Create a memory mapped view of the zip file
                        //hFile = CreateFileA(szXcDiagOut,
                        //    GENERIC_READ | GENERIC_WRITE,
                        //    0,
                        //    NULL,
                        //    OPEN_EXISTING,
                        //    FILE_ATTRIBUTE_NORMAL,
                        //    NULL);
                        using (Microsoft.Win32.SafeHandles.SafeFileHandle mapHandle = wcf.Native.FileFunctions.CreateFile(xcdiagProcessInfo.xcDiagOutputPath
                            , global::XenClientGuestService.Native.EFileAccess.FILE_GENERIC_READ | global::XenClientGuestService.Native.EFileAccess.FILE_GENERIC_WRITE
                            , System.IO.FileShare.None
                            , IntPtr.Zero
                            , System.IO.FileMode.Open
                            , System.IO.FileAttributes.Normal
                            , IntPtr.Zero))
            #endif // MEMORYMAPFILE_SUPPORTED
                        {
                            // Finish creating the native mapping, and then work out how to read bytes...
            #if MEMORYMAPFILE_SUPPORTED
                            using (System.IO.MemoryMappedFiles.MemoryMappedViewStream streamXcDiag = memmapXcDiag.CreateViewStream())
            #else // !MEMORYMAPFILE_SUPPORTED
                            long fileSize = new System.IO.FileInfo(xcdiagProcessInfo.xcDiagOutputPath).Length;
                            //hMapFile = CreateFileMapping(
                            //    hFile,          // current file handle
                            //    NULL,           // default security
                            //    PAGE_READWRITE, // read/write permission
                            //    0,              // size of mapping object, high
                            //    filesize,       // size of mapping object, low
                            //    NULL);          // name of mapping object
                            using (Microsoft.Win32.SafeHandles.SafeFileHandle xcDiagOutputMappingHandle = wcf.Native.MappingFunctions.CreateFileMapping(mapHandle
                                    , IntPtr.Zero
                                    , global::XenClientGuestService.Native.FileMapProtection.PageReadWrite
                                    , 0
                                    , checked((uint)fileSize)
                                    , null))
            #endif // MEMORYMAPFILE_SUPPORTED
                            {
            #if MEMORYMAPFILE_SUPPORTED
                                long fileSize = streamXcDiag.Length;
            #else // !MEMORYMAPFILE_SUPPORTED
                                //// Map the view
                                //lpMapAddress = (unsigned char *)MapViewOfFile(
                                //    hMapFile,			 // handle to mapping object
                                //    FILE_MAP_ALL_ACCESS, // read/write
                                //    0,                   // high-order 32 bits of file offset
                                //    0,                   // low-order 32 bits of file offset
                                //    filesize);           // number of bytes to map
                                using (wcf.Native.FileMappingViewHandle mappingViewHandler = wcf.Native.MappingFunctions.MapViewOfFile(xcDiagOutputMappingHandle
                                    , global::XenClientGuestService.Native.FileMapAccess.FileMapAllAccess
                                    , 0
                                    , 0
                                    , (checked((UInt32)fileSize))))
            #endif // !MEMORYMAPFILE_SUPPORTED
                                {
            #if MEMORYMAPFILE_SUPPORTED
                                    System.IO.BinaryReader reader = new System.IO.BinaryReader(streamXcDiag);
            #else // !MEMORYMAPFILE_SUPPORTED
                                    wcf.Native.FileMappingViewHandle.ViewReader reader = mappingViewHandler.CreateViewReader();
            #endif // !MEMORYMAPFILE_SUPPORTED
                                    int resultSize = checked((int)(fileSize * 2));
                                    dataBuffer = new StringBuilder(resultSize, resultSize);
                                    for (int byteIter = 0; byteIter < fileSize; ++byteIter)
                                    {
                                        byte b = reader.ReadByte();
                                        dataBuffer.Append(b.ToString("x2"));

                                    } // Ends loop over bytes
                                } // Ends using map view handle
                            } // Ends using Memory Map view
                        } // Ends using Memory Map file

                        string data = dataBuffer.ToString();
                        byte[] stringBytes = System.Text.Encoding.Default.GetBytes(data);
                        byte[] asciiBytes = System.Text.ASCIIEncoding.Convert(Encoding.Default, Encoding.ASCII, stringBytes);
                        data = System.Text.Encoding.ASCII.GetString(asciiBytes);
                        Gather(uuid, data);

                    } // Ends else xcdiag ran ok
                } // Ends if launched xcdiag
            } // Ends if got xcdiag process info

            return run;
        }
Esempio n. 24
0
 /// <summary>
 /// 真正判断文件类型的关键函数(不太准确,比如txt获取到的值都不一样)
 /// </summary>
 /// <param name="hifile"></param>
 /// <returns></returns>
 public static string GetFileTrueType(System.Web.HttpPostedFile postedFile)
 {
     //System.IO.FileStream fs = new System.IO.FileStream(strPhysicsPath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
     System.IO.Stream fs = postedFile.InputStream;
     System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
     string fileclass = "";
     byte buffer;
     try
     {
         buffer = r.ReadByte();
         fileclass = buffer.ToString();
         buffer = r.ReadByte();
         fileclass += buffer.ToString();
     }
     catch { }
     r.Close();
     fs.Close();
     /*文件扩展名说明
      *7173        gif
      *255216      jpg
      *13780       png
      *6677        bmp
      *239187      txt,aspx,asp,sql
      *208207      xls.doc.ppt
      *6063        xml
      *6033        htm,html
      *4742        js
      *8075        xlsx,zip,pptx,mmap,zip
      *8297        rar
      *01          accdb,mdb
      *7790        exe,dll
      *5666        psd
      *255254      rdp
      *10056       bt种子
      *64101       bat
      */
     if (fileclass == "255216")//说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
     {
         return "jpg";
     }
     else if (fileclass == "7173")
     {
         return "gif";
     }
     else if (fileclass == "6677")
     {
         return "bmp";
     }
     else if (fileclass == "13780")
     {
         return "png";
     }
     else if (fileclass == "7790")
     {
         return "exe";
     }
     else if (fileclass == "8297")
     {
         return "rar/zip";
     }
     else if (fileclass == "208207")
     {
         return "doc/xls";
     }
     else if (fileclass == "8075")
     {
         return "docx/xlsx";
     }
     else if (fileclass == "5155")
     {
         return "txt";
     }
     else if (fileclass == "6787")
     {
         return "swf";
     }
     else
     {
         return "";
     }
 }
Esempio n. 25
0
        public void readFile()
        {
            System.IO.BinaryReader sr;

            try { //TODO: test, rather than try/fail?
                sr = new System.IO.BinaryReader(System.IO.File.Open(path, System.IO.FileMode.Open));
            } catch (System.IO.IOException) {
                throw;
            }

            //====================
            //RIFF chunk id
            char[] ckID = sr.ReadChars(4);
            String a    = new string(ckID);

            if (a.CompareTo("RIFF") != 0)
            {
                throw new FormatException("RIFF chunkID missing. Found " + ckID[0] + ckID[1] + ckID[2] + ckID[3] + ".");
            }

            UInt32 RIFFSize = sr.ReadUInt32();

            //====================
            //WAVE chunk id
            ckID = sr.ReadChars(4);
            a    = new string(ckID);
            if (a.CompareTo("WAVE") != 0)
            {
                throw new FormatException("WAVE chunkID missing. Found " + ckID[0] + ckID[1] + ckID[2] + ckID[3] + ".");
            }

            //====================
            //fmt_ chunk id
            ckID = sr.ReadChars(4);
            a    = new string(ckID);
            UInt32 chunkSize = sr.ReadUInt32();

            while (a.CompareTo("fmt ") != 0)
            {
                sr.ReadBytes((int)chunkSize);
                ckID      = sr.ReadChars(4);
                a         = new string(ckID);
                chunkSize = sr.ReadUInt32();
            }
            Int16 wFormatTag      = sr.ReadInt16();
            Int16 nChannels       = sr.ReadInt16();
            Int32 nSamplesPerSec  = sr.ReadInt32();
            Int32 nAvgBytesPerSec = sr.ReadInt32();
            Int16 nBlockAlign     = sr.ReadInt16();
            Int16 wBitsPerSample  = sr.ReadInt16();

            chunkSize -= 16;
            //there may be more bytes in fmt_ so skip those.
            sr.ReadBytes((int)chunkSize);

            if (wFormatTag != 0x0001)
            {
                throw new FormatException("Invalid wave format. Only PCM wave files supported.");
            }

            //====================
            //data chunk id
            ckID      = sr.ReadChars(4);
            a         = new string(ckID);
            chunkSize = sr.ReadUInt32();
            while (a.CompareTo("data") != 0)
            {
                sr.ReadBytes((int)chunkSize);
                ckID      = sr.ReadChars(4);
                a         = new string(ckID);
                chunkSize = sr.ReadUInt32();
            }

            channels   = (short)nChannels;
            bitDepth   = (short)wBitsPerSample;
            sampleRate = nSamplesPerSec;
            long numSamples = chunkSize / (bitDepth / 8) / channels;

            samples = new double[channels][];
            for (int c = 0; c < channels; c++)
            {
                samples[c] = new double[numSamples];
            }

            //======================
            // read samples
            if (bitDepth == 16)
            {
                for (int i = 0; i < numSamples; i++)
                {
                    for (int c = 0; c < channels; c++)
                    {
                        //assuming signed
                        //normalized to -1.0..+1.0
                        samples[c][i] = (double)sr.ReadInt16() / 32768.0;
                    }
                }
            }
            else if (bitDepth == 8)
            {
                for (int i = 0; i < numSamples; i++)
                {
                    for (int c = 0; c < channels; c++)
                    {
                        //assuming unsigned
                        //normalized to -1.0..+1.0
                        samples[c][i] = (double)sr.ReadByte() / 128.0 - 1.0;
                    }
                }
            }
            else
            {
                throw new FormatException("Bit depth must be one of 8 or 16 bits.");
            }
            sr.Close();
        }
Esempio n. 26
0
        protected override void DataUpdate()
        {
            System.IO.BinaryReader BSReader = new System.IO.BinaryReader(ByteStream);
            ByteStream.Position = 0;
            SubModels           = BSReader.ReadInt32();
            SubModel            = new _SubModel[SubModels];

            for (int i = 0; i < SubModels; i++)
            {
                _SubModel withBlock = SubModel[i];
                withBlock.Vertexes  = BSReader.ReadInt32();
                withBlock.BlockSize = BSReader.ReadUInt32();
                withBlock.k         = BSReader.ReadUInt16();
                withBlock.c         = BSReader.ReadUInt16();
                int cnt, offset;
                cnt                 = 0;
                offset              = (int)ByteStream.Position;
                withBlock.Null1     = BSReader.ReadUInt32();
                withBlock.Something = BSReader.ReadUInt32();
                withBlock.Null2     = BSReader.ReadUInt32();
                while ((cnt < withBlock.Vertexes) && (ByteStream.Position < offset + withBlock.BlockSize))
                {
                    var withBlock1 = new _Group();
                    Array.Resize(ref withBlock1.UV, 0);
                    Array.Resize(ref withBlock1.Shit, 0);
                    withBlock1.SomeNum1 = BSReader.ReadUInt32();
                    withBlock1.Vertexes = BSReader.ReadByte();
                    cnt += withBlock1.Vertexes;
                    withBlock1.Some80h    = BSReader.ReadByte();
                    withBlock1.Null1      = BSReader.ReadUInt16();
                    withBlock1.SomeNum2   = BSReader.ReadUInt32();
                    withBlock1.SomeNum3   = BSReader.ReadUInt32();
                    withBlock1.Null2      = BSReader.ReadUInt32();
                    withBlock1.Signature1 = BSReader.ReadUInt32();
                    withBlock1.SomeShit1  = BSReader.ReadUInt32();
                    withBlock1.SomeShit2  = BSReader.ReadUInt32();
                    withBlock1.SomeShit3  = BSReader.ReadUInt32();
                    withBlock1.Signature2 = BSReader.ReadUInt32();
                    uint head = BSReader.ReadUInt32();
                    while (head != 335544320)
                    {
                        switch (head & 255)
                        {
                        case 3:
                        {
                            withBlock1.VertHead = head;
                            withBlock1.Vertex   = new Position3[withBlock1.Vertexes];
                            for (int j = 0; j <= withBlock1.Vertexes - 1; j++)
                            {
                                withBlock1.Vertex[j].X = BSReader.ReadSingle();
                                withBlock1.Vertex[j].Y = BSReader.ReadSingle();
                                withBlock1.Vertex[j].Z = BSReader.ReadSingle();
                            }

                            break;
                        }

                        case 4:
                        {
                            withBlock1.WeightHead = head;
                            withBlock1.Weight     = new _Weight[withBlock1.Vertexes];
                            for (int j = 0; j <= withBlock1.Vertexes - 1; j++)
                            {
                                withBlock1.Weight[j].X        = BSReader.ReadSingle();
                                withBlock1.Weight[j].Y        = BSReader.ReadSingle();
                                withBlock1.Weight[j].Z        = BSReader.ReadSingle();
                                withBlock1.Weight[j].SomeByte = BSReader.ReadByte();
                                withBlock1.Weight[j].CONN     = BSReader.ReadByte();
                                withBlock1.Weight[j].Null1    = BSReader.ReadUInt16();
                            }

                            break;
                        }

                        case 5:
                        {
                            withBlock1.UVHead = head;
                            withBlock1.UV     = new Position3[withBlock1.Vertexes];
                            for (int j = 0; j <= withBlock1.Vertexes - 1; j++)
                            {
                                withBlock1.UV[j].X = BSReader.ReadSingle();
                                withBlock1.UV[j].Y = BSReader.ReadSingle();
                                withBlock1.UV[j].Z = BSReader.ReadSingle();
                            }

                            break;
                        }

                        case 6:
                        {
                            withBlock1.ShiteHead = head;
                            withBlock1.Shit      = new uint[withBlock1.Vertexes];
                            for (int j = 0; j <= withBlock1.Vertexes - 1; j++)
                            {
                                withBlock1.Shit[j] = BSReader.ReadUInt32();
                            }
                            break;
                        }
                        }
                        head = BSReader.ReadUInt32();
                    }
                    withBlock1.EndSignature1 = head;
                    withBlock1.EndSignature2 = BSReader.ReadUInt32();
                    withBlock1.leftovers     = new byte[] { };
                    _Groups.Add(withBlock1);
                }
                withBlock.Group = _Groups.ToArray();
                Array.Resize(ref withBlock.Group[withBlock.Group.Length - 1].leftovers, (int)(withBlock.BlockSize + offset - ByteStream.Position));
                withBlock.Group[withBlock.Group.Length - 1].leftovers = BSReader.ReadBytes((int)(withBlock.BlockSize + offset - ByteStream.Position));

                SubModel[i] = withBlock;
            }
            _Groups.Clear();
        }
Esempio n. 27
0
        private void OpenFile(string filename)
        {
            #if !DEBUG
            try
            {
            #endif
                _filename = filename;
                fileIn = new System.IO.BinaryReader(System.IO.File.Open(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read));

                string startFileSig = "";
                for (int i = 0; i < 4; i++) // 4 bytes
                {
                    startFileSig += fileIn.ReadChar();
                }
                if (startFileSig != "#PES")
                {
                    // This is not a file that we can read
                    readyStatus = statusEnum.ParseError;
                    lastError = "Missing #PES at beginning of file";
                    fileIn.Close();
                    return;
                }

                // PES version
                string versionString = "";
                for (int i = 0; i < 4; i++) // 4 bytes
                {
                    versionString += fileIn.ReadChar();
                }
                pesVersion = Convert.ToUInt16(versionString);

                int pecstart = fileIn.ReadInt32();

                // Read number of colors in this design
                fileIn.BaseStream.Position = pecstart + 48;
                int numColors = fileIn.ReadByte() +1;
                List<byte> colorList = new List<byte>();
                for (int x = 0; x < numColors; x++)
                {
                    colorList.Add(fileIn.ReadByte());
                }

                // Read stitch data
                fileIn.BaseStream.Position = pecstart + 532;
                bool thisPartIsDone = false;
                StitchBlock curBlock;
                int prevX = 0;
                int prevY = 0;
                int maxX = 0;
                int minX = 0;
                int maxY = 0;
                int minY = 0;
                int colorNum = -1;
                int colorIndex = 0;
                List<Stitch> tempStitches = new List<Stitch>();
                while (!thisPartIsDone)
                {
                    byte val1;
                    byte val2;
                    val1 = fileIn.ReadByte();
                    val2 = fileIn.ReadByte();
                    if (val1 == 0xff && val2 == 0x00)
                    {
                        //end of stitches
                        thisPartIsDone = true;

                        //add the last block
                        curBlock = new StitchBlock();
                        curBlock.stitches = new Stitch[tempStitches.Count];
                        tempStitches.CopyTo(curBlock.stitches);
                        curBlock.stitchesTotal = tempStitches.Count;
                        colorNum++;
                        colorIndex = colorList[colorNum];
                        curBlock.colorIndex = colorIndex;
                        curBlock.color = getColorFromIndex(colorIndex);
                        blocks.Add(curBlock);
                    }
                    else if (val1 == 0xfe && val2 == 0xb0)
                    {
                        //color switch, start a new block

                        curBlock = new StitchBlock();
                        curBlock.stitches = new Stitch[tempStitches.Count];
                        tempStitches.CopyTo(curBlock.stitches);
                        curBlock.stitchesTotal = tempStitches.Count;
                        colorNum++;
                        colorIndex = colorList[colorNum];
                        curBlock.colorIndex = colorIndex;
                        curBlock.color = getColorFromIndex(colorIndex);
                        //read useless(?) byte
                        // The value of this 'useless' byte seems to alternate
                        // between 2 and 1 for every other block. The only
                        // exception I've noted is the last block which appears
                        // to always be 0.
                        curBlock.unknownStartByte = fileIn.ReadByte();
                        blocks.Add(curBlock);

                        tempStitches = new List<Stitch>();
                    }
                    else
                    {
                        int deltaX = 0;
                        int deltaY = 0;
                        if ((val1 & 0x80) == 0x80)
                        {
                            // This is a 12-bit int. Allows for needle movement
                            // of up to +2047 or -2048.
                            deltaX = get12Bit2sComplement(val1, val2);

                            // The X value used both bytes, so read next byte
                            // for Y value.
                            val1 = fileIn.ReadByte();
                        }
                        else
                        {
                            // This is a 7-bit int. Allows for needle movement
                            // of up to +63 or -64.
                            deltaX = get7Bit2sComplement(val1);

                            // The X value only used 1 byte, so copy the second
                            // to to the first for Y value.
                            val1 = val2;
                        }

                        if ((val1 & 0x80) == 0x80)
                        {
                            // This is a 12-bit int. Allows for needle movement
                            // of up to +2047 or -2048.
                            // Read in the next byte to get the full value
                            val2 = fileIn.ReadByte();
                            deltaY = get12Bit2sComplement(val1, val2);
                        }
                        else
                        {
                            // This is a 7-bit int. Allows for needle movement
                            // of up to +63 or -64.
                            deltaY = get7Bit2sComplement(val1);
                            // Finished reading data for this stitch, no more
                            // bytes needed.
                        }
                        tempStitches.Add(
                            new Stitch(
                                new Point(prevX, prevY),
                                new Point(prevX + deltaX, prevY + deltaY)
                            )
                        );
                        prevX = prevX + deltaX;
                        prevY = prevY + deltaY;
                        if (prevX > maxX)
                        {
                            maxX = prevX;
                        }
                        else if (prevX < minX)
                        {
                            minX = prevX;
                        }

                        if (prevY > maxY)
                        {
                            maxY = prevY;
                        }
                        else if (prevY < minY)
                        {
                            minY = prevY;
                        }
                    }
                }
                imageWidth = maxX - minX;
                imageHeight = maxY - minY;
                translateStart.X = -minX;
                translateStart.Y = -minY;
                readyStatus = statusEnum.Ready;

                // Close the file
                fileIn.Close();

            #if !DEBUG
            }
            catch (System.IO.IOException ioex)
            {
                readyStatus = statusEnum.IOError;
                lastError = ioex.Message;
                if (fileIn != null)
                {
                    fileIn.Close();
                }
            }
            catch (Exception ex)
            {
                readyStatus = statusEnum.ParseError;
                lastError = ex.Message;
                if (fileIn != null)
                {
                    fileIn.Close();
                }
            }
            #endif
        }
Esempio n. 28
0
 public override void LoadState(System.IO.BinaryReader stream)
 {
     base.LoadState(stream);
     latch = stream.ReadInt32();
     menu  = stream.ReadByte();
 }
 public Ole10Native(System.IO.Stream inputStream)
 {
     System.IO.BinaryReader reader = new System.IO.BinaryReader(inputStream);
     totalSize = reader.ReadInt32();
     if (totalSize < 4)
     {
         throw new Exception(
                 String.Format("Invalid total data size: {0}.", totalSize));
     }
     flags1 = reader.ReadInt16();
     label = ReadString(reader);
     fileName = ReadString(reader);
     flags2 = reader.ReadInt16();
     byte unknown1Len = reader.ReadByte();
     unknown1 = reader.ReadBytes(unknown1Len);
     unknown2 = reader.ReadBytes(3);
     command = ReadString(reader);
     nativeDataSize = reader.ReadInt32();
     if (nativeDataSize > totalSize || nativeDataSize < 0)
     {
         throw new Exception(
                 String.Format("Invalid native data size: {0}.", nativeDataSize));
     }
     nativeData = reader.ReadBytes(nativeDataSize);
     unknown3 = unknown1.Length > 0 ? reader.ReadInt16() : (short)0;
 }
Esempio n. 30
0
        /// <summary>
        /// Get a cryptographic service for encrypting data using the server's RSA public key
        /// </summary>
        /// <param name="key">Byte array containing the encoded key</param>
        /// <returns>Returns the corresponding RSA Crypto Service</returns>
        public static RSACryptoServiceProvider DecodeRSAPublicKey(byte[] x509key)
        {
            /* Code from StackOverflow no. 18091460 */

            byte[] SeqOID = { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01 };

            System.IO.MemoryStream ms = new System.IO.MemoryStream(x509key);
            System.IO.BinaryReader reader = new System.IO.BinaryReader(ms);

            if (reader.ReadByte() == 0x30)
                ReadASNLength(reader); //skip the size
            else
                return null;

            int identifierSize = 0; //total length of Object Identifier section
            if (reader.ReadByte() == 0x30)
                identifierSize = ReadASNLength(reader);
            else
                return null;

            if (reader.ReadByte() == 0x06) //is the next element an object identifier?
            {
                int oidLength = ReadASNLength(reader);
                byte[] oidBytes = new byte[oidLength];
                reader.Read(oidBytes, 0, oidBytes.Length);
                if (oidBytes.SequenceEqual(SeqOID) == false) //is the object identifier rsaEncryption PKCS#1?
                    return null;

                int remainingBytes = identifierSize - 2 - oidBytes.Length;
                reader.ReadBytes(remainingBytes);
            }

            if (reader.ReadByte() == 0x03) //is the next element a bit string?
            {
                ReadASNLength(reader); //skip the size
                reader.ReadByte(); //skip unused bits indicator
                if (reader.ReadByte() == 0x30)
                {
                    ReadASNLength(reader); //skip the size
                    if (reader.ReadByte() == 0x02) //is it an integer?
                    {
                        int modulusSize = ReadASNLength(reader);
                        byte[] modulus = new byte[modulusSize];
                        reader.Read(modulus, 0, modulus.Length);
                        if (modulus[0] == 0x00) //strip off the first byte if it's 0
                        {
                            byte[] tempModulus = new byte[modulus.Length - 1];
                            Array.Copy(modulus, 1, tempModulus, 0, modulus.Length - 1);
                            modulus = tempModulus;
                        }

                        if (reader.ReadByte() == 0x02) //is it an integer?
                        {
                            int exponentSize = ReadASNLength(reader);
                            byte[] exponent = new byte[exponentSize];
                            reader.Read(exponent, 0, exponent.Length);

                            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                            RSAParameters RSAKeyInfo = new RSAParameters();
                            RSAKeyInfo.Modulus = modulus;
                            RSAKeyInfo.Exponent = exponent;
                            RSA.ImportParameters(RSAKeyInfo);
                            return RSA;
                        }
                    }
                }
            }
            return null;
        }
        public override void Load(System.IO.BinaryReader br, bool loadByteArray)
        {
            long position = br.BaseStream.Position;

            base.Load(br, loadByteArray);
            byte first  = br.ReadByte();
            byte second = br.ReadByte();
            bool isGeom = true;

            for (int i = 0; i < 3; i++)
            {
                byte checkByte = br.ReadByte();
                if (checkByte != 0)
                {
                    isGeom = false;
                    break;
                }
            }

            if (isGeom)
            {
                NCZGeometryTypes geomType = (NCZGeometryTypes)Enum.Parse(typeof(NCZGeometryTypes),
                                                                         br.ReadByte().ToString());
                switch (geomType)
                {
                case NCZGeometryTypes.Unknown:
                    break;

                case NCZGeometryTypes.Point:
                    NCZPoint p = new NCZPoint();
                    p.Load(br, false);
                    _geometry = p;
                    break;

                //case NCZGeometryTypes.Line:
                //    //NCZLine line = new NCZLine();
                //    //line.Load(br, false);
                //    //_geometry = line;
                //    break;

                //case NCZGeometryTypes.Circle:
                //    break;

                //case NCZGeometryTypes.Arc:
                //    break;

                //case NCZGeometryTypes.Text:
                //    break;

                //case NCZGeometryTypes.Symbol:
                //    break;

                //case NCZGeometryTypes.Polyline:
                //    //this part is included in the original project
                //    break;

                //case NCZGeometryTypes.Box:
                //    break;

                default:
                    br.BaseStream.Position = position;
                    break;
                }
            }
            else
            {
                br.BaseStream.Position = position;
            }
        }
Esempio n. 32
0
 public bool Read(ref byte val, string name = null)
 {
     val = _reader.ReadByte();
     return(true);
 }
Esempio n. 33
0
        public bool Parse(System.IO.BinaryReader reader)
        {
            // 1 byte socksVersion, +1 byte command, +1 byte reserved, +1 byte addressType, +{addressType} bytes dst.address, +2 bytes dst.Port
            if (reader.BaseStream.Length < 10)
            {
                return(false);
            }

            this.SocksVersion = reader.ReadByte();

            this.SocksCommand = (Constants.Command)reader.ReadByte();
            if (!Enum.IsDefined(typeof(Constants.Command), this.SocksCommand))
            {
                return(false);
            }

            if (reader.ReadByte() != 0)
            {
                return(false);
            }

            this.AddressType = (Constants.AddressType)reader.ReadByte();
            if (!Enum.IsDefined(typeof(Constants.AddressType), this.AddressType))
            {
                return(false);
            }

            if (this.AddressType == Constants.AddressType.IPv4)
            {
                if (reader.BaseStream.PeekBytes() != 6)
                {
                    return(false);
                }
                this.DestinationAddress = new IPAddress((long)(uint)reader.ReadInt32());
            }
            else if (this.AddressType == Constants.AddressType.IPv6)
            {
                if (reader.BaseStream.PeekBytes() != 18)
                {
                    return(false);
                }
                this.DestinationAddress = new IPAddress(reader.ReadBytes(16));
            }
            else if (this.AddressType == Constants.AddressType.Domain)
            {
                byte domainLength = reader.ReadByte();
                if (reader.BaseStream.PeekBytes() != domainLength + 2)
                {
                    return(false);
                }
                this.Domain = Encoding.UTF8.GetString(reader.ReadBytes(domainLength));

                try
                {
                    IPHostEntry dnsResults = Dns.GetHostEntry(this.Domain);
                    this.DestinationAddress = dnsResults.AddressList.Where(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).FirstOrDefault();
                    this.DnsSuccess         = true;
                }
                catch (Exception)
                { }

                if (this.DestinationAddress == null)
                {
                    Program.GetInstance().Log.InfoFormat("Domain '{0}' could not be resolved", this.Domain);
                    this.DestinationAddress = IPAddress.Loopback;
                    this.DnsSuccess         = false;
                }
            }

            this.DestinationPort = (ushort)IPAddress.NetworkToHostOrder(reader.ReadInt16());
            return(true);
        }
Esempio n. 34
0
        protected override void DataUpdate()
        {
            System.IO.BinaryReader BSReader = new System.IO.BinaryReader(ByteStream);
            ByteStream.Position = 0;
            Class1               = BSReader.ReadUInt32();
            OGINumber            = BSReader.ReadByte();
            AnimationNumber      = OGINumber;
            ScriptNumber         = BSReader.ReadByte();
            GameObjectNumber     = BSReader.ReadByte();
            UnkI32Number         = BSReader.ReadByte();
            ByteStream.Position -= 4;
            Class2               = BSReader.ReadUInt32();
            Class3               = BSReader.ReadUInt32();
            SoundNumber          = (int)Class3;
            int Len = BSReader.ReadInt32();

            Name = new string(BSReader.ReadChars(Len));

            // UnkI32Number = BSReader.ReadInt32
            UnkI32 = new uint[UnkI32Number];
            for (int i = 0; i <= UnkI32Number - 1; i++)
            {
                UnkI32[i] = BSReader.ReadUInt32();
            }

            // OGINumber = BSReader.ReadInt32
            OGI = new ushort[OGINumber];
            for (int i = 0; i <= OGINumber - 1; i++)
            {
                OGI[i] = BSReader.ReadUInt16();
            }

            // AnimationNumber = BSReader.ReadInt32
            Animation = new ushort[AnimationNumber];
            for (int i = 0; i <= AnimationNumber - 1; i++)
            {
                Animation[i] = BSReader.ReadUInt16();
            }

            // ScriptNumber = BSReader.ReadInt32
            Script = new ushort[ScriptNumber];
            for (int i = 0; i <= ScriptNumber - 1; i++)
            {
                Script[i] = BSReader.ReadUInt16();
            }

            // GameObjectNumber = BSReader.ReadInt32
            _GameObject = new ushort[GameObjectNumber];
            for (int i = 0; i <= GameObjectNumber - 1; i++)
            {
                _GameObject[i] = BSReader.ReadUInt16();
            }

            // SoundNumber = BSReader.ReadInt32
            Sound = new ushort[SoundNumber];
            for (int i = 0; i <= SoundNumber - 1; i++)
            {
                Sound[i] = BSReader.ReadUInt16();
            }

            uint choose = BSReader.ReadUInt32();

            if (choose > 255)
            {
                ParametersHeader        = choose;
                ByteStream.Position    -= 4;
                ParametersUnkI321Number = BSReader.ReadByte();
                ParametersUnkI322Number = BSReader.ReadByte();
                ParametersUnkI323Number = BSReader.ReadByte();
                BSReader.ReadByte();
                ParametersUnkI32 = BSReader.ReadUInt32();

                // ParametersUnkI321Number = BSReader.ReadInt32

                ParametersUnkI321 = new uint[ParametersUnkI321Number];
                for (int i = 0; i <= ParametersUnkI321Number - 1; i++)
                {
                    ParametersUnkI321[i] = BSReader.ReadUInt32();
                }

                // ParametersUnkI322Number = BSReader.ReadInt32
                ParametersUnkI322 = new float[ParametersUnkI322Number];
                for (int i = 0; i <= ParametersUnkI322Number - 1; i++)
                {
                    ParametersUnkI322[i] = BSReader.ReadSingle();
                }

                // ParametersUnkI323Number = BSReader.ReadInt32
                ParametersUnkI323 = new uint[ParametersUnkI323Number];
                for (int i = 0; i <= ParametersUnkI323Number - 1; i++)
                {
                    ParametersUnkI323[i] = BSReader.ReadUInt32();
                }
                choose = BSReader.ReadUInt32();
            }
            else
            {
                ParametersHeader        = 0;
                ParametersUnkI32        = 0;
                ParametersUnkI321Number = 0;
                ParametersUnkI321       = new uint[] { };
                ParametersUnkI322Number = 0;
                ParametersUnkI322       = new float[] { };
                ParametersUnkI323Number = 0;
                ParametersUnkI323       = new uint[] { };
            }
            ChildFlag = choose;
            if (choose > 0)
            {
                string str = Convert.ToString(ChildFlag, 2);
                while (str.Length < 8)
                {
                    str = "0" + str;
                }
                bool GameObjectFlag = (str[7] == '1');
                bool OGIFlag        = (str[6] == '1');
                bool AnimationFlag  = (str[5] == '1');
                bool ID4Flag        = (str[4] == '1');
                bool ScriptFlag     = (str[3] == '1');
                bool UnknownFlag    = (str[2] == '1');
                bool SoundFlag      = (str[1] == '1');
                if (GameObjectFlag)
                {
                    ChildObjectNumber = BSReader.ReadInt32();
                    ChildObject       = new ushort[ChildObjectNumber];
                    for (int i = 0; i <= ChildObjectNumber - 1; i++)
                    {
                        ChildObject[i] = BSReader.ReadUInt16();
                    }
                }
                if (OGIFlag)
                {
                    ChildOGINumber = BSReader.ReadInt32();
                    ChildOGI       = new ushort[ChildOGINumber];
                    for (int i = 0; i <= ChildOGINumber - 1; i++)
                    {
                        ChildOGI[i] = BSReader.ReadUInt16();
                    }
                }
                if (AnimationFlag)
                {
                    ChildAnimationNumber = BSReader.ReadInt32();
                    ChildAnimation       = new ushort[ChildAnimationNumber];
                    for (int i = 0; i <= ChildAnimationNumber - 1; i++)
                    {
                        ChildAnimation[i] = BSReader.ReadUInt16();
                    }
                }
                if (ID4Flag)
                {
                    ChildID4Number = BSReader.ReadInt32();
                    ChildID4       = new ushort[ChildID4Number];
                    for (int i = 0; i <= ChildID4Number - 1; i++)
                    {
                        ChildID4[i] = BSReader.ReadUInt16();
                    }
                }
                if (ScriptFlag)
                {
                    ChildScriptNumber = BSReader.ReadInt32();
                    ChildScript       = new ushort[ChildScriptNumber];
                    for (int i = 0; i <= ChildScriptNumber - 1; i++)
                    {
                        ChildScript[i] = BSReader.ReadUInt16();
                    }
                }
                if (UnknownFlag)
                {
                    ChildUnknownNumber = BSReader.ReadInt32();
                    ChildUnknown       = new ushort[ChildUnknownNumber];
                    for (int i = 0; i <= ChildUnknownNumber - 1; i++)
                    {
                        ChildUnknown[i] = BSReader.ReadUInt16();
                    }
                }
                if (SoundFlag)
                {
                    ChildSoundNumber = BSReader.ReadInt32();
                    ChildSound       = new ushort[ChildSoundNumber];
                    for (int i = 0; i <= ChildSoundNumber - 1; i++)
                    {
                        ChildSound[i] = BSReader.ReadUInt16();
                    }
                }
                ScriptLength = (int)BSReader.ReadUInt32();
                if (ScriptLength > 1)
                {
                    var arrLen = 18;
                    ScriptParameters = new ushort[arrLen];
                    for (int i = 0; i < arrLen; i++)
                    {
                        ScriptParameters[i] = BSReader.ReadUInt16();
                    }
                }
                ScriptArray = BSReader.ReadBytes((int)(ByteStream.Length - ByteStream.Position));
            }
        }
Esempio n. 35
0
        public static JSONNode Deserialize(System.IO.BinaryReader aReader)
        {
            JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte();

            switch (type)
            {
            case JSONBinaryTag.Array:
            {
                int       count = aReader.ReadInt32();
                JSONArray tmp   = new JSONArray();
                for (int i = 0; i < count; i++)
                {
                    tmp.Add(Deserialize(aReader));
                }
                return(tmp);
            }

            case JSONBinaryTag.Class:
            {
                int       count = aReader.ReadInt32();
                JSONClass tmp   = new JSONClass();
                for (int i = 0; i < count; i++)
                {
                    string key = aReader.ReadString();
                    var    val = Deserialize(aReader);
                    tmp.Add(key, val);
                }
                return(tmp);
            }

            case JSONBinaryTag.Value:
            {
                return(new JSONData(aReader.ReadString()));
            }

            case JSONBinaryTag.IntValue:
            {
                return(new JSONData(aReader.ReadInt32()));
            }

            case JSONBinaryTag.DoubleValue:
            {
                return(new JSONData(aReader.ReadDouble()));
            }

            case JSONBinaryTag.BoolValue:
            {
                return(new JSONData(aReader.ReadBoolean()));
            }

            case JSONBinaryTag.FloatValue:
            {
                return(new JSONData(aReader.ReadSingle()));
            }

            default:
            {
                throw new Exception("Error deserializing JSON. Unknown tag: " + type);
            }
            }
        }
Esempio n. 36
0
        protected override void DataUpdate()
        {
            System.IO.BinaryReader BSReader = new System.IO.BinaryReader(ByteStream);
            ByteStream.Position = 0;
            SubModels           = BSReader.ReadInt32();
            Array.Resize(ref SubModel, SubModels);
            for (int i = 0; i <= SubModels - 1; i++)
            {
                {
                    var withBlock = SubModel[i];
                    withBlock.MaterialID = BSReader.ReadUInt32();
                    withBlock.BlockSize  = BSReader.ReadUInt32();
                    withBlock.Vertexes   = BSReader.ReadInt32();
                    int cnt, offset;
                    cnt                 = 0;
                    offset              = (int)ByteStream.Position;
                    withBlock.k         = BSReader.ReadUInt16();
                    withBlock.c         = BSReader.ReadUInt16();
                    withBlock.Null1     = BSReader.ReadUInt32();
                    withBlock.Something = BSReader.ReadUInt32();
                    withBlock.Null2     = BSReader.ReadUInt32();
                    Array.Resize(ref withBlock.Group, 0);
                    while ((cnt < withBlock.Vertexes) && (ByteStream.Position < offset + withBlock.BlockSize))
                    {
                        _Groups.Add(new _Group());
                        {
                            var withBlock1 = _Groups[_Groups.Count - 1];
                            Array.Resize(ref withBlock1.Struct3, 0);
                            Array.Resize(ref withBlock1.Struct4, 0);
                            Array.Resize(ref withBlock1.Struct5, 0);
                            Array.Resize(ref withBlock1.Struct6, 0);
                            withBlock1.SomeNum1 = BSReader.ReadUInt32();
                            withBlock1.Vertexes = BSReader.ReadByte();
                            cnt += withBlock1.Vertexes;
                            withBlock1.Some80h        = BSReader.ReadByte();
                            withBlock1.Null1          = BSReader.ReadUInt16();
                            withBlock1.SomeNum2       = BSReader.ReadUInt32();
                            withBlock1.SomeNum3       = BSReader.ReadUInt32();
                            withBlock1.Null2          = BSReader.ReadUInt32();
                            withBlock1.Signature1     = BSReader.ReadUInt32();
                            withBlock1.SomeGroup1Head = BSReader.ReadUInt32();
                            Array.Resize(ref withBlock1.Group1Stuff, 2);
                            for (int n = 0; n <= 1; n++)
                            {
                                withBlock1.Group1Stuff[n] = BSReader.ReadUInt32();
                            }
                            withBlock1.SomeGroup2Head = BSReader.ReadUInt32();
                            Array.Resize(ref withBlock1.Group2Stuff, 8);
                            for (int n = 0; n <= 7; n++)
                            {
                                withBlock1.Group2Stuff[n] = BSReader.ReadUInt32();
                            }
                            withBlock1.Signature2 = BSReader.ReadUInt32();
                            uint head = BSReader.ReadUInt32();
                            while (head != 335544320)
                            {
                                switch (head & 255)
                                {
                                case 3:
                                {
                                    withBlock1.Struct3Head = head;
                                    Array.Resize(ref withBlock1.Struct3, withBlock1.Vertexes);
                                    for (int j = 0; j <= withBlock1.Vertexes - 1; j++)
                                    {
                                        withBlock1.Struct3[j].ID1 = BSReader.ReadUInt32();
                                        withBlock1.Struct3[j].ID2 = BSReader.ReadUInt32();
                                    }
                                    Array.Resize(ref withBlock1.Struct3End, 5);
                                    for (int n = 0; n <= 4; n++)
                                    {
                                        withBlock1.Struct3End[n] = BSReader.ReadUInt32();
                                    }
                                    break;
                                }

                                case 4:
                                {
                                    withBlock1.Struct4Head = head;
                                    Array.Resize(ref withBlock1.Struct4, withBlock1.Vertexes);
                                    for (int j = 0; j <= withBlock1.Vertexes - 1; j++)
                                    {
                                        withBlock1.Struct4[j].ID1 = BSReader.ReadUInt32();
                                        withBlock1.Struct4[j].ID2 = BSReader.ReadUInt32();
                                    }
                                    withBlock1.Struct4End = BSReader.ReadUInt32();
                                    break;
                                }

                                case 6:
                                {
                                    withBlock1.Struct6Head = head;
                                    Array.Resize(ref withBlock1.Struct6, withBlock1.Vertexes);
                                    for (int j = 0; j <= withBlock1.Vertexes - 1; j++)
                                    {
                                        withBlock1.Struct6[j] = BSReader.ReadUInt32();
                                    }
                                    break;
                                }

                                case 5:
                                {
                                    withBlock1.Struct5Head = head;
                                    Array.Resize(ref withBlock1.Struct5, withBlock1.Vertexes);
                                    for (int j = 0; j <= withBlock1.Vertexes - 1; j++)
                                    {
                                        withBlock1.Struct5[j].Float = BSReader.ReadSingle();
                                        withBlock1.Struct5[j].a     = BSReader.ReadUInt32();
                                        withBlock1.Struct5[j].b     = BSReader.ReadUInt32();
                                        withBlock1.Struct5[j].ID    = BSReader.ReadByte();
                                        withBlock1.Struct5[j].CONN  = BSReader.ReadByte();
                                        withBlock1.Struct5[j].Null  = BSReader.ReadInt16();
                                    }

                                    break;
                                }
                                }
                                head = BSReader.ReadUInt32();
                            }
                            withBlock1.EndSignature1 = head;
                            withBlock1.EndSignature2 = BSReader.ReadUInt32();
                            Array.Resize(ref withBlock1.leftovers, 0);
                        }
                    }
                    withBlock.Group = _Groups.ToArray();
                    _Groups.Clear();
                    Array.Resize(ref withBlock.Group[withBlock.Group.Length - 1].leftovers, (int)(withBlock.BlockSize + offset - ByteStream.Position));
                    withBlock.Group[withBlock.Group.Length - 1].leftovers = BSReader.ReadBytes((int)(withBlock.BlockSize + offset - ByteStream.Position));
                }
            }
        }
Esempio n. 37
0
        private void GetResponseCallback(IAsyncResult asynchronousResult)
        {
            try
            {
                HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
                HttpWebResponse response;

                // End the get response operation
                response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
                System.IO.Stream streamResponse = response.GetResponseStream();

                System.IO.BinaryReader inputstream = new System.IO.BinaryReader(streamResponse);

                if (inputstream.BaseStream.Length > 0)
                {
                    byte[] responsebytes = new byte[inputstream.BaseStream.Length];
                    int totalRead = 0;
                    while (totalRead < inputstream.BaseStream.Length)
                    {
                        responsebytes[totalRead++] = inputstream.ReadByte();
                    }

                    ArraySegment<byte> raw = new ArraySegment<byte>(responsebytes, 0, totalRead);
                    PCOSMessageBase msg = PCOSMsgFactory.Parse(raw);

                    OnPingPongResponse(this, new PingPongEventArgs(msg));
                }
                streamResponse.Close();
                inputstream.Close();
                response.Close();
            }
            catch (WebException e)
            {
            }
        }
Esempio n. 38
0
        public void Populate(int iOffset, bool useMemoryStream)
        {
            this.isNulledOutReflexive = false;
            System.IO.BinaryReader BR = new System.IO.BinaryReader(meta.MS);
            //set offsets
            BR.BaseStream.Position = iOffset + this.chunkOffset;
            this.offsetInMap       = iOffset + this.chunkOffset;
            // If we need to read / save tag info directly to file...
            if (!useMemoryStream)
            {
                map.OpenMap(MapTypes.Internal);
                BR = map.BR;
                BR.BaseStream.Position = this.offsetInMap;
            }
            else
            {
                this.offsetInMap += meta.offset;
            }

            this.sidIndexer = BR.ReadInt16();
            byte tempnull  = BR.ReadByte();
            byte sidLength = BR.ReadByte();

            // ...and then close the file once we are done!
            if (!useMemoryStream)
            {
                map.CloseMap();
            }

            try
            {
                string s = map.Strings.Name[this.sidIndexer];
                if (map.Strings.Length[this.sidIndexer] == sidLength)
                {
                    if (this.comboBox1.DataSource == null)
                    {
                        this.comboBox1.Items.Clear();
                        this.comboBox1.Items.Add(s);
                        this.comboBox1.SelectedIndex = 0;
                    }
                    else
                    {
                        this.comboBox1.SelectedIndex = this.sidIndexer; //.Text = s;
                    }
                }
                else
                {
                    this.comboBox1.Text = "";
                }
            }
            catch
            {
                this.comboBox1.Text = "error reading sid";
            }

            /*
             * if (AddEvents == true)
             * {
             *  this.comboBox1.TextChanged += new System.EventHandler(this.comboBox1_TextChanged);
             *  AddEvents = false;
             * }
             */
        }
Esempio n. 39
0
        private void LoadProgram()
        {
            var fileStream = new System.IO.FileStream(programFileName, System.IO.FileMode.Open);
            var binaryReader = new System.IO.BinaryReader(fileStream);

            var magicWordBytes = binaryReader.ReadBytes(8);
            var magicWord = System.Text.Encoding.Default.GetString(magicWordBytes);

            if (magicWord != "ZHANGSHU")
            {
                System.Windows.Forms.MessageBox.Show("It is NOT a VM binary file!", "Error!", MessageBoxButtons.OK);
                return;
            }

            var offset = binaryReader.ReadUInt16();
            var length = binaryReader.ReadUInt16();

            var position = binaryReader.ReadUInt16();          //where the program starts in memory

            ushort i = 0;
            while (binaryReader.BaseStream.Position < binaryReader.BaseStream.Length)
            {
                memory[(UInt16)(position + i)] = binaryReader.ReadByte();
                ++i;
            }

            binaryReader.Close();
            fileStream.Close();

            programPosition = (UInt16)(position + offset - 14);
        }
Esempio n. 40
0
        public void OnCharCreate(int serial, byte worldID, byte slotID, string charName, byte[] charData)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream(charData);
            System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
            ms.Position = 2;
            byte[] display1 = Conversions.HexStr2Bytes("6363634E63737364777777636464776464646464646464");
            br.ReadBytes(br.ReadInt16()).CopyTo(display1, 0);
            ActorPC pc = new ActorPC()
            {
                Level       = 1,
                AccountID   = account.AccountID,
                Name        = charName,
                SlotID      = slotID,
                WorldID     = worldID,
                Appearence1 = display1
            };

            ms.Position     += 2;
            pc.Race          = (Race)br.ReadByte();
            ms.Position     += 2;
            pc.Gender        = (Gender)br.ReadByte();
            ms.Position     += 2;
            pc.Job           = (Job)br.ReadByte();
            ms.Position     += 2;
            pc.Appearence2   = br.ReadBytes(br.ReadInt16());
            pc.MapID         = 1101;
            pc.X             = -3177;
            pc.Y             = 9243;
            pc.Z             = 599;
            pc.Dir           = 45;
            pc.UISettings    = string.Empty;
            pc.InventorySize = 32;
            switch (pc.Job)
            {
            case Job.Assassin:
                pc.HP    = 66;
                pc.MP    = 0;
                pc.MaxHP = 66;
                pc.MaxMP = 10;
                break;

            case Job.ForceMaster:
                pc.HP    = 61;
                pc.MP    = 10;
                pc.MaxHP = 61;
                pc.MaxMP = 10;
                break;

            case Job.KungfuMaster:
                pc.HP    = 109;
                pc.MaxHP = 109;
                pc.MP    = 0;
                pc.MaxMP = 10;
                break;

            case Job.BladeMaster:
            default:
                pc.HP    = 99;
                pc.MP    = 0;
                pc.MaxHP = 99;
                pc.MaxMP = 10;
                break;
            }

            characterSerial = serial;
            createdPC       = pc;
            CharacterSession.Instance.CreateChar(pc, this);
        }
Esempio n. 41
0
        private void GetResponseCallback(IAsyncResult asynchronousResult)
        {
            PCOSMessageBase retmsg = new PCOSMsgInvalid();
            try
            {
                HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
                HttpWebResponse response;

                // End the get response operation
                response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
                System.IO.Stream streamResponse = response.GetResponseStream();

                System.IO.BinaryReader inputstream = new System.IO.BinaryReader(streamResponse);

                if (inputstream.BaseStream.Length > 0)
                {
                    byte[] responsebytes = new byte[inputstream.BaseStream.Length];
                    int totalRead = 0;
                    while (totalRead < inputstream.BaseStream.Length)
                    {
                        responsebytes[totalRead++] = inputstream.ReadByte();
                    }

                    ArraySegment<byte> raw = new ArraySegment<byte>(responsebytes, 0, totalRead);
                    retmsg = PCOSMsgFactory.Parse(raw);
                }
                streamResponse.Close();
                inputstream.Close();
                response.Close();
            }
            catch (WebException e)
            {
            }

            DSAHelper.RegisterResult registerresult = new RegisterResult();
            if(retmsg is PCOSMsgRegisterAck)
            {
                PCOSMsgRegisterAck pcosregack = (PCOSMsgRegisterAck)retmsg;

                registerresult.Registered = true;
                registerresult.Message = "Registered Successful";

                PCSettings.PEMPublic = this.PEMPublicKey;
                PCSettings.PEMPrivate = this.PEMPrivateKey;
                PCSettings.MAT = Convert.ToBase64String(pcosregack.MAT);
                PCSettings.Registered = true;
                PCSettings.RegDatetime = DateTime.Now;

                // save it first...
                PCSettings.Save();
            }
            else if(retmsg is PCOSMsgError)
            {
                PCOSMsgError pcosmsgerr = (PCOSMsgError)retmsg;
                registerresult.Message = pcosmsgerr.ErrorCode + ":" + pcosmsgerr.Reason;
            }
            else
            {
                registerresult.Message = "Failed to registered with Push Coin server. Please try again at a later time.";
            }

            if (OnRegistered != null)
                OnRegistered(registerresult);
        }
Esempio n. 42
0
 public override void Deserialize(System.IO.BinaryReader reader)
 {
     base.Deserialize(reader);
     _responseType = reader.ReadByte();
     _result       = reader.ReadByte();
 }
        private void OpenFile(string filename)
        {
            #if !DEBUG
            try
            {
            #endif
                _filename = filename;
                fileIn = new System.IO.BinaryReader(System.IO.File.Open(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read));

                string startFileSig = "";
                for (int i = 0; i < 4; i++) // 4 bytes
                {
                    startFileSig += fileIn.ReadChar();
                }
                if (startFileSig != "#PES")
                {
                    // This is not a file that we can read
                    readyStatus = statusEnum.ParseError;
                    lastError = "Missing #PES at beginning of file";
                    fileIn.Close();
                    return;
                }

                // PES version
                string versionString = "";
                for (int i = 0; i < 4; i++) // 4 bytes
                {
                    versionString += fileIn.ReadChar();
                }
                pesVersion = Convert.ToUInt16(versionString);

                int pecstart = fileIn.ReadInt32();

                fileIn.BaseStream.Position = pecstart + 48;
                int numColors = fileIn.ReadByte() +1;
                List<byte> colorList = new List<byte>();
                for (int x = 0; x < numColors; x++)
                {
                    colorList.Add(fileIn.ReadByte());
                }

                fileIn.BaseStream.Position = pecstart + 532;
                bool thisPartIsDone = false;
                stitchBlock curBlock;
                int prevX = 0;
                int prevY = 0;
                int maxX = 0;
                int minX = 0;
                int maxY = 0;
                int minY = 0;
                int colorNum = -1;
                int colorIndex = 0;
                List<Point> tempStitches = new List<Point>();
                while (!thisPartIsDone)
                {
                    byte val1;
                    byte val2;
                    val1 = fileIn.ReadByte();
                    val2 = fileIn.ReadByte();
                    if (val1 == 255 && val2 == 0)
                    {
                        //end of stitches
                        thisPartIsDone = true;

                        //add the last block
                        curBlock = new stitchBlock();
                        curBlock.stitches = new Point[tempStitches.Count];
                        tempStitches.CopyTo(curBlock.stitches);
                        curBlock.stitchesTotal = tempStitches.Count;
                        colorNum++;
                        colorIndex = colorList[colorNum];
                        curBlock.colorIndex = colorIndex;
                        curBlock.color = getColorFromIndex(colorIndex);
                        blocks.Add(curBlock);
                    }
                    else if (val1 == 254 && val2 == 176)
                    {
                        //color switch, start a new block

                        curBlock = new stitchBlock();
                        curBlock.stitches = new Point[tempStitches.Count];
                        tempStitches.CopyTo(curBlock.stitches);
                        curBlock.stitchesTotal = tempStitches.Count;
                        colorNum++;
                        colorIndex = colorList[colorNum];
                        curBlock.colorIndex = colorIndex;
                        curBlock.color = getColorFromIndex(colorIndex);
                        blocks.Add(curBlock);

                        tempStitches = new List<Point>();

                        //read useless(?) byte
                        fileIn.ReadByte();
                    }
                    else
                    {
                        int deltaX = 0;
                        int deltaY = 0;
                        if ((val1 & 0x80) == 0x80)
                        {
                            //this is a jump stitch
                            deltaX = ((val1 & 0x0f) << 8) + val2;
                            /* dead code? bit we're checking is masked out in previous line
                            if ((deltaX & 0x0800) == 0x0800)
                            {
                                deltaX = deltaX - 4096;
                            }
                            */
                            //read next byte for Y value
                            val2 = fileIn.ReadByte();
                        }
                        else
                        {
                            //normal stitch
                            deltaX = val1;
                            if (deltaX > 63)
                            {
                                deltaX = deltaX - 128;
                            }
                        }

                        if ((val2 & 0x08) == 0x80)
                        {
                            //this is a jump stitch
                            int val3 = fileIn.ReadByte();
                            deltaY = ((val2 & 0x0f) << 8) + val3;
                            /* dead code? bit we're checking is masked out in previous line
                            if ((deltaY & 0x0800) == 0x0800)
                            {
                                deltaY = deltaY - 4096;
                            }*/
                        }
                        else
                        {
                            //normal stitch
                            deltaY = val2;
                            if (deltaY > 63)
                            {
                                deltaY = deltaY - 128;
                            }
                        }
                        tempStitches.Add(new Point(prevX + deltaX, prevY + deltaY));
                        prevX = prevX + deltaX;
                        prevY = prevY + deltaY;
                        if (prevX > maxX)
                        {
                            maxX = prevX;
                        }
                        else if (prevX < minX)
                        {
                            minX = prevX;
                        }

                        if (prevY > maxY)
                        {
                            maxY = prevY;
                        }
                        else if (prevY < minY)
                        {
                            minY = prevY;
                        }
                    }
                }
                imageWidth = maxX - minX;
                imageHeight = maxY - minY;
                translateStart.X = -minX;
                translateStart.Y = -minY;
                readyStatus = statusEnum.Ready;

                // Close the file
                fileIn.Close();

            #if !DEBUG
            }
            catch (System.IO.IOException ioex)
            {
                readyStatus = statusEnum.IOError;
                lastError = ioex.Message;
                if (fileIn != null)
                {
                    fileIn.Close();
                }
            }
            catch (Exception ex)
            {
                readyStatus = statusEnum.ParseError;
                lastError = ex.Message;
                if (fileIn != null)
                {
                    fileIn.Close();
                }
            }
            #endif
        }
Esempio n. 44
0
        /// <summary>
        /// 检查是否为允许的图片格式
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private bool IsAllowedImage(string filePath)
        {
            bool ret = false;

            System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
            string fileclass = "";
            byte buffer;
            try
            {
                buffer = r.ReadByte();
                fileclass = buffer.ToString();
                buffer = r.ReadByte();
                fileclass += buffer.ToString();
            }
            catch
            {
                return false;
            }
            r.Close();
            fs.Close();
            /*文件扩展名说明
             *7173        gif
             *255216      jpg
             *13780       png
             *6677        bmp
             *239187      txt,aspx,asp,sql
             *208207      xls.doc.ppt
             *6063        xml
             *6033        htm,html
             *4742        js
             *8075        xlsx,zip,pptx,mmap,zip
             *8297        rar
             *01          accdb,mdb
             *7790        exe,dll
             *5666        psd
             *255254      rdp
             *10056       bt种子
             *64101       bat
             */

            // String[] fileType = { "255216", "7173", "6677", "13780", "8297", "5549", "870", "87111", "8075" };
            string[] fileType = { "255216", "7173", "6677", "13780" };

            for (int i = 0; i < fileType.Length; i++)
            {
                if (fileclass == fileType[i])
                {
                    ret = true;
                    break;
                }
            }
            return ret;
        }
Esempio n. 45
0
        public void Populate(int iOffset, bool useMemoryStream)
        {
            this.isNulledOutReflexive = false;
            System.IO.BinaryReader BR = new System.IO.BinaryReader(meta.MS);
            //set offsets
            BR.BaseStream.Position = iOffset + this.chunkOffset;
            this.offsetInMap = iOffset + this.chunkOffset;
            // If we need to read / save tag info directly to file...
            if (!useMemoryStream)
            {
                map.OpenMap(MapTypes.Internal);
                BR = map.BR;
                BR.BaseStream.Position = this.offsetInMap;
            }
            else
                this.offsetInMap += meta.offset;

            //Decide how big the bitmask is
            switch (this.bitCount)
            {
                case 8:
                    {
                        this.value = BR.ReadByte();
                        break;
                    }
                case 16:
                    {
                        this.value = BR.ReadUInt16();
                        break;
                    }
                case 32:
                    {
                        this.value = BR.ReadUInt32();
                        break;
                    }
            }
            // ...and then close the file once we are done!
            if (!useMemoryStream)
                map.CloseMap();
            //convert this.value (an object) into a bool array, then update the checkboxes with that bool array
            BitsToBool();
            BoolsToControls();
        }
Esempio n. 46
0
        public static void readSeparateIndex(System.IO.Stream index, System.IO.Stream XMLBytes, int XMLSize, VTDGen vg)
        {
            if (index == null || vg == null || XMLBytes == null)
            {
                throw new System.ArgumentException("Invalid argument(s) for readIndex()");
            }
            //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader'
            //which has a different behavior.
            //"ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'"
            System.IO.BinaryReader dis = new System.IO.BinaryReader(index);
            byte b = dis.ReadByte(); // first byte

            // no check on version number for now
            // second byte
            vg.encoding = dis.ReadByte();
            int intLongSwitch;
            int endian;

            // third byte
            b = dis.ReadByte();
            if ((b & 0x80) != 0)
            {
                intLongSwitch = 1;
            }
            //use ints
            else
            {
                intLongSwitch = 0;
            }
            if ((b & 0x40) != 0)
            {
                vg.ns = true;
            }
            else
            {
                vg.ns = false;
            }
            if ((b & 0x20) != 0)
            {
                endian = 1;
            }
            else
            {
                endian = 0;
            }
            if ((b & 0x1f) != 0)
            {
                throw new IndexReadException("Last 5 bits of the third byte should be zero");
            }

            // fourth byte
            vg.VTDDepth = dis.ReadByte();

            // 5th and 6th byte
            int LCLevel = (((int)dis.ReadByte()) << 8) | dis.ReadByte();

            if (LCLevel != 4 && LCLevel != 6)
            {
                throw new IndexReadException("LC levels must be at least 3");
            }
            // 7th and 8th byte
            vg.rootIndex = (((int)dis.ReadByte()) << 8) | dis.ReadByte();

            // skip a long
            dis.ReadInt64();
            //Console.WriteLine(" l ==>" + l);
            dis.ReadInt64();
            //Console.WriteLine(" l ==>" + l);
            long l = dis.ReadInt64();

            int size;

            // read XML size
            if (BitConverter.IsLittleEndian && endian == 0 ||
                BitConverter.IsLittleEndian == false && endian == 1)
            {
                size = (int)l;
            }
            else
            {
                size = (int)reverseLong(l);
            }


            // read XML bytes
            byte[] XMLDoc = new byte[size];
            XMLBytes.Read(XMLDoc, 0, size);

            //dis.Read(XMLDoc, 0, size);

            /*if ((size & 0x7) != 0)
             * {
             *  int t = (((size >> 3) + 1) << 3) - size;
             *  while (t > 0)
             *  {
             *      dis.ReadByte();
             *      t--;
             *  }
             * }*/

            vg.setDoc(XMLDoc);
            // skip a long
            dis.ReadInt64();
            //Console.WriteLine(" l ==>" + l);
            dis.ReadInt64();
            //Console.WriteLine(" l ==>" + l);
            if (BitConverter.IsLittleEndian && endian == 0 ||
                BitConverter.IsLittleEndian == false && endian == 1)
            {
                // read vtd records
                int vtdSize = (int)dis.ReadInt64();
                while (vtdSize > 0)
                {
                    vg.VTDBuffer.append(dis.ReadInt64());
                    vtdSize--;
                }
                // read L1 LC records
                int l1Size = (int)dis.ReadInt64();
                while (l1Size > 0)
                {
                    vg.l1Buffer.append(dis.ReadInt64());
                    l1Size--;
                }
                // read L2 LC records
                int l2Size = (int)dis.ReadInt64();
                while (l2Size > 0)
                {
                    vg.l2Buffer.append(dis.ReadInt64());
                    l2Size--;
                }
                // read L3 LC records
                int l3Size = (int)dis.ReadInt64();
                if (vg.shallowDepth)
                {
                    if (intLongSwitch == 1)
                    {
                        //l3 uses ints
                        while (l3Size > 0)
                        {
                            vg.l3Buffer.append(dis.ReadInt32());
                            l3Size--;
                        }
                    }
                    else
                    {
                        while (l3Size > 0)
                        {
                            vg.l3Buffer.append((int)(dis.ReadInt64() >> 32));
                            l3Size--;
                        }
                    }
                }
                else
                {
                    while (l3Size > 0)
                    {
                        vg._l3Buffer.append(dis.ReadInt64());
                        l3Size--;
                    }

                    int l4Size = (int)dis.ReadInt64();
                    while (l4Size > 0)
                    {
                        vg._l4Buffer.append(dis.ReadInt64());
                        l4Size--;
                    }

                    int l5Size = (int)dis.ReadInt64();
                    if (intLongSwitch == 1)
                    {
                        while (l5Size > 0)
                        {
                            vg._l5Buffer.append(dis.ReadInt32());
                            l5Size--;
                        }
                    }
                    else
                    {
                        while (l5Size > 0)
                        {
                            vg._l5Buffer.append((int)(dis.ReadInt64() >> 32));
                            l5Size--;
                        }
                    }
                }
            }
            else
            {
                // read vtd records
                int vtdSize = (int)reverseLong(dis.ReadInt64());
                while (vtdSize > 0)
                {
                    vg.VTDBuffer.append(reverseLong(dis.ReadInt64()));
                    vtdSize--;
                }
                // read L1 LC records
                int l1Size = (int)reverseLong(dis.ReadInt64());
                while (l1Size > 0)
                {
                    vg.l1Buffer.append(reverseLong(dis.ReadInt64()));
                    l1Size--;
                }
                // read L2 LC records
                int l2Size = (int)reverseLong(dis.ReadInt64());
                while (l2Size > 0)
                {
                    vg.l2Buffer.append(reverseLong(dis.ReadInt64()));
                    l2Size--;
                }
                // read L3 LC records
                int l3Size = (int)reverseLong(dis.ReadInt64());
                if (vg.shallowDepth)
                {
                    if (intLongSwitch == 1)
                    {
                        //l3 uses ints
                        while (l3Size > 0)
                        {
                            vg.l3Buffer.append(reverseInt(dis.ReadInt32()));
                            l3Size--;
                        }
                    }
                    else
                    {
                        while (l3Size > 0)
                        {
                            vg.l3Buffer.append(reverseInt((int)(dis.ReadInt64() >> 32)));
                            l3Size--;
                        }
                    }
                }
                else
                {
                    while (l3Size > 0)
                    {
                        vg._l3Buffer.append(reverseLong(dis.ReadInt64()));
                        l3Size--;
                    }

                    int l4Size = (int)reverseLong(dis.ReadInt64());
                    {
                        vg._l4Buffer.append(reverseLong(dis.ReadInt64()));
                        l4Size--;
                    }

                    int l5Size = (int)reverseLong(dis.ReadInt64());
                    if (intLongSwitch == 1)
                    {
                        //l3 uses ints
                        while (l5Size > 0)
                        {
                            vg._l5Buffer.append(reverseInt(dis.ReadInt32()));
                            l5Size--;
                        }
                    }
                    else
                    {
                        while (l5Size > 0)
                        {
                            vg._l5Buffer.append(reverseInt((int)(dis.ReadInt64() >> 32)));
                            l5Size--;
                        }
                    }
                }
            }
        }
Esempio n. 47
0
        static private System.Collections.Generic.SortedList <System.UInt64, System.IntPtr> ReadFile(System.IO.BinaryReader binaryReader, AddressLibrary.Header header)
        {
            var offsets = new System.Collections.Generic.SortedList <System.UInt64, System.IntPtr>(header.AddressCount);

            System.UInt64 identifier;
            System.UInt64 offset;

            System.UInt64 previousIdentifier = 0;
            System.UInt64 previousOffset     = 0;

            for (var index = 0; index < header.AddressCount; index++)
            {
                var type           = binaryReader.ReadByte();
                var identifierType = type & 0xF;
                var offsetType     = type >> 4;

                switch ((AddressLibrary.ReadTypes)identifierType)
                {
                case AddressLibrary.ReadTypes.ReadUInt64:
                {
                    identifier = binaryReader.ReadUInt64();

                    break;
                }

                case AddressLibrary.ReadTypes.Add1:
                {
                    identifier = previousIdentifier + 1;

                    break;
                }

                case AddressLibrary.ReadTypes.AddReadByte:
                {
                    identifier = previousIdentifier + binaryReader.ReadByte();

                    break;
                }

                case AddressLibrary.ReadTypes.SubtractReadByte:
                {
                    identifier = previousIdentifier - binaryReader.ReadByte();

                    break;
                }

                case AddressLibrary.ReadTypes.AddReadUInt16:
                {
                    identifier = previousIdentifier + binaryReader.ReadUInt16();

                    break;
                }

                case AddressLibrary.ReadTypes.SubtractReadUInt16:
                {
                    identifier = previousIdentifier - binaryReader.ReadUInt16();

                    break;
                }

                case AddressLibrary.ReadTypes.ReadUInt16:
                {
                    identifier = binaryReader.ReadUInt16();

                    break;
                }

                case AddressLibrary.ReadTypes.ReadUInt32:
                {
                    identifier = binaryReader.ReadUInt32();

                    break;
                }

                default:
                {
                    try
                    {
                        throw new System.InvalidOperationException($"{nameof(AddressLibrary)}: Unexpected {nameof(identifierType)} encountered, {identifierType}.");
                    }
                    catch (System.InvalidOperationException invalidOperationException)
                    {
                        Log.Information($"{invalidOperationException}");

                        throw;
                    }
                }
                }

                var temporaryOffset = (offsetType & 8) != 0 ? previousOffset / (System.UInt64)header.PointerSize : previousOffset;

                switch ((AddressLibrary.ReadTypes)(offsetType & 7))
                {
                case AddressLibrary.ReadTypes.ReadUInt64:
                {
                    offset = binaryReader.ReadUInt64();

                    break;
                }

                case AddressLibrary.ReadTypes.Add1:
                {
                    offset = temporaryOffset + 1;

                    break;
                }

                case AddressLibrary.ReadTypes.AddReadByte:
                {
                    offset = temporaryOffset + binaryReader.ReadByte();

                    break;
                }

                case AddressLibrary.ReadTypes.SubtractReadByte:
                {
                    offset = temporaryOffset - binaryReader.ReadByte();

                    break;
                }

                case AddressLibrary.ReadTypes.AddReadUInt16:
                {
                    offset = temporaryOffset + binaryReader.ReadUInt16();

                    break;
                }

                case AddressLibrary.ReadTypes.SubtractReadUInt16:
                {
                    offset = temporaryOffset - binaryReader.ReadUInt16();

                    break;
                }

                case AddressLibrary.ReadTypes.ReadUInt16:
                {
                    offset = binaryReader.ReadUInt16();

                    break;
                }

                case AddressLibrary.ReadTypes.ReadUInt32:
                {
                    offset = binaryReader.ReadUInt32();

                    break;
                }

                default:
                {
                    try
                    {
                        throw new System.InvalidOperationException($"{nameof(AddressLibrary)}: Unexpected {nameof(offsetType)} encountered, {offsetType}.");
                    }
                    catch (System.InvalidOperationException invalidOperationException)
                    {
                        Log.Information($"{invalidOperationException}");

                        throw;
                    }
                }
                }

                if ((offsetType & 8) != 0)
                {
                    offset *= (System.UInt64)header.PointerSize;
                }

                offsets.Add(identifier, new System.IntPtr((System.Int64)offset));

                previousIdentifier = identifier;
                previousOffset     = offset;
            }

            return(offsets);
        }
Esempio n. 48
0
        public override object Deserialize(System.IO.BinaryReader binaryReader)
        {
            bool hasValue = binaryReader.ReadBoolean();

            if (!hasValue)
            {
                return(null);
            }
            int typeID = binaryReader.ReadByte();

            switch (typeID)
            {
            case 1:
                return(binaryReader.ReadBoolean());

            case 2:
                return(binaryReader.ReadByte());

            case 128:
                return(binaryReader.ReadSByte());

            case 3:
                return(binaryReader.ReadInt16());

            case 129:
                return(binaryReader.ReadUInt16());

            case 4:
                return(binaryReader.ReadInt32());

            case 130:
                return(binaryReader.ReadUInt32());

            case 5:
                return(binaryReader.ReadInt64());

            case 131:
                return(binaryReader.ReadUInt64());

            case 9:
                return(binaryReader.ReadDouble());

            case 16:
                return(binaryReader.ReadString());

            case 144:
                return(binaryReader.ReadChar());

            case 24:
                return(new DateTime(binaryReader.ReadInt64()));

            case 32:
                return(new Guid(binaryReader.ReadBytes(16)));

            case 36:
                return(binaryReader.ReadBytes(binaryReader.ReadInt32()));

            default:
                throw new Exception(string.Format("Serialization for type <{0}> is not supported", typeID));
            }
        }
Esempio n. 49
0
        public void readFile()
        {
            System.IO.BinaryReader sr;

            try { //TODO: test, rather than try/fail?
                sr = new System.IO.BinaryReader(System.IO.File.Open(path, System.IO.FileMode.Open));
            } catch (System.IO.IOException) {
                throw;
            }

            //====================
            //RIFF chunk id
            char[] ckID = sr.ReadChars(4);
            String a = new string(ckID);
            if (a.CompareTo("RIFF") != 0) {
                throw new FormatException("RIFF chunkID missing. Found " + ckID[0] + ckID[1] + ckID[2] + ckID[3] + ".");
            }

            UInt32 RIFFSize = sr.ReadUInt32();

            //====================
            //WAVE chunk id
            ckID = sr.ReadChars(4);
            a = new string(ckID);
            if (a.CompareTo("WAVE") != 0) {
                throw new FormatException("WAVE chunkID missing. Found " + ckID[0] + ckID[1] + ckID[2] + ckID[3] + ".");
            }

            //====================
            //fmt_ chunk id
            ckID = sr.ReadChars(4);
            a = new string(ckID);
            UInt32 chunkSize = sr.ReadUInt32();
            while (a.CompareTo("fmt ") != 0) {
                sr.ReadBytes((int)chunkSize);
                ckID = sr.ReadChars(4);
                a = new string(ckID);
                chunkSize = sr.ReadUInt32();
            }
            Int16 wFormatTag = sr.ReadInt16();
            Int16 nChannels = sr.ReadInt16();
            Int32 nSamplesPerSec = sr.ReadInt32();
            Int32 nAvgBytesPerSec = sr.ReadInt32();
            Int16 nBlockAlign = sr.ReadInt16();
            Int16 wBitsPerSample = sr.ReadInt16();
            chunkSize -= 16;
            //there may be more bytes in fmt_ so skip those.
            sr.ReadBytes((int)chunkSize);

            if (wFormatTag != 0x0001) {
                throw new FormatException("Invalid wave format. Only PCM wave files supported.");
            }

            //====================
            //data chunk id
            ckID = sr.ReadChars(4);
            a = new string(ckID);
            chunkSize = sr.ReadUInt32();
            while (a.CompareTo("data") != 0) {
                sr.ReadBytes((int)chunkSize);
                ckID = sr.ReadChars(4);
                a = new string(ckID);
                chunkSize = sr.ReadUInt32();
            }

            channels = (short)nChannels;
            bitDepth = (short)wBitsPerSample;
            sampleRate = nSamplesPerSec;
            long numSamples = chunkSize / (bitDepth / 8) / channels;
            samples = new double[channels][];
            for (int c = 0; c < channels; c++) {
                samples[c] = new double[numSamples];
            }

            //======================
            // read samples
            if (bitDepth == 16) {
                for (int i = 0; i < numSamples; i++) {
                    for (int c = 0; c < channels; c++) {
                        //assuming signed
                        //normalized to -1.0..+1.0
                        samples[c][i] = (double)sr.ReadInt16() / 32768.0;
                    }
                }
            } else if (bitDepth == 8) {
                for (int i = 0; i < numSamples; i++) {
                    for (int c = 0; c < channels; c++) {
                        //assuming unsigned
                        //normalized to -1.0..+1.0
                        samples[c][i] = (double)sr.ReadByte() / 128.0 - 1.0;
                    }
                }
            } else {
                throw new FormatException("Bit depth must be one of 8 or 16 bits.");
            }
            sr.Close();
        }
Esempio n. 50
0
        public static void readSeparateIndex(System.IO.Stream index, System.IO.Stream XMLBytes, int XMLSize, VTDGen vg)
        {
            if (index == null || vg == null || XMLBytes == null)
            {
                throw new System.ArgumentException("Invalid argument(s) for readIndex()");
            }
            //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' 
            //which has a different behavior. 
            //"ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'"
            System.IO.BinaryReader dis = new System.IO.BinaryReader(index);
            byte b = dis.ReadByte(); // first byte
            // no check on version number for now
            // second byte
            vg.encoding = dis.ReadByte();
            int intLongSwitch;
            int endian;
            // third byte
            b = dis.ReadByte();
            if ((b & 0x80) != 0)
                intLongSwitch = 1;
            //use ints
            else
                intLongSwitch = 0;
            if ((b & 0x40) != 0)
                vg.ns = true;
            else
                vg.ns = false;
            if ((b & 0x20) != 0)
                endian = 1;
            else
                endian = 0;
            if ((b & 0x1f) != 0)
                throw new IndexReadException("Last 5 bits of the third byte should be zero");

            // fourth byte
            vg.VTDDepth = dis.ReadByte();

            // 5th and 6th byte
            int LCLevel = (((int)dis.ReadByte()) << 8) | dis.ReadByte();
            if (LCLevel != 4 && LCLevel != 6)
            {
                throw new IndexReadException("LC levels must be at least 3");
            }
            // 7th and 8th byte
            vg.rootIndex = (((int)dis.ReadByte()) << 8) | dis.ReadByte();

            // skip a long
            dis.ReadInt64();
            //Console.WriteLine(" l ==>" + l);
            dis.ReadInt64();
            //Console.WriteLine(" l ==>" + l);
            long l = dis.ReadInt64();

            int size;
            // read XML size
            if (BitConverter.IsLittleEndian && endian == 0
                || BitConverter.IsLittleEndian == false && endian == 1)
                size = (int)l;
            else
                size = (int)reverseLong(l);


            // read XML bytes
            byte[] XMLDoc = new byte[size];
            XMLBytes.Read(XMLDoc, 0, size);

            //dis.Read(XMLDoc, 0, size);
            /*if ((size & 0x7) != 0)
            {
                int t = (((size >> 3) + 1) << 3) - size;
                while (t > 0)
                {
                    dis.ReadByte();
                    t--;
                }
            }*/

            vg.setDoc(XMLDoc);
            // skip a long
            dis.ReadInt64();
            //Console.WriteLine(" l ==>" + l);
            dis.ReadInt64();
            //Console.WriteLine(" l ==>" + l);
            if (BitConverter.IsLittleEndian && endian == 0
                || BitConverter.IsLittleEndian == false && endian == 1)
            {
                // read vtd records
                int vtdSize = (int)dis.ReadInt64();
                while (vtdSize > 0)
                {
                    vg.VTDBuffer.append(dis.ReadInt64());
                    vtdSize--;
                }
                // read L1 LC records
                int l1Size = (int)dis.ReadInt64();
                while (l1Size > 0)
                {
                    vg.l1Buffer.append(dis.ReadInt64());
                    l1Size--;
                }
                // read L2 LC records
                int l2Size = (int)dis.ReadInt64();
                while (l2Size > 0)
                {
                    vg.l2Buffer.append(dis.ReadInt64());
                    l2Size--;
                }
                // read L3 LC records
                int l3Size = (int)dis.ReadInt64();
                if (vg.shallowDepth)
                {
                    if (intLongSwitch == 1)
                    {
                        //l3 uses ints
                        while (l3Size > 0)
                        {
                            vg.l3Buffer.append(dis.ReadInt32());
                            l3Size--;
                        }
                    }
                    else
                    {
                        while (l3Size > 0)
                        {
                            vg.l3Buffer.append((int)(dis.ReadInt64() >> 32));
                            l3Size--;
                        }
                    }
                }
                else
                {
                    while (l3Size > 0)
                    {
                        vg._l3Buffer.append(dis.ReadInt64());
                        l3Size--;
                    }

                    int l4Size = (int)dis.ReadInt64();
                    while (l4Size > 0)
                    {
                        vg._l4Buffer.append(dis.ReadInt64());
                        l4Size--;
                    }

                    int l5Size = (int)dis.ReadInt64();
                    if (intLongSwitch == 1)
                    {
                        while (l5Size > 0)
                        {
                            vg._l5Buffer.append(dis.ReadInt32());
                            l5Size--;
                        }
                    }
                    else
                    {
                        while (l5Size > 0)
                        {
                            vg._l5Buffer.append((int)(dis.ReadInt64() >> 32));
                            l5Size--;
                        }
                    }
                }
            }
            else
            {
                // read vtd records
                int vtdSize = (int)reverseLong(dis.ReadInt64());
                while (vtdSize > 0)
                {
                    vg.VTDBuffer.append(reverseLong(dis.ReadInt64()));
                    vtdSize--;
                }
                // read L1 LC records
                int l1Size = (int)reverseLong(dis.ReadInt64());
                while (l1Size > 0)
                {
                    vg.l1Buffer.append(reverseLong(dis.ReadInt64()));
                    l1Size--;
                }
                // read L2 LC records
                int l2Size = (int)reverseLong(dis.ReadInt64());
                while (l2Size > 0)
                {
                    vg.l2Buffer.append(reverseLong(dis.ReadInt64()));
                    l2Size--;
                }
                // read L3 LC records
                int l3Size = (int)reverseLong(dis.ReadInt64());
                if (vg.shallowDepth)
                {
                    if (intLongSwitch == 1)
                    {
                        //l3 uses ints
                        while (l3Size > 0)
                        {
                            vg.l3Buffer.append(reverseInt(dis.ReadInt32()));
                            l3Size--;
                        }
                    }
                    else
                    {
                        while (l3Size > 0)
                        {
                            vg.l3Buffer.append(reverseInt((int)(dis.ReadInt64() >> 32)));
                            l3Size--;
                        }
                    }
                }
                else
                {
                    while (l3Size > 0)
                    {
                        vg._l3Buffer.append(reverseLong(dis.ReadInt64()));
                        l3Size--;
                    }

                    int l4Size = (int)reverseLong(dis.ReadInt64());
                    {
                        vg._l4Buffer.append(reverseLong(dis.ReadInt64()));
                        l4Size--;
                    }

                    int l5Size = (int)reverseLong(dis.ReadInt64());
                    if (intLongSwitch == 1)
                    {
                        //l3 uses ints
                        while (l5Size > 0)
                        {
                            vg._l5Buffer.append(reverseInt(dis.ReadInt32()));
                            l5Size--;
                        }
                    }
                    else
                    {
                        while (l5Size > 0)
                        {
                            vg._l5Buffer.append(reverseInt((int)(dis.ReadInt64() >> 32)));
                            l5Size--;
                        }
                    }
                }
            }
        }
Esempio n. 51
0
        public void Populate(int iOffset, bool useMemoryStream)
        {
            this.isNulledOutReflexive = false;
            System.IO.BinaryReader BR = new System.IO.BinaryReader(meta.MS);
            //set offsets
            BR.BaseStream.Position = iOffset + this.chunkOffset;
            this.offsetInMap = iOffset + this.chunkOffset;
            // If we need to read / save tag info directly to file...
            if (!useMemoryStream)
            {
                map.OpenMap(MapTypes.Internal);
                BR = map.BR;
                BR.BaseStream.Position = this.offsetInMap;
            }
            else
                this.offsetInMap += meta.offset;

            switch (this.enumType)
            {
                case 8:
                    {
                        this.value = (int)BR.ReadByte();
                        break;
                    }
                case 16:
                    {
                        this.value = (int)BR.ReadInt16();
                        break;
                    }
                case 32:
                    {
                        this.value = BR.ReadInt32();
                        break;
                    }

            }
            // ...and then close the file once we are done!
            if (!useMemoryStream)
                map.CloseMap();
            UpdateComboBox();
        }
Esempio n. 52
0
        public override void Read(System.IO.BinaryReader br, int len, int[] blockSizes = null)
        {
            long p = br.BaseStream.Position;

            int OutlineID = br.ReadInt32();

            Debug.WriteLine(String.Format("Outline ID:{0:d}", OutlineID));

            int lt = 0x4, ct = 0x6, jt = 0x8, lw = 0xc, st = 0x10, ang = 0x14, varo = 0x1c, lc = 0x4c, dash = 0x68, arrw = 0x80;

            if (Parent.Version >= 13)
            {
                int flag = br.ReadInt32();
                int off  = 0;
                if (flag == 5)
                {
                    off = 107;
                }
                else if (Parent.Version >= 16)
                {
                    off = 51;
                }
                lt   = 0x18 + off;
                ct   = 0x1a + off;
                jt   = 0x1c + off;
                lw   = 0x1e + off;
                st   = 0x22 + off;
                ang  = 0x24 + off;
                varo = 0x28 + off;
                lc   = 0x58 + off;
                dash = 0x74 + off;
                arrw = 0x8a + off;
            }
            else if (Parent.Version < 6)
            {
                lw   = 0xa;
                st   = 0xc;
                ang  = 0xe;
                lc   = 0x10;
                dash = 0x26;
            }
            br.BaseStream.Position = p + lt;
            short  ltype = br.ReadInt16();
            String ltxt  = "Non-scalable";

            if ((ltype & 0x20) == 0x20)
            {
                ltxt = "Scalable";
            }
            if ((ltype & 0x10) == 0x10)
            {
                ltxt += ", Behind fill";
            }
            if ((ltype & 0x80) == 0x80)
            {
                ltxt += ", Share Attrs";
            }
            if ((ltype & 0x4) == 0x4)
            {
                ltxt += ", Dashed";
            }

            Debug.WriteLine(String.Format("Line Type {0:d} {1:s}", ltype, ltxt));
            br.BaseStream.Position = p + ct;
            Debug.WriteLine(String.Format("Caps Type {0:d}", br.ReadByte()));
            br.BaseStream.Position = p + jt;
            Debug.WriteLine(String.Format("Join Type {0:d}", br.ReadByte()));
            br.BaseStream.Position = p + lw;
            Debug.WriteLine(String.Format("LineWidth {0:f}", br.ReadInt32() / 10000.0));

            br.BaseStream.Position = p;
            base.Read(br, len, blockSizes);
        }
Esempio n. 53
0
 static void SetPalette(string filename)
 {
     using (System.IO.BinaryReader palette = new System.IO.BinaryReader(System.IO.File.OpenRead(filename))) {
         for (int p = 0; p < 256; p++) {
             colorPalette.Entries[p] = Color.FromArgb(palette.ReadByte(), palette.ReadByte(), palette.ReadByte());
         }
     }
 }
Esempio n. 54
0
        public static void vglLoadDDS(string filename, ref vglImageData image)
        {
            System.IO.FileStream   f  = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.BinaryReader br = new System.IO.BinaryReader(f);

            //DDS_FILE_HEADER file_header = { 0, };
            DDS_FILE_HEADER file_header = new DDS_FILE_HEADER();

            //fread(&file_header, sizeof(file_header.magic) + sizeof(file_header.std_header), 1, f);
            file_header = br.ReadStruct <DDS_FILE_HEADER>();
            file_header.dxt10_header.format     = 0;
            file_header.dxt10_header.array_size = 0;
            f.Position = Marshal.SizeOf(file_header.magic) + Marshal.SizeOf(file_header.std_header);

            if (file_header.magic != DDSSignal.DDS_MAGIC)
            {
                goto done_close_file;
            }

            if (file_header.std_header.ddspf.dwFourCC == DDSSignal.DDS_FOURCC_DX10)
            {
                //fread(&file_header.dxt10_header, sizeof(file_header.dxt10_header), 1, f);
                f.Position = Marshal.SizeOf(file_header.magic) + Marshal.SizeOf(file_header.std_header);
                file_header.dxt10_header = br.ReadStruct <DDS_HEADER_DXT10>();
            }

            if (!vgl_DDSHeaderToImageDataHeader(ref file_header, ref image))
            {
                goto done_close_file;
            }

            image.target = vgl_GetTargetFromDDSHeader(ref file_header);

            if (image.target == GL.GL_NONE)
            {
                goto done_close_file;
            }

            //int current_pos = ftell(f);
            long current_pos = f.Position;
            long file_size   = f.Length;

            image.totalDataSize = (int)(file_size - current_pos);
            var data = new UnmanagedArray <byte>(image.totalDataSize);

            if (image.mip == null)
            {
                image.mip = new vglImageMipData[vermilion.MAX_TEXTURE_MIPS];
            }
            image.mip[0].data = data.Header;
            //image.mip[0].data = new byte[image.totalDataSize];

            //fread(image.mip[0].data, file_size - current_pos, 1, f);
            for (int i = 0; i < image.totalDataSize; i++)
            {
                data[i] = br.ReadByte();
            }

            int    level;
            IntPtr ptr = image.mip[0].data;

            uint width  = file_header.std_header.width;
            uint height = file_header.std_header.height;
            uint depth  = file_header.std_header.depth;

            image.sliceStride = 0;

            if (image.mipLevels == 0)
            {
                image.mipLevels = 1;
            }

            for (level = 0; level < image.mipLevels; ++level)
            {
                image.mip[level].data      = ptr;
                image.mip[level].width     = (int)width;
                image.mip[level].height    = (int)height;
                image.mip[level].depth     = (int)depth;
                image.mip[level].mipStride = (int)(vgl_GetDDSStride(ref file_header, (int)width) * height);
                image.sliceStride         += image.mip[level].mipStride;
                ptr     += image.mip[level].mipStride;
                width  >>= 1;
                height >>= 1;
                depth  >>= 1;
            }

done_close_file:
            f.Close();
        }
Esempio n. 55
0
 public byte getByte()
 {
     return(reader.ReadByte());
 }
Esempio n. 56
0
        private static System.Security.Cryptography.RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
        {
            byte[] MODULUS, E, D, P, Q, DP, DQ, IQ;

            // ---------  Set up stream to decode the asn.1 encoded RSA private key  ------
            System.IO.MemoryStream mem  = new System.IO.MemoryStream(privkey);
            System.IO.BinaryReader binr = new System.IO.BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading
            byte   bt       = 0;
            ushort twobytes = 0;
            int    elems    = 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);
                }

                twobytes = binr.ReadUInt16();
                if (twobytes != 0x0102) //version number
                {
                    return(null);
                }
                bt = binr.ReadByte();
                if (bt != 0x00)
                {
                    return(null);
                }

                //------  all private key components are Integer sequences ----
                elems   = GetIntegerSize(binr);
                MODULUS = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                E     = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                D     = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                P     = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                Q     = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                DP    = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                DQ    = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                IQ    = binr.ReadBytes(elems);

                //  System.Security.Cryptography.RSA.Create();

                // ------- create RSACryptoServiceProvider instance and initialize with public key -----
                System.Security.Cryptography.RSACryptoServiceProvider RSA       = new System.Security.Cryptography.RSACryptoServiceProvider();
                System.Security.Cryptography.RSAParameters            RSAparams = new System.Security.Cryptography.RSAParameters();
                RSAparams.Modulus  = MODULUS;
                RSAparams.Exponent = E;
                RSAparams.D        = D;
                RSAparams.P        = P;
                RSAparams.Q        = Q;
                RSAparams.DP       = DP;
                RSAparams.DQ       = DQ;
                RSAparams.InverseQ = IQ;
                RSA.ImportParameters(RSAparams);
                return(RSA);
            }
            catch (Exception)
            {
                return(null);
            }
            finally
            {
                binr.Close();
            }
        }
Esempio n. 57
0
        /// <summary>
        /// 根据文件的前2个字节进行判断文件类型是不是图片
        /// </summary>
        /// <param name="hpf"></param>
        /// <returns></returns>
        public bool CheckUploadByTwoByteIsImg(HttpPostedFile hpf)
        {
            System.IO.FileStream fs = new System.IO.FileStream(hpf.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
            string fileclass = "";
            byte buffer;
            try
            {
                buffer = r.ReadByte();
                fileclass = buffer.ToString();
                buffer = r.ReadByte();
                fileclass += buffer.ToString();

            }
            catch
            {

            }
            r.Close();
            fs.Close();
            //说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
            if (fileclass == "255216" || fileclass == "7173" || fileclass == "13780")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
Esempio n. 58
0
        private static System.Security.Cryptography.RSACryptoServiceProvider DecodePublicKey(byte[] x509key)
        {
            // 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];
            // ---------  Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob  ------
            System.IO.MemoryStream mem  = new System.IO.MemoryStream(x509key);
            System.IO.BinaryReader binr = new System.IO.BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading
            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 (!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 }; //reverse byte order since asn.1 key uses big endian order
                int    modsize = BitConverter.ToInt32(modint, 0);

                byte firstbyte = binr.ReadByte();
                binr.BaseStream.Seek(-1, System.IO.SeekOrigin.Current);

                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(); // should only need one byte for actual exponent data (for all useful values)
                byte[] exponent = binr.ReadBytes(expbytes);


                // ------- create RSACryptoServiceProvider instance and initialize with public key -----
                System.Security.Cryptography.RSACryptoServiceProvider RSA        = new System.Security.Cryptography.RSACryptoServiceProvider();
                System.Security.Cryptography.RSAParameters            RSAKeyInfo = new System.Security.Cryptography.RSAParameters();
                RSAKeyInfo.Modulus  = modulus;
                RSAKeyInfo.Exponent = exponent;
                RSA.ImportParameters(RSAKeyInfo);
                return(RSA);
            }
            catch (Exception)
            {
                return(null);
            }

            finally
            {
                binr.Close();
            }
        }
Esempio n. 59
0
        public static void vglLoadDDS(string filename, ref vglImageData image)
        {
            System.IO.FileStream f = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.BinaryReader br = new System.IO.BinaryReader(f);

            //DDS_FILE_HEADER file_header = { 0, };
            DDS_FILE_HEADER file_header = new DDS_FILE_HEADER();

            //fread(&file_header, sizeof(file_header.magic) + sizeof(file_header.std_header), 1, f);
            file_header = br.ReadStruct<DDS_FILE_HEADER>();
            file_header.dxt10_header.format = 0;
            file_header.dxt10_header.array_size = 0;
            f.Position = Marshal.SizeOf(file_header.magic) + Marshal.SizeOf(file_header.std_header);

            if (file_header.magic != DDSSignal.DDS_MAGIC)
            {
                goto done_close_file;
            }

            if (file_header.std_header.ddspf.dwFourCC == DDSSignal.DDS_FOURCC_DX10)
            {
                //fread(&file_header.dxt10_header, sizeof(file_header.dxt10_header), 1, f);
                f.Position = Marshal.SizeOf(file_header.magic) + Marshal.SizeOf(file_header.std_header);
                file_header.dxt10_header = br.ReadStruct<DDS_HEADER_DXT10>();
            }

            if (!vgl_DDSHeaderToImageDataHeader(ref file_header, ref image))
                goto done_close_file;

            image.target = vgl_GetTargetFromDDSHeader(ref file_header);

            if (image.target == GL.GL_NONE)
                goto done_close_file;

            //int current_pos = ftell(f);
            long current_pos = f.Position;
            long file_size = f.Length;

            image.totalDataSize = (int)(file_size - current_pos);
            var data = new UnmanagedArray<byte>(image.totalDataSize);
            if (image.mip == null) { image.mip = new vglImageMipData[vermilion.MAX_TEXTURE_MIPS]; }
            image.mip[0].data = data.Header;
            //image.mip[0].data = new byte[image.totalDataSize];

            //fread(image.mip[0].data, file_size - current_pos, 1, f);
            for (int i = 0; i < image.totalDataSize; i++)
            {
                data[i] = br.ReadByte();
            }

            int level;
            IntPtr ptr = image.mip[0].data;

            uint width = file_header.std_header.width;
            uint height = file_header.std_header.height;
            uint depth = file_header.std_header.depth;

            image.sliceStride = 0;

            if (image.mipLevels == 0)
            {
                image.mipLevels = 1;
            }

            for (level = 0; level < image.mipLevels; ++level)
            {
                image.mip[level].data = ptr;
                image.mip[level].width = (int)width;
                image.mip[level].height = (int)height;
                image.mip[level].depth = (int)depth;
                image.mip[level].mipStride = (int)(vgl_GetDDSStride(ref file_header, (int)width) * height);
                image.sliceStride += image.mip[level].mipStride;
                ptr += image.mip[level].mipStride;
                width >>= 1;
                height >>= 1;
                depth >>= 1;
            }

        done_close_file:
            f.Close();
        }
Esempio n. 60
0
 internal void LoadState(System.IO.BinaryReader bin)
 {
     VClock              = bin.ReadInt32();
     HClock              = bin.ReadInt32();
     oddSwap             = bin.ReadBoolean();
     current_pixel       = bin.ReadInt32();
     temp                = bin.ReadInt32();
     temp_comparator     = bin.ReadInt32();
     bkg_pos             = bin.ReadInt32();
     spr_pos             = bin.ReadInt32();
     object0             = bin.ReadInt32();
     infront             = bin.ReadInt32();
     bkgPixel            = bin.ReadInt32();
     sprPixel            = bin.ReadInt32();
     bkg_fetch_address   = bin.ReadInt32();
     bkg_fetch_nametable = bin.ReadByte();
     bkg_fetch_attr      = bin.ReadByte();
     bkg_fetch_bit0      = bin.ReadByte();
     bkg_fetch_bit1      = bin.ReadByte();
     spr_fetch_address   = bin.ReadInt32();
     spr_fetch_bit0      = bin.ReadByte();
     spr_fetch_bit1      = bin.ReadByte();
     spr_fetch_attr      = bin.ReadByte();
     for (int i = 0; i < spr_zero_buffer.Length; i++)
     {
         spr_zero_buffer[i] = bin.ReadBoolean();
     }
     vram_temp                 = bin.ReadInt32();
     vram_address              = bin.ReadInt32();
     vram_address_temp_access  = bin.ReadInt32();
     vram_address_temp_access1 = bin.ReadInt32();
     vram_increament           = bin.ReadInt32();
     vram_flipflop             = bin.ReadBoolean();
     vram_fine                 = bin.ReadByte();
     reg2007buffer             = bin.ReadByte();
     bkg_enabled               = bin.ReadBoolean();
     bkg_clipped               = bin.ReadBoolean();
     bkg_patternAddress        = bin.ReadInt32();
     spr_enabled               = bin.ReadBoolean();
     spr_clipped               = bin.ReadBoolean();
     spr_patternAddress        = bin.ReadInt32();
     spr_size16                = bin.ReadInt32();
     spr_0Hit              = bin.ReadBoolean();
     spr_overflow          = bin.ReadBoolean();
     grayscale             = bin.ReadInt32();
     emphasis              = bin.ReadInt32();
     ppu_2002_temp         = bin.ReadByte();
     ppu_2004_temp         = bin.ReadByte();
     ppu_2007_temp         = bin.ReadByte();
     oam_address           = bin.ReadByte();
     oam_fetch_data        = bin.ReadByte();
     oam_evaluate_slot     = bin.ReadByte();
     oam_evaluate_count    = bin.ReadByte();
     oam_fetch_mode        = bin.ReadBoolean();
     oam_phase_index       = bin.ReadByte();
     spr_render_i          = bin.ReadInt32();
     bkg_render_i          = bin.ReadInt32();
     spr_evaluation_i      = bin.ReadInt32();
     spr_render_temp_pixel = bin.ReadInt32();
 }