ReadByte() public méthode

public ReadByte ( ) : int
Résultat int
        /// <summary>
        /// </summary>
        /// <param name="stream">
        /// </param>
        /// <returns>
        /// </returns>
        public static StatelData ReadFromStream(Stream stream)
        {
            StatelData statel = new StatelData();
            FlatIdentity fi = new FlatIdentity();
            fi.ReadFromStream(stream);
            statel.StatelIdentity = fi.Id;

            // Skip 4, is always 1?
            stream.ReadByte();
            stream.ReadByte();
            stream.ReadByte();
            stream.ReadByte();
            PFCoordHeading pfc = new PFCoordHeading();
            pfc.ReadFromStream(stream);

            statel.X = pfc.Coordinate.X;
            statel.Y = pfc.Coordinate.Y;
            statel.Z = pfc.Coordinate.Z;

            statel.HeadingX = pfc.Heading.X;
            statel.HeadingY = pfc.Heading.Y;
            statel.HeadingZ = pfc.Heading.Z;
            statel.HeadingW = pfc.Heading.W;

            statel.PlayfieldId = pfc.PlayfieldIdentity;

            BinaryReader br = new BinaryReader(stream);
            br.ReadInt32();
            statel.TemplateId = br.ReadInt32();
            int len2 = br.ReadInt32();
            byte[] HighLow = br.ReadBytes(len2);
            MemoryStream ms = new MemoryStream(HighLow);

            BinaryReader br2 = new BinaryReader(ms);
            br2.ReadBytes(8);
            int C1 = IPAddress.NetworkToHostOrder(br2.ReadInt32());
            Debug.Assert(C1 % 0x3f1 == 0, "Wrong 3f1 encountered... stop please");

            int evcount = IPAddress.NetworkToHostOrder(br2.ReadInt32());
            while (evcount > 0)
            {
                int dataType = IPAddress.NetworkToHostOrder(br2.ReadInt32());
                switch (dataType)
                {
                    case 2:
                        HLFlatEvent flatEvent = new HLFlatEvent();
                        flatEvent.ReadFromStream(ms);
                        statel.Events.Add(flatEvent.ToEvents());
                        break;
                    default:

                        // Console.WriteLine("DataType " + dataType + " found... stop please");
                        break;
                }

                evcount--;
            }

            return statel;
        }
Exemple #2
0
 public override ImageData Read(Stream stream, ImageMetaData info)
 {
     var pixels = new byte[info.Width*info.Height*4];
     stream.Position = 0x18;
     int dst = 0;
     for (uint y = 0; y < info.Height; ++y)
     {
         while (dst < pixels.Length)
         {
             int a = stream.ReadByte();
             if (-1 == a)
                 throw new EndOfStreamException();
             else if (0 == a)
             {
                 int count = stream.ReadByte();
                 if (-1 == count)
                     throw new EndOfStreamException();
                 else if (0 == count)
                     break;
                 dst += count * 4;
             }
             else
             {
                 stream.Read (pixels, dst, 3);
                 pixels[dst + 3] = (byte)a;
                 dst += 4;
             }
         }
     }
     return ImageData.Create (info, PixelFormats.Bgra32, null, pixels);
 }
Exemple #3
0
        public static RequestLine Parse(Stream stream)
        {
            int b = stream.ReadByte();
            while (b == CR || b == LF)
            {
                b = stream.ReadByte();
            }

            var bytes = new LinkedList<byte>();
            bytes.AddLast((byte)b);

            while (true)
            {
                b = stream.ReadByte();
                if (b == CR || b < 0)
                {
                    stream.ReadByte();
                    break;
                }
                bytes.AddLast((byte)b);
            }

            var text = Encoding.Default.GetString(bytes.ToArray());
            var parts = text.Split(' ');

            if (parts.Length == 3)
            {
                return new RequestLine(parts[0], parts[1], parts[2]);
            }

            throw new InvalidRequestException("Invalid Request Line.");
        }
Exemple #4
0
 private static Stream MoveStream(Stream stream)
 {
     // HACK: we need this to get the DeflateStream to read properly
     stream.ReadByte();
     stream.ReadByte();
     return stream;
 }
 public LogMessageAttributes(Stream stream)
 {
     Classification = (MessageClass)stream.ReadByte();
     Level = (MessageLevel)stream.ReadByte();
     MessageSuppression = (MessageSuppression)stream.ReadByte();
     Flags = (MessageFlags)stream.ReadByte();
 }
        public static long[] Match(Stream source, byte[] pattern, int[] next)
        {
            var result = new List<long>();
            int i = 0, k = 0;
            int currentData = source.ReadByte();
            while (i < source.Length && k < pattern.Length)
            {
                if (k == -1 || currentData == pattern[k])
                {
                    ++i;
                    ++k;
                    currentData = source.ReadByte();
                }
                else
                {
                    k = next[k];
                }

                if (k == pattern.Length)
                {
                    result.Add(i - pattern.Length);
                    k = 0;
                }
            }
            return result.ToArray();
        }
Exemple #7
0
        /// <summary>
        /// Inflate the token
        /// NOTE: This operation is not continuable and assumes that the entire token is available in the stream
        /// </summary>
        /// <param name="source">Stream to inflate the token from</param>
        /// <returns>TRUE if inflation is complete</returns>
        public virtual bool Inflate(Stream source)
        {
            // Read column number
            Number = (byte)source.ReadByte();

            // Update offset with the read size
            InflationSize += sizeof(byte);

            // Read table number
            TableNumber = (byte)source.ReadByte();

            // Update offset with the read size
            InflationSize += sizeof(byte);

            // Read status
            Status = (TDSColumnStatus)source.ReadByte();

            // Update offset with the read size
            InflationSize += sizeof(byte);

            // Check if status indicates the table name
            if ((Status & TDSColumnStatus.DifferentName) != 0)
            {
                // Read the length of the table name
                byte tableNameLength = (byte)source.ReadByte();

                // Read table name
                Name = TDSUtilities.ReadString(source, (ushort)(tableNameLength * 2));
            }

            return true;
        }
Exemple #8
0
        /// <summary>
        /// Decompress (if needed) the given stream.
        /// </summary>
        private static Stream Decompress(Stream stream)
        {
            if (stream.Length > 2)
            {
                var id1 = stream.ReadByte();
                var id2 = stream.ReadByte();
                stream.Position -= 2;

                if ((id1 == 0x1F) && (id2 == 0x8B))
                {
                    // GZIP compressed
                    var memStream = new MemoryStream();
                    using (var gzipStream = new GZipStream(stream, CompressionMode.Decompress))
                    {
                        var buffer = new byte[64 * 1024];
                        int len;
                        while ((len = gzipStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            memStream.Write(buffer, 0, len);
                        }
                    }
                    memStream.Position = 0;
                    return memStream;
                }
            }

            return stream;
        }
 private string ReadNextString(Stream reader, char marker)
 {
     StringBuilder sbuild = new StringBuilder();
     int i = reader.ReadByte();
     while (true)
     {
         if (i == -1 || i == marker)
             break;
         else if (i == '/')
         {
             i = reader.ReadByte();
             if (i == '/')
             {
                 do { i = reader.ReadByte(); } while (i != '\n' && i != -1);
                 i = reader.ReadByte();
             }
             else
                 sbuild.Append('/');
         }
         else
         {
             sbuild.Append((char)i);
             i = reader.ReadByte();
         }       
     }
     return sbuild.ToString();
 }
 internal IndefiniteLengthInputStream(
     Stream inStream)
     : base(inStream)
 {
     _b1 = inStream.ReadByte();
     _b2 = inStream.ReadByte();
     _eofReached = (_b2 < 0);
 }
 public static EulaVersion Read(Stream s)
 {
     var eula = new EulaVersion
     {
         Minor = (byte) s.ReadByte(),
         Major = (byte) s.ReadByte()
     };
     return eula;
 }
Exemple #12
0
 protected override void LoadBlockData(Map map, Stream stream) {
     for (int i = 0; i < map.Volume; i++) {
         map.Blocks[i] = (byte)stream.ReadByte();
         int msb = stream.ReadByte();
         if (msb == 1) {
             map.Blocks[i] = ReduxExtraMapping[map.Blocks[i]];
         }
     }
     map.ConvertBlockTypes(MCSharpMapping);
 }
Exemple #13
0
 public static int ToInt32(Stream stream, bool littleEndian)
 {
     return
         ToInt32(
             new[]
             {
                 (byte) stream.ReadByte(), (byte) stream.ReadByte(), (byte) stream.ReadByte(),
                 (byte) stream.ReadByte()
             }, 0, littleEndian);
 }
 public static PTableHeader FromStream(Stream stream)
 {
     var type = stream.ReadByte();
     if (type != (int) FileType.PTableFile)
         throw new CorruptIndexException("Corrupted PTable.", new InvalidFileException("Wrong type of PTable."));
     var version = stream.ReadByte();
     if (version == -1)
         throw new CorruptIndexException("Couldn't read version of PTable from header.", new InvalidFileException("Invalid PTable file."));
     return new PTableHeader((byte)version);
 }
        public Id3v2Tag Read(Stream mp3Stream)
        {
            Id3v2Tag tag;

            byte[] b = new byte[3];

            mp3Stream.Read(b, 0, b.Length);
            mp3Stream.Seek(0, SeekOrigin.Begin);

            string ID3 = new string(System.Text.Encoding.ASCII.GetChars(b));

            if (ID3 != "ID3") {
                throw new CannotReadException("Not an ID3 tag");
            }
            //Begins tag parsing ---------------------------------------------
            mp3Stream.Seek(3, SeekOrigin.Begin);
            //----------------------------------------------------------------------------
            //Version du tag ID3v2.xx.xx
            string versionHigh=mp3Stream.ReadByte() +"";
            string versionID3 =versionHigh+ "." + mp3Stream.ReadByte();
            //------------------------------------------------------------------------- ---
            //D?tection de certains flags (A COMPLETER)
            this.ID3Flags = ProcessID3Flags( (byte) mp3Stream.ReadByte() );
            //----------------------------------------------------------------------------

            //			On extrait la taille du tag ID3
            int tagSize = ReadSyncsafeInteger(mp3Stream);
            //System.err.println("TagSize: "+tagSize);

            //			------------------NEWNEWNWENENEWNENWEWN-------------------------------
            //Fill a byte buffer, then process according to correct version
            b = new byte[tagSize+2];
            mp3Stream.Read(b, 0, b.Length);
            ByteBuffer bb = new ByteBuffer(b);

            if (ID3Flags[0]==true) {
                //We have unsynchronization, first re-synchronize
                bb = synchronizer.synchronize(bb);
            }

            if(versionHigh == "2") {
                tag = v23.Read(bb, ID3Flags, Id3v2Tag.ID3V22);
            }
            else if(versionHigh == "3") {
                tag = v23.Read(bb, ID3Flags, Id3v2Tag.ID3V23);
            }
            else if(versionHigh == "4") {
                throw new CannotReadException("ID3v2 tag version "+ versionID3 + " not supported !");
            }
            else {
                throw new CannotReadException("ID3v2 tag version "+ versionID3 + " not supported !");
            }

            return tag;
        }
Exemple #16
0
    public void LoadPlanesData(System.IO.Stream fs)
    {
        var b = fs.ReadByte();

        IPlanableSupportClass.AddBlockRepresentation(this, basement, ref myBlock, false);
        if (b == 1)
        {
            upperPlane = Plane.Load(fs, this);
        }
        b = fs.ReadByte();
        if (b == 1)
        {
            bottomPlane = Plane.Load(fs, this);
        }
    }
        public void ReadStream(Stream stream)
        {
            while (true)
            {
                var c = stream.ReadByte();

                while (c != -1)
                {
                    lock (_buffer) _buffer.Enqueue((char) c);
                    c = stream.ReadByte();
                }

                Thread.Sleep(2);
            }
        }
        /// <summary>
        /// Inflate the option
        /// </summary>
        public bool Inflate(Stream source)
        {
            // Read pre-login packet token type
            Type = (TDSPreLoginTokenOptionType)source.ReadByte();

            // Check if terminator found
            if (Type != TDSPreLoginTokenOptionType.Terminator)
            {
                // Read token position and length
                Position = (ushort)((source.ReadByte() << 8) + source.ReadByte());
                Length = (ushort)((source.ReadByte() << 8) + source.ReadByte());
            }

            return true;
        }
        /// <summary>
        /// Checks that the actual stream has the same content as another one.
        /// </summary>
        /// <param name="check">The fluent check to be extended.</param>
        /// <param name="expected">The stream to compare content with.</param>
        /// <returns>A check link</returns>
        public static ICheckLink<ICheck<Stream>> HasSameSequenceOfBytesAs(this ICheck<Stream> check, Stream expected)
        {
            var checker = ExtensibilityHelper.ExtractChecker(check);
            var value = checker.Value;

            return checker.ExecuteCheck(
                () =>
                    {
                        if (value.Length != expected.Length)
                        {
                            var message = GenerateMessageWhenFullyDistinct(expected, checker, value);
                            throw new FluentCheckException(message.ToString());
                        }

                        // Keeps initial positions to be able to restore them after the check
                        var valueInitialPosition = value.Position;
                        var otherInitialPosition = expected.Position;

                        value.Seek(0, SeekOrigin.Begin);
                        expected.Seek(0, SeekOrigin.Begin);
                        while (value.Position < value.Length)
                        {
                            if (value.ReadByte() != expected.ReadByte())
                            {
                                var message = GenerateMessageWhenSameLenghtButDiffContent(expected, checker, value);
                                throw new FluentCheckException(message.ToString());
                            }
                        }

                        // Side-effect free. Restore initial positions of streams
                        value.Position = valueInitialPosition;
                        expected.Position = otherInitialPosition;
                    },
                BuildNegatedMessage(expected, value).ToString());
        }
Exemple #20
0
 public int readByte(Stream s)
 {
     int result = s.ReadByte();
     if (result == -1)
         throw new InvalidContainerException("Unexpected end of stream");
     return result;
 }
Exemple #21
0
        private static void ReadHeader(Stream stream, out ObjectType type, out int size)
        {
            size = 0;
            var typeCode = string.Empty;
            var sb = new StringBuilder();
            var inHeader = true;

            while (inHeader)
            {
                var c = (char)stream.ReadByte();
                switch (c)
                {
                    case ' ':
                        typeCode = sb.ToString();
                        sb.Clear();
                        continue;
                    case '\0':
                        size = int.Parse(sb.ToString());
                        sb.Clear();
                        inHeader = false;
                        continue;
                }
                sb.Append(c);
            }

            type = ObjectTypeFromString(typeCode);
        }
Exemple #22
0
    public void LoadPlanesData(System.IO.Stream fs)
    {
        int count = fs.ReadByte();

        if (count > 0)
        {
            var   pls = new Dictionary <byte, Plane>();
            Plane p;
            for (byte i = 0; i < count; i++)
            {
                p = Plane.Load(fs, this);
                if (p != null)
                {
                    pls.Add(p.faceIndex, p);
                }
            }
            if (pls.Count > 0)
            {
                planes = pls;
            }
            else
            {
                planes = null;
            }
        }
        else
        {
            planes = null;
        }
    }
        /// <summary>
        /// Read the raw data but don't interpret it
        /// </summary>
        protected byte[] InflateValue(Stream source)
        {
            // Read the next byte to check if length is DWORD
            int length = (int)source.ReadByte();

            // Update inflation size
            InflationSize += sizeof(byte);

            // Check
            if (length == 0xFF)
            {
                // Length is long
                length = TDSUtilities.ReadInt(source);

                // Update inflation size
                InflationSize += sizeof(int);
            }

            // Allocate a container
            byte[] value = new byte[length];

            // Read all bytes
            source.Read(value, 0, value.Length);

            // Update inflation size
            InflationSize += (uint)length;

            return value;
        }
        /*
        public bool Enable
        {
            get { return Flags.HasFlag(AgeRatingFlags.Enable); }
            set
            {
                if (value)
                    Flags |= AgeRatingFlags.Enable;
                else
                    Flags &= ~AgeRatingFlags.Enable;
            }
        }

        public bool AllAges
        {
            get { return Flags.HasFlag(AgeRatingFlags.AllAges); }
            set
            {
                if (value)
                    Flags |= AgeRatingFlags.AllAges;
                else
                    Flags &= ~AgeRatingFlags.AllAges;
            }
        }

        public bool RatingPending
        {
            get { return Flags.HasFlag(AgeRatingFlags.RatingPending); }
            set
            {
                if (value)
                    Flags |= AgeRatingFlags.RatingPending;
                else
                    Flags &= ~AgeRatingFlags.RatingPending;
            }
        }
        */

        public static AgeRating Read(Stream s)
        {
            return new AgeRating
            {
                Value = (byte) s.ReadByte()
            };
        }
        /// <summary>
        /// Reads stream to match it against a dictionary of all known units for an ingredient
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="matchdata"></param>
        /// <returns></returns>
        public bool Read(Stream stream, MatchData matchdata)
        {
            if (data == null)
            {
                data = new NumericVocab();
            }

            var matchFound = false;
            var buffer = string.Empty;
            var matchPos = stream.Position;
            int curByte;

            while ((curByte = stream.ReadByte()) >= 0)
            {
                buffer += (char)curByte;
                NumericNode node;
                var match = data.Parse(buffer, out node);
                if (match == MatchPrecision.None)
                {
                    stream.Seek(matchPos, SeekOrigin.Begin);
                    break;
                }

                if (match == MatchPrecision.Exact)
                {
                    matchPos = stream.Position;
                    matchFound = true;
                    matchdata.Amount = new Amount { SizeHigh = node.Value };
                }
            }

            return matchFound;
        }
 public override object GetValue(Stream inputStream)
 {
     var len = inputStream.ReadByte();
     var buffer = new byte[len];
     inputStream.Read(buffer, 0, len);
     return Encoding.GetEncoding("iso-8859-1").GetString(buffer);
 }
        /// <summary>
        /// Reads stream to match it against a dictionary of all known forms
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="matchdata"></param>
        /// <returns></returns>
        public bool Read(Stream stream, MatchData matchdata)
        {
            if (data == null)
            {
                data = new FormSynonyms();
            }

            matchdata.Form = null;
            var buffer = string.Empty;
            var matchPos = stream.Position;
            int curByte;

            while ((curByte = stream.ReadByte()) >= 0)
            {
                buffer += (char)curByte;
                FormNode node;
                var match = data.Parse(buffer, out node);
                if (match == MatchPrecision.None)
                {
                    break;
                }

                if (match == MatchPrecision.Exact)
                {
                    matchPos = stream.Position;
                    matchdata.Form = node;
                }
            }

            stream.Seek(matchPos, SeekOrigin.Begin);
            return matchdata.Form != null;
        }
		public override IGeometry Read(Stream stream)
		{
			using (BinaryReader reader1 = new BinaryReader(stream))
			{
				int srid = -1;
				try
				{
					srid = reader1.ReadInt32();
				}
				catch
				{
				}
				if (srid == 0)
				{
					srid = -1;
				}

				ByteOrder byteOrder = (ByteOrder)stream.ReadByte();
				BinaryReader reader2;
				if (byteOrder == ByteOrder.BigEndian)
				{
					reader2 = new BEBinaryReader(stream);
				}
				else
				{
					reader2 = new BinaryReader(stream);
				}
				using (reader2)
				{
					IGeometry geometry = Read(reader2);
					geometry.SRID = srid;
					return geometry;
				}
			}
		}
        internal IndefiniteLengthInputStream(
			Stream	inStream,
			int		limit)
            : base(inStream, limit)
        {
            _b1 = inStream.ReadByte();
            _b2 = inStream.ReadByte();

            if (_b2 < 0)
            {
                // Corrupted stream
                throw new EndOfStreamException();
            }

            CheckForEof();
        }
Exemple #30
0
		public bool Read(Id3Tag tag, Stream mp3Stream)
		{
			//Check wether the file contains an Id3v1 tag--------------------------------
			mp3Stream.Seek( -128 , SeekOrigin.End);
			
			byte[] b = new byte[3];
			mp3Stream.Read( b, 0, 3 );
			mp3Stream.Seek(0, SeekOrigin.Begin);
			string tagS = Encoding.ASCII.GetString(b);
			if(tagS != "TAG")
				return false;
			
			mp3Stream.Seek( - 128 + 3, SeekOrigin.End );
			//Parse the tag -)------------------------------------------------
			tag.AddTitle(Read(mp3Stream, 30));
			tag.AddArtist(Read(mp3Stream, 30));
			tag.AddAlbum(Read(mp3Stream, 30));
			//------------------------------------------------
			tag.AddYear(Read(mp3Stream, 4));
			tag.AddComment(Read(mp3Stream, 30));

			//string trackNumber;
			mp3Stream.Seek(- 2, SeekOrigin.Current);
			b = new byte[2];
			mp3Stream.Read(b, 0, 2);
			
			if (b[0] == 0)
				tag.AddTrack(b[1].ToString());

			byte genreByte = (byte) mp3Stream.ReadByte();
			mp3Stream.Seek(0, SeekOrigin.Begin);
			tag.AddGenre(TagGenres.Get(genreByte));

			return true;
		}
		public override IGeometry Read(Stream stream)
		{
			BinaryReader reader = null;
			ByteOrder byteOrder = (ByteOrder)stream.ReadByte();
			try
			{
				if (byteOrder == ByteOrder.BigEndian)
					reader = new BEBinaryReader(stream);
				else reader = new BinaryReader(stream);
				IGeometry geometry = Read(reader);
				int srid = -1;
				try
				{
					srid = reader.ReadInt32();
				}
				catch { }
				if (srid == 0)
					srid = -1;
				geometry.SRID = srid;
				return geometry;
			}
			finally
			{
				if (reader != null)
					reader.Close();
			}
		}
Exemple #32
0
        public D900CdrElement DecodeRecord(Stream asnStream, bool skipFillers)
        {
            TlvObject tlv;
            long offset = asnStream.Position;

            // Verify that the next byte - Billing Record Tag (0xE1)
            if (!skipFillers)
            {
                int b = asnStream.ReadByte();
                if (b != 0xE1)
                {
                    return null;
                }
                asnStream.Seek(-1, SeekOrigin.Current);
            }

            BerDecoderResult pr = DecodeTlv(asnStream, out tlv, ref offset, 0, byte.MaxValue);

            D900CdrElement record = null;

            if (pr == BerDecoderResult.Finished)
            {

                record = _tlvParser.ParseTlvObject(tlv); ;
            }

            return record;
        }
Exemple #33
0
    public static bool TryToLoadBlock(System.IO.Stream fs, Chunk c, ref Block b)
    {
        b = new Block(c, new ChunkPos(fs.ReadByte(), fs.ReadByte(), fs.ReadByte()));
        var csize = Chunk.chunkSize;

        if (b.pos.x >= csize | b.pos.y >= csize | b.pos.z >= csize)
        {
            Debug.Log("block load error - wrong position");
            GameMaster.LoadingFail();
            return(false);
        }
        if (fs.ReadByte() == 1)
        {
            b.extension = BlockExtension.Load(fs, b);
        }
        return(true);
    }
    public static Ship Load(System.IO.Stream fs, Dock d)
    {
        byte     slevel = (byte)fs.ReadByte();
        ShipType stype  = (ShipType)fs.ReadByte();
        Ship     s      = PoolMaster.current.GetShip(slevel, stype);

        s.level       = slevel;
        s.type        = stype;
        s.destination = d;
        bool isDocked = fs.ReadByte() == 1;

        if (s.destination != null && !s.destination.IsDestroyed())
        {
            s.docked = isDocked;
        }
        else
        {
            s.docked = false;
        }
        var data = new byte[34];

        fs.Read(data, 0, data.Length);
        if (s == null)
        {
            Debug.Log("ship loading error again");
            return(null);
        }
        s.transform.position = new Vector3(
            System.BitConverter.ToSingle(data, 0),
            System.BitConverter.ToSingle(data, 4),
            System.BitConverter.ToSingle(data, 8)
            );
        s.transform.rotation = new Quaternion(
            System.BitConverter.ToSingle(data, 12),
            System.BitConverter.ToSingle(data, 16),
            System.BitConverter.ToSingle(data, 20),
            System.BitConverter.ToSingle(data, 24)
            );
        s.speed       = System.BitConverter.ToSingle(data, 28);
        s.unloaded    = data[32] == 1;
        s.xAxisMoving = data[33] == 1;
        return(s);
    }
Exemple #35
0
        private void Net_OnReceived(System.IO.Stream data)
        {
            if (state == ServerState.LoginServer)
            {
                int    headl = data.ReadByte();
                byte[] head  = new byte[headl];
                data.Read(head, 0, headl);
                NetHead netHead  = NetHead.Parser.ParseFrom(head);
                byte[]  dataArea = new byte[netHead.DataLength];
                data.Read(dataArea, 0, netHead.DataLength);

                LC_Login lc_login = LC_Login.Parser.ParseFrom(dataArea);
                this.BeginInvoke(new LoginOk((LC_Login lgonInfo) =>
                {
                    m_data.Text        = "登录成功";
                    m_managerIp.Text   = lgonInfo.ManagerIp;
                    m_managerport.Text = lgonInfo.ManagerPort.ToString();
                    m_Managerkey.Text  = lgonInfo.Key;
                    m_uidlabal.Text    = lc_login.Uid.ToString();
                }
                                             ), lc_login);
            }
            else if (state == ServerState.ManagerServer)
            {
                int    headl = data.ReadByte();
                byte[] head  = new byte[headl];
                data.Read(head, 0, headl);
                NetHead netHead  = NetHead.Parser.ParseFrom(head);
                byte[]  dataArea = new byte[netHead.DataLength];
                data.Read(dataArea, 0, netHead.DataLength);

                MC_Login lc_login = MC_Login.Parser.ParseFrom(dataArea);
                this.BeginInvoke(new LoginMOk((MC_Login lgonInfo) =>
                {
                    m_data.Text           = "登录成功";
                    m_gameserverip.Text   = lgonInfo.GameIp;
                    m_gameserverPort.Text = lgonInfo.GamePort.ToString();
                    m_gameserverkey.Text  = lgonInfo.Key;
                }
                                              ), lc_login);
            }
        }
Exemple #36
0
        public override void GetData(
            System.IO.Stream source, int rowPitch, int slicePitch,
            Vector4sb[] destination, int index, int width, int height,
            Boxi sourceBoxi, Point3i destinationPoint)
        {
            //seek to start
            source.Seek(
                sourceBoxi.X * 4 + sourceBoxi.Y * rowPitch + sourceBoxi.Z * slicePitch,
                System.IO.SeekOrigin.Current);

            for (int z = 0; z < sourceBoxi.Depth; ++z)
            {
                int zindex = index + (destinationPoint.Z + z) * (height * width);

                for (int y = 0; y < sourceBoxi.Height; ++y)
                {
                    int xyindex = destinationPoint.X + (destinationPoint.Y + y) * width + zindex;

                    //write scan line
                    for (int x = 0; x < sourceBoxi.Width; ++x)
                    {
                        int r = source.ReadByte();
                        int g = source.ReadByte();
                        int b = source.ReadByte();
                        int a = source.ReadByte();

                        if ((r | g | b | a) < 0)
                        {
                            throw new System.IO.EndOfStreamException();
                        }

                        destination[xyindex++] = new Vector4sb((sbyte)r, (sbyte)g, (sbyte)b, (sbyte)a);
                    }

                    //seek to next scan line
                    source.Seek(rowPitch - sourceBoxi.Width * 4, System.IO.SeekOrigin.Current);
                }

                //seek to next scan slice
                source.Seek(slicePitch - sourceBoxi.Height * rowPitch, System.IO.SeekOrigin.Current);
            }
        }
Exemple #37
0
        /// <summary>
        /// ConvertStreamToByteBuffer:把给定的文件流转换为二进制字节数组。
        /// </summary>
        /// <param name="theStream"></param>
        /// <returns></returns>
        public static byte[] ConvertStreamToByteBuffer(System.IO.Stream theStream)
        {
            int b1;

            System.IO.MemoryStream tempStream = new System.IO.MemoryStream();
            while ((b1 = theStream.ReadByte()) != -1)
            {
                tempStream.WriteByte(((byte)b1));
            }
            return(tempStream.ToArray());
        }
Exemple #38
0
        public static Task <(bool success, byte[] data)> TryReadToEnd(this System.IO.Stream stream)
        {
            long originalPosition = 0;

            if (stream.CanSeek)
            {
                originalPosition = stream.Position;
                stream.Position  = 0;
            }

            try {
                byte[] readBuffer = new byte[4096];

                int totalBytesRead = 0;
                int bytesRead;

                while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
                {
                    totalBytesRead += bytesRead;

                    if (totalBytesRead == readBuffer.Length)
                    {
                        int nextByte = stream.ReadByte();
                        if (nextByte != -1)
                        {
                            byte[] temp = new byte[readBuffer.Length * 2];
                            Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
                            Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
                            readBuffer = temp;
                            totalBytesRead++;
                        }
                    }

                    //detect overflow
                    if (totalBytesRead > int.MaxValue || totalBytesRead < 0)
                    {
                        return(Task.FromResult((false, (byte[])null)));
                    }
                }

                byte[] data = readBuffer;
                if (readBuffer.Length != totalBytesRead)
                {
                    data = new byte[totalBytesRead];
                    Buffer.BlockCopy(readBuffer, 0, data, 0, totalBytesRead);
                }
                return(Task.FromResult((true, data)));
            } finally {
                if (stream.CanSeek)
                {
                    stream.Position = originalPosition;
                }
            }
        }
        private static string ReadCStr(System.IO.Stream src)
        {
            StringBuilder builder = new StringBuilder();
            int           i       = 0;

            while ((i = src.ReadByte()) > 0)
            {
                builder.Append((char)i);
            }
            return(builder.ToString());
        }
Exemple #40
0
        //private DataRow[] PrepDataArrForUL(int nReg)
        //{
        //    int nRet = AppC.RC_OK;
        //    string sRf = "";
        //    DataRow[] ret = null;

        //    if (nReg == AppC.UPL_CUR)
        //    {
        //        if ((int)xCDoc.drCurRow["SOURCE"] == NSI.DOCSRC_UPLD)
        //        {
        //            string sErr = "Уже выгружен!";
        //            DialogResult dr;
        //            dr = MessageBox.Show("Отменить выгрузку (Enter)?\r\n (ESC) - выгрузить повторно",
        //            sErr,
        //            MessageBoxButtons.OKCancel, MessageBoxIcon.Question,
        //            MessageBoxDefaultButton.Button1);
        //            if (dr == DialogResult.OK)
        //            {
        //                nRet = AppC.RC_CANCEL;
        //            }
        //            else
        //                nRet = AppC.RC_OK;
        //        }
        //        if (nRet == AppC.RC_OK)
        //        {
        //            ret = new DataRow[] { xCDoc.drCurRow };
        //        }
        //    }
        //    else if (nReg == AppC.UPL_ALL)
        //    {
        //        // фильтр - текущий для Grid документов + невыгруженные
        //        sRf = xNSI.DT[NSI.TBD_DOC].dt.DefaultView.RowFilter;
        //        if (sRf != "")
        //        {
        //            sRf = "(" + sRf + ")AND";
        //        }
        //        sRf += String.Format("(SOURCE<>{0})", NSI.DOCSRC_UPLD);
        //        ret = (DataRow[])PrepForAll(sRf, false);
        //    }
        //    else if (nReg == AppC.UPL_FLT)
        //    {
        //        //sRf = FiltForDoc(xCUpLoad.SetFiltInRow(xNSI));
        //        sRf = xCUpLoad.SetFiltInRow();
        //        ret = (DataRow[])PrepForAll(sRf, false);
        //    }
        //    return (ret);
        //}



        // формирование DataSet для отгрузки данных
        //private DataSet PrepDataSetForUL(int nReg)
        //{
        //    int nRet = AppC.RC_OK;
        //    string sRf = "";
        //    DataSet ret = null;

        //    if (nReg == AppC.UPL_CUR)
        //    {
        //        if ((int)xCDoc.drCurRow["SOURCE"] == NSI.DOCSRC_UPLD)
        //        {
        //            string sErr = "Уже выгружен!";
        //            DialogResult dr;
        //            dr = MessageBox.Show("Отменить выгрузку (Enter)?\r\n (ESC) - выгрузить повторно",
        //            sErr,
        //            MessageBoxButtons.OKCancel, MessageBoxIcon.Question,
        //            MessageBoxDefaultButton.Button1);
        //            if (dr == DialogResult.OK)
        //            {
        //                nRet = AppC.RC_CANCEL;
        //            }
        //            else
        //                nRet = AppC.RC_OK;
        //        }
        //        if (nRet == AppC.RC_OK)
        //        {
        //            DataRow[] drA = { xCDoc.drCurRow };
        //            ret = xNSI.MakeWorkDataSet(xNSI.DT[NSI.TBD_DOC].dt, xNSI.DT[NSI.I_TFAKT].dt, drA);
        //        }
        //    }
        //    else if (nReg == AppC.UPL_ALL)
        //    {
        //        // фильтр - текущий для Grid документов + невыгруженные
        //        sRf = xNSI.DT[NSI.TBD_DOC].dt.DefaultView.RowFilter;
        //        if (sRf != "")
        //        {
        //            sRf = "(" + sRf + ")AND";
        //        }
        //        sRf += String.Format("(SOURCE<>{0})", NSI.DOCSRC_UPLD);
        //        ret = (DataSet)PrepForAll(sRf, true);
        //    }
        //    else if (nReg == AppC.UPL_FLT)
        //    {
        //        //sRf = FiltForDoc(xCUpLoad.SetFiltInRow(xNSI));
        //        sRf = xCUpLoad.SetFiltInRow();
        //        ret = (DataSet)PrepForAll(sRf, true);
        //    }
        //    return (ret);
        //}

        //private object PrepForAll(string sRf, bool bNeedDataSet)
        //{
        //    object ret = null;

        //    // сортировка - ???
        //    string sSort = "";

        //    // все неотгруженные документы
        //    DataView dv = new DataView(xNSI.DT[NSI.TBD_DOC].dt, sRf, sSort, DataViewRowState.CurrentRows);
        //    DataRow[] drA = new DataRow[dv.Count];
        //    xCUpLoad.naComms = new List<int>();
        //    for (int i = 0; i < dv.Count; i++)
        //    {
        //        drA.SetValue(dv[i].Row, i);
        //        xCUpLoad.naComms.Add( (int)drA[i]["TD"]);

        //    }
        //    if (drA.Length > 0)
        //    {
        //            ret = drA;
        //    }
        //    return (ret);

        //}



        // сохранение документов в XML

/*
 *      private string UpLoadXML(int nComm)
 *      {
 *          int i,
 *              nCommLen = 0;
 *          byte[] baCom,
 *              baAns;
 *          string sC,
 *              sErr = "";
 *          DataSet dsTrans;
 *          DataRow[] drAUpL = null;
 *          Dictionary<string, string> aComm;
 *          System.IO.Stream stm;
 *
 *          byte[] baBuf = new byte[1024];
 *          try
 *          {
 *
 *              //dsTrans = PrepDataSetForUL(xCUpLoad.ilUpLoad.CurReg);
 *              //sErr = "(" + tSrvParServer.Text + ")Ошибка передачи - ";
 *
 *              drAUpL = PrepDataArrForUL(xCUpLoad.ilUpLoad.CurReg);
 *              if (drAUpL != null)
 *              {
 *                  baCom = SetUpLoadCommand(nComm, "", "");
 *
 *                  for (i = 0; i < drAUpL.Length; i++)
 *                  {
 *                      ssWrite = new SocketStream(tSrvParServer.Text, int.Parse(tSrvParServPort.Text));
 *                      stm = ssWrite.Connect();
 *
 *                      dsTrans = xNSI.MakeWorkDataSet(xNSI.DT[NSI.TBD_DOC].dt,
 *                                xNSI.DT[NSI.I_TFAKT].dt, new DataRow[] {drAUpL[i]});
 *
 *
 *                      stm.Write(baCom, 0, baCom.Length);
 *                      stm.Write(AppC.baTermCom, 0, AppC.baTermCom.Length);
 *
 *                      dsTrans.WriteXml(stm, XmlWriteMode.IgnoreSchema);
 *
 *                      stm.Write(AppC.baTermMsg, 0, AppC.baTermMsg.Length);
 *
 *                      //nRec = stm.Read(baBuf, 0, baBuf.Length);
 *
 *
 *                      nCommLen = 0;
 *                      baAns = ReadAnswerCommand(stm, ref nCommLen);
 *                      stm.Close();
 *                      ssWrite.Disconnect();
 *
 *                      sC = Encoding.UTF8.GetString(baAns, 0, nCommLen - AppC.baTermCom.Length);
 *                      aComm = SrvCommParse(sC);
 *
 *                      if (aComm["COM"] == AppC.saComms[nComm])
 *                      {
 *                          if (int.Parse(aComm["RET"]) == 0)
 *                          {
 *                              xNSI.SetRecState(dsTrans);
 *                              if ((i + 1) >= drAUpL.Length)
 *                                  sErr += "OK - Передача завершена";
 *
 *                          }
 *                          else
 *                          {
 *                              sErr += drAUpL[i]["KEKS"].ToString() + "-" + aComm["MSG"] + "\n";
 *                          }
 *                      }
 *
 *                  }
 *              }
 *              else
 *              {
 *                  sErr = "Нет данных для передачи";
 *              }
 *          }
 *          catch (Exception ex)
 *          {
 *              sErr = "(" + tSrvParServer.Text + ")Ошибка передачи";
 *              //sErr = ex.Message;
 *          }
 *          //MessageBox.Show(sErr, sRez);
 *          return (sErr);
 *      }
 */


        //private string UpLoadDoc(int nComm, ref int nR)
        //{
        //    int i,
        //        nRet = AppC.RC_OK;
        //    string sErr = "";
        //    DataRow[] drAUpL = null;

        //    try
        //    {
        //        drAUpL = PrepDataArrForUL(xCUpLoad.ilUpLoad.CurReg);
        //        if (drAUpL != null)
        //        {
        //            LoadFromSrv dgL = null;
        //            for (i = 0; i < drAUpL.Length; i++)
        //            {
        //                xCUpLoad.xCur = new CurDoc(AppC.UPL_CUR);
        //                xCUpLoad.xCur.drCurRow = drAUpL[i];
        //                xNSI.InitCurDoc(xCUpLoad.xCur);
        //                //tbPanP1.Text = xCUpLoad.xCur.xDocP.sNomDoc;
        //                //tbPanP1.Refresh();
        //                xFPan.UpdateReg(xCUpLoad.xCur.xDocP.sNomDoc);
        //                sErr = ExchgSrv(nComm, "", "", dgL, null, ref nRet);
        //                if (nRet != AppC.RC_OK)
        //                    break;
        //            }
        //            sErr += "(" + drAUpL.Length.ToString() + ")";
        //        }
        //        else
        //        {
        //            nRet = AppC.RC_NODATA;
        //            sErr = "Нет данных для передачи";
        //        }
        //    }
        //    catch (Exception)
        //    {
        //        nRet = AppC.RC_NODATA;
        //        sErr = "Ошибка подготовки";
        //    }
        //    nR = nRet;
        //    return (sErr);
        //}

        //private string FiltForDoc(DataRow drZ)
        //{
        //    int n;
        //    string s;

        //    string sF = String.Format("(TD={0}) AND (DT={1}) AND (SYSN={2})", drZ["TD"], drZ["DT"], drZ["SYSN"]);


        //    s = "AND(ISNULL(KPP1,-1)=-1)";
        //    try
        //    {
        //        n = (int)drZ["KPP1"];
        //        if (n > 0)
        //        {
        //            s = "AND(KPP1=" + n.ToString() + ")";
        //        }
        //        else
        //            drZ["KPP1"] = System.DBNull.Value;
        //    }
        //    catch { s = ""; }
        //    finally
        //    {
        //        sF += s;
        //    }

        //    s = "AND(ISNULL(NUCH,-1)=-1)";
        //    try
        //    {
        //        n = (int)drZ["NUCH"];
        //        if (n > 0)
        //        {
        //            s = "AND(NUCH=" + n.ToString() + ")";
        //        }
        //        else
        //            drZ["NUCH"] = System.DBNull.Value;
        //    }
        //    catch { s = ""; }
        //    finally
        //    {
        //        sF += s;
        //    }

        //    return ("(" + sF + ")");
        //}



        // чтение ответа
        //private byte[] ReadAnswerCommand(System.IO.Stream stm, ref int nLen)
        //{
        //    int i, n1Byte;
        //    bool bEnd = false;
        //    byte[] baCom = new byte[1024];
        //    nLen = 0;
        //    i = 0;
        //    try
        //    {
        //        n1Byte = stm.ReadByte();
        //        while ((n1Byte != -1) && (bEnd == false))
        //        {
        //            i++;
        //            baCom[i - 1] = (byte)n1Byte;
        //            bEnd = false;
        //            if ((i >= AppC.baTermCom.Length) && (baCom[i - 1] == AppC.baTermCom[AppC.baTermCom.Length - 1]))
        //            {
        //                bEnd = true;
        //                for (int j = 0; j < AppC.baTermCom.Length; j++)
        //                {
        //                    if (baCom[i - 1 - j] != AppC.baTermCom[AppC.baTermCom.Length - 1 - j])
        //                    {
        //                        bEnd = false;
        //                        break;
        //                    }
        //                }
        //            }
        //            if (bEnd != true)
        //                n1Byte = stm.ReadByte();
        //        }
        //        if (bEnd == true)
        //            nLen = i;

        //    }
        //    catch { }
        //    return (baCom);
        //}



        // обмен данными с сервером в формате XML
        // nCom - номер команды
        // sPar1



        // чтение ответа
        private byte[] ReadAnswerCommand(System.IO.Stream stm, ref int nLen)
        {
            int  i, n1Byte;
            bool bEnd = false;

            byte[] baCom = new byte[1024];
            nLen = 0;
            i    = 0;
            try
            {
                n1Byte = stm.ReadByte();
                while ((n1Byte != -1) && (bEnd == false))
                {
                    i++;
                    baCom[i - 1] = (byte)n1Byte;
                    bEnd         = false;
                    if ((i >= AppC.baTermCom.Length) && (baCom[i - 1] == AppC.baTermCom[AppC.baTermCom.Length - 1]))
                    {
                        bEnd = true;
                        for (int j = 0; j < AppC.baTermCom.Length; j++)
                        {
                            if (baCom[i - 1 - j] != AppC.baTermCom[AppC.baTermCom.Length - 1 - j])
                            {
                                bEnd = false;
                                break;
                            }
                        }
                    }
                    if (bEnd != true)
                    {
                        n1Byte = stm.ReadByte();
                    }
                }
                if (bEnd == true)
                {
                    nLen = i;
                }
            }
            catch { }
            return(baCom);
        }
Exemple #41
0
        public byte[] ReadToEnd(System.IO.Stream stream)
        {
            long originalPosition = 0;

            if (stream.CanSeek)
            {
                originalPosition = stream.Position;
                stream.Position  = 0;
            }

            try
            {
                byte[] readBuffer = new byte[4096];

                int totalBytesRead = 0;
                int bytesRead;

                while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
                {
                    totalBytesRead += bytesRead;

                    if (totalBytesRead == readBuffer.Length)
                    {
                        int nextByte = stream.ReadByte();
                        if (nextByte != -1)
                        {
                            byte[] temp = new byte[readBuffer.Length * 2];
                            Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
                            Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
                            readBuffer = temp;
                            totalBytesRead++;
                        }
                    }
                }

                byte[] buffer = readBuffer;
                if (readBuffer.Length != totalBytesRead)
                {
                    buffer = new byte[totalBytesRead];
                    Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
                }

                var returbuff = App.ResizeImageAndroid(buffer, 200, 200);
                return(returbuff);
            }
            finally
            {
                if (stream.CanSeek)
                {
                    stream.Position = originalPosition;
                }
            }
        }
Exemple #42
0
        public override void GetColords(
            System.IO.Stream source, int rowPitch, int slicePitch,
            Colord[] destination, int index, int width, int height,
            Boxi sourceBoxi, Point3i destinationPoint)
        {
            //seek to start
            source.Seek(
                sourceBoxi.X + sourceBoxi.Y * rowPitch + sourceBoxi.Z * slicePitch,
                System.IO.SeekOrigin.Current);

            for (int z = 0; z < sourceBoxi.Depth; ++z)
            {
                int zindex = index + (destinationPoint.Z + z) * (height * width);

                for (int y = 0; y < sourceBoxi.Height; ++y)
                {
                    int xyindex = destinationPoint.X + (destinationPoint.Y + y) * width + zindex;

                    //write scan line
                    for (int x = 0; x < sourceBoxi.Width; ++x)
                    {
                        int bgra = source.ReadByte() | (source.ReadByte() << 8);

                        double b = (bgra & 31) / 31.0;
                        double g = ((bgra >> 5) & 31) / 31.0;
                        double r = ((bgra >> 10) & 31) / 31.0;
                        double a = (bgra >> 15) / 1.0;

                        destination[xyindex++] = new Numerics.Colord(r, g, b, a);
                    }

                    //seek to next scan line
                    source.Seek(rowPitch - (sourceBoxi.Width * 2), System.IO.SeekOrigin.Current);
                }

                //seek to next scan slice
                source.Seek(slicePitch - (sourceBoxi.Height * rowPitch), System.IO.SeekOrigin.Current);
            }
        }
Exemple #43
0
        public void ReadMessageHeader(IO.Stream stream, out int length, out PeerMessage type)
        {
            length = ReadInt(stream);

            if (length > 0)
            {
                type = (PeerMessage)stream.ReadByte();
            }
            else
            {
                type = PeerMessage.KeepAlive;
            }
        }
    public static Environment Load(System.IO.Stream fs)
    {
        EnvironmentPreset ep = (EnvironmentPreset)fs.ReadByte();

        if (ep != EnvironmentPreset.Custom)
        {
            return(GetEnvironment(ep));
        }
        else
        {
            return(new Environment(fs));
        }
    }
Exemple #45
0
 static public int ReadByte(IntPtr l)
 {
     try {
         System.IO.Stream self = (System.IO.Stream)checkSelf(l);
         var ret = self.ReadByte();
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Exemple #46
0
        public static byte[] ReadToEnd(System.IO.Stream stream)
        {
            long position = 0L;

            if (stream.CanSeek)
            {
                position        = stream.Position;
                stream.Position = 0L;
            }
            checked
            {
                byte[] result;
                try
                {
                    byte[] array = new byte[4096];
                    int    num   = 0;
                    int    num2  = 0;
                    while (FileHelper.InlineAssignHelper(ref num2, stream.Read(array, num, array.Length - num)) > 0)
                    {
                        num += num2;
                        if (num == array.Length)
                        {
                            int num3 = stream.ReadByte();
                            if (num3 != -1)
                            {
                                byte[] array2 = new byte[array.Length * 2 - 1 + 1];
                                Buffer.BlockCopy(array, 0, array2, 0, array.Length);
                                Buffer.SetByte(array2, num, (byte)num3);
                                array = array2;
                                num++;
                            }
                        }
                    }
                    byte[] array3 = array;
                    if (array.Length != num)
                    {
                        array3 = new byte[num - 1 + 1];
                        Buffer.BlockCopy(array, 0, array3, 0, num);
                    }
                    result = array3;
                }
                finally
                {
                    if (stream.CanSeek)
                    {
                        stream.Position = position;
                    }
                }
                return(result);
            }
        }
Exemple #47
0
        public static byte[] ConvertGenericStreamToByteArray(System.IO.Stream stream)
        {
            long originalPosition = 0;

            if (stream.CanSeek)
            {
                originalPosition = stream.Position;
                stream.Position  = 0;
            }

            try
            {
                byte[] readBuffer = new byte[4096];

                int totalBytesRead = 0;
                int bytesRead;

                while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
                {
                    totalBytesRead += bytesRead;

                    if (totalBytesRead == readBuffer.Length)
                    {
                        int nextByte = stream.ReadByte();
                        if (nextByte != -1)
                        {
                            byte[] temp = new byte[readBuffer.Length * 2];
                            Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
                            Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
                            readBuffer = temp;
                            totalBytesRead++;
                        }
                    }
                }

                byte[] buffer = readBuffer;
                if (readBuffer.Length != totalBytesRead)
                {
                    buffer = new byte[totalBytesRead];
                    Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
                }
                return(buffer);
            }
            finally
            {
                if (stream.CanSeek)
                {
                    stream.Position = originalPosition;
                }
            }
        }
        static void Main(string[] args)
        {
            string access_token = "35_EwDiuIMKB2ZVwEKC0KYGGceJZ25yvhFVAB6YgmMazLUBFNC0XCssbDQq_3yJ8M9O8kgs5vJGKSVppH0oW9sJs4iyc5L6iS-htqGfX3UlFM9bOVBVDaFp3Ct4IlfYW_GhPrZ0euiUOqaNym3UDWSaACAWPL"; //这里写你调用token的方法


            string         postUrl = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + access_token;
            HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;

            request.Method      = "POST";
            request.ContentType = "application/json;charset=UTF-8";

            string options = "{\"path\":\"pages/index/index\"}";

            byte[] payload = Encoding.UTF8.GetBytes(options);
            request.ContentLength = payload.Length;

            Stream writer = request.GetRequestStream();

            writer.Write(payload, 0, payload.Length);
            writer.Close();

            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
            System.IO.Stream           stream   = response.GetResponseStream();
            List <byte> bytes = new List <byte>();
            int         temp  = stream.ReadByte();

            while (temp != -1)
            {
                bytes.Add((byte)temp);
                temp = stream.ReadByte();
            }
            byte[] result = bytes.ToArray();
            string base64 = Convert.ToBase64String(result);//将byte[]转为base64

            File.WriteAllText(@"C:\Users\Administrator\Desktop\1.txt", base64);

            Console.ReadLine();
        }
        public override byte ReadByte(int p_Pos)
        {
            long l_RealPosition = CalcRealPosition(p_Pos);

            lock (m_Stream)
            {
                if (m_Stream.Position != l_RealPosition)
                {
                    m_Stream.Position = l_RealPosition;
                }

                return((byte)m_Stream.ReadByte());
            }
        }
 protected static bool StreamsContentMatches(System.IO.Stream a, System.IO.Stream b, int length, out int failurePosition)
 {
     for (int i = 0; i < length; i++)
     {
         if (a.ReadByte() == b.ReadByte())
         {
             continue;
         }
         failurePosition = i;
         return(false);
     }
     failurePosition = -1;
     return(true);
 }
Exemple #51
0
 public static void WriteResourceToFile(string outputDir, string resourceLocation, string file)
 {
     using (System.IO.Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceLocation + @".Resources." + file))
     {
         using (System.IO.FileStream fileStream = new System.IO.FileStream(System.IO.Path.Combine(outputDir, file), System.IO.FileMode.Create))
         {
             for (int i = 0; i < stream.Length; i++)
             {
                 fileStream.WriteByte((byte)stream.ReadByte());
             }
             fileStream.Close();
         }
     }
 }
    public void LoadPlanesData(System.IO.Stream fs)
    {
        var count = fs.ReadByte();

        if (count > 0)
        {
            IPlanableSupportClass.AddBlockRepresentation(this, basement, ref myBlock, false);
            planes = new Dictionary <byte, Plane>();
            for (int i = 0; i < count; i++)
            {
                var p = Plane.Load(fs, this);
                planes.Add(p.faceIndex, p);
            }
        }
    }
Exemple #53
0
 /// <summary>
 /// Create the file on the Filesystem from the Resource File
 /// </summary>
 private static void createHelpFile()
 {
     //Write the File to the FileSystem
     using (System.IO.Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Connecty.Resources.ConnectyHilfe.chm"))
     {
         using (System.IO.FileStream fileStream = new System.IO.FileStream(System.IO.Path.Combine("ConnectyHilfe.chm"), System.IO.FileMode.Create))
         {
             for (int i = 0; i < stream.Length; i++)
             {
                 fileStream.WriteByte((byte)stream.ReadByte());
             }
             fileStream.Close();
         }
     }
 }
        /// <summary>
        /// Might be used for debugging <seealso cref="ProcessDiagramRetrievalTest#testGetProcessDiagram()"/>.
        /// </summary>
        //JAVA TO C# CONVERTER TODO Resources.Task: Most Java annotations will not have direct .NET equivalent attributes:
        //ORIGINAL LINE: @SuppressWarnings("unused") private static void writeToFile(java.io.InputStream is, java.io.File file) throws Exception
        //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
        private static void writeToFile(System.IO.Stream @is, FileStream file)
        {
            var bs = new byte[file.Length];

            file.Read(bs, 0, (int)file.Length);
            var @out = new MemoryStream(bs, true);
            int c;

            while ((c = @is.ReadByte()) != -1)
            {
                @out.WriteByte((byte)c);
            }
            @is.Close();
            @out.Close();
        }
Exemple #55
0
    public static void LoadDockSystem(System.IO.Stream fs, int saveVersion)
    {
        current = null;
        int x = fs.ReadByte();

        if (x == 0)
        {
            return;
        }
        else
        {
            current = new DockSystem();
            current.Load(fs);
        }
    }
Exemple #56
0
        public override void GetColords(
            System.IO.Stream source, int rowPitch, int slicePitch,
            Colord[] destination, int index, int width, int height,
            Boxi sourceBoxi, Point3i destinationPoint)
        {
            //seek to start
            source.Seek(
                sourceBoxi.X * 3 + sourceBoxi.Y * rowPitch + sourceBoxi.Z * slicePitch,
                System.IO.SeekOrigin.Current);

            for (int z = 0; z < sourceBoxi.Depth; ++z)
            {
                int zindex = index + (destinationPoint.Z + z) * (height * width);

                for (int y = 0; y < sourceBoxi.Height; ++y)
                {
                    int xyindex = destinationPoint.X + (destinationPoint.Y + y) * width + zindex;

                    //write scan line
                    for (int x = 0; x < sourceBoxi.Width; ++x)
                    {
                        double b = source.ReadByte() / (double)byte.MaxValue;
                        double g = source.ReadByte() / (double)byte.MaxValue;
                        double r = source.ReadByte() / (double)byte.MaxValue;

                        destination[xyindex++] = new Numerics.Colord(r, g, b);
                    }

                    //seek to next scan line
                    source.Seek(rowPitch - (sourceBoxi.Width * 3), System.IO.SeekOrigin.Current);
                }

                //seek to next scan slice
                source.Seek(slicePitch - (sourceBoxi.Height * rowPitch), System.IO.SeekOrigin.Current);
            }
        }
Exemple #57
0
        public void ExtractEmbeddedResource(string outputDir, string resource)
        {
            var a = Assembly.GetExecutingAssembly().GetManifestResourceNames();

            using (System.IO.Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("MelocoaTesseractLibrary.ApplicationFiles." + resource))
            {
                using (System.IO.FileStream fileStream = new System.IO.FileStream(System.IO.Path.Combine(outputDir, resource), System.IO.FileMode.Create))
                {
                    for (int i = 0; i < stream.Length; i++)
                    {
                        fileStream.WriteByte((byte)stream.ReadByte());
                    }
                    fileStream.Close();
                }
            }
        }
Exemple #58
0
 /// <summary>
 /// Create the file on the Filesystem from the Resource File
 /// </summary>
 private static void createHelpFile()
 {
     //Write the File to the FileSystem
     // Stream could not be created.. Does the File Exist???
     using (System.IO.Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(fileLocation + "." + helpFileName))
     {
         using (System.IO.FileStream fileStream = new System.IO.FileStream(System.IO.Path.Combine(helpFileName), System.IO.FileMode.Create))
         {
             for (int i = 0; i < stream.Length; i++)
             {
                 fileStream.WriteByte((byte)stream.ReadByte());
             }
             fileStream.Close();
         }
     }
 }
Exemple #59
0
        /// <summary>
        /// Reads data from a stream until the end is reached. The
        /// data is returned as a byte array. An IOException is
        /// thrown if any of the underlying IO calls fail.
        /// </summary>
        /// <param name="stream">The stream to read data from</param>
        /// <param name="initialLength">The initial buffer length</param>
        ///

        private static byte[] ReadFully(System.IO.Stream stream, long initialLength)
        {
            // reset pointer just in case
            stream.Seek(0, System.IO.SeekOrigin.Begin);

            // If we've been passed an unhelpful initial length, just
            // use 32K.
            if (initialLength < 1)
            {
                initialLength = 32768;
            }

            byte[] buffer = new byte[initialLength];
            int    read   = 0;

            int chunk;

            while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0)
            {
                read += chunk;

                // If we've reached the end of our buffer, check to see if there's
                // any more information
                if (read == buffer.Length)
                {
                    int nextByte = stream.ReadByte();

                    // End of stream? If so, we're done
                    if (nextByte == -1)
                    {
                        return(buffer);
                    }

                    // Nope. Resize the buffer, put in the byte we've just
                    // read, and continue
                    byte[] newBuffer = new byte[buffer.Length * 2];
                    Array.Copy(buffer, newBuffer, buffer.Length);
                    newBuffer[read] = (byte)nextByte;
                    buffer          = newBuffer;
                    read++;
                }
            }
            // Buffer is now too big. Shrink it.
            byte[] ret = new byte[read];
            Array.Copy(buffer, ret, read);
            return(ret);
        }
Exemple #60
0
        private void ReadJPGImage(System.IO.Stream stream)
        {
            char ch1 = (char)stream.ReadByte();
            char ch2 = (char)stream.ReadByte();

            if (ch1 != 0x00FF || ch2 != 0x00D8)
            {
                throw new Exception("Error: Invalid JPEG header.");
            }

            bool foundSOFn = false;

            while (true)
            {
                char ch = NextMarker(stream);
                switch (ch)
                {
                // Note that marker codes 0xC4, 0xC8, 0xCC are not,
                // and must not be treated as SOFn. C4 in particular
                // is actually DHT.
                case M_SOF0:    // Baseline
                case M_SOF1:    // Extended sequential, Huffman
                case M_SOF2:    // Progressive, Huffman
                case M_SOF3:    // Lossless, Huffman
                case M_SOF5:    // Differential sequential, Huffman
                case M_SOF6:    // Differential progressive, Huffman
                case M_SOF7:    // Differential lossless, Huffman
                case M_SOF9:    // Extended sequential, arithmetic
                case M_SOF10:   // Progressive, arithmetic
                case M_SOF11:   // Lossless, arithmetic
                case M_SOF13:   // Differential sequential, arithmetic
                case M_SOF14:   // Differential progressive, arithmetic
                case M_SOF15:   // Differential lossless, arithmetic
                    // Skip 3 bytes to get to the image height and width
                    stream.ReadByte();
                    stream.ReadByte();
                    stream.ReadByte();
                    height          = GetUInt16(stream);
                    width           = GetUInt16(stream);
                    colorComponents = stream.ReadByte();
                    foundSOFn       = true;
                    break;

                default:
                    SkipVariable(stream);
                    break;
                }

                if (foundSOFn)
                {
                    break;
                }
            }
        }