ReadByte() public method

public ReadByte ( ) : int
return int
Example #1
0
        /// <summary>
        /// Build and return a revision by applying a set of DiffCodes to a base version.
        /// DiffCodes should be from StorageDiffCode().
        /// </summary>
        public static List<Fragment> BuildChanges(string BaseRevision, byte[] DiffCodes)
        {
            // Decompress and send to real decoder.
            var @in = new MemoryStream(DiffCodes); // this will receive the compressed code
            var filter = new DeflateStream(@in, CompressionMode.Decompress);

            var @out = new List<byte>(DiffCodes.Length);
            int b = filter.ReadByte();
            while (b >= 0) {
                @out.Add((byte)b);
                b = filter.ReadByte();
            }
            return DecodeRevisionFragments(BaseRevision, Encoding.UTF8.GetString(@out.ToArray()));
        }
        public byte[] Load( Stream stream, Game game, out int width, out int height, out int length )
        {
            GZipHeaderReader gsHeader = new GZipHeaderReader();
            while( !gsHeader.ReadHeader( stream ) ) { }

            using( DeflateStream gs = new DeflateStream( stream, CompressionMode.Decompress ) ) {
                BinaryReader reader = new BinaryReader( gs );
                ushort header = reader.ReadUInt16();

                width = header == Version ? reader.ReadUInt16() : header;
                length = reader.ReadUInt16();
                height = reader.ReadUInt16();

                LocalPlayer p = game.LocalPlayer;
                p.Spawn.X = reader.ReadUInt16();
                p.Spawn.Z = reader.ReadUInt16();
                p.Spawn.Y = reader.ReadUInt16();
                p.SpawnYaw = (float)Utils.PackedToDegrees( reader.ReadByte() );
                p.SpawnPitch = (float)Utils.PackedToDegrees( reader.ReadByte() );

                if( header == Version )
                    reader.ReadUInt16(); // pervisit and perbuild perms
                byte[] blocks = new byte[width * height * length];
                int read = gs.Read( blocks, 0, blocks.Length );
                ConvertPhysicsBlocks( blocks );

                if( gs.ReadByte() != 0xBD ) return blocks;
                ReadCustomBlocks( gs, width, height, length, blocks );
                return blocks;
            }
        }
Example #3
0
        static void Main()
        {
            FileStream source = File.OpenRead(@"D:\archive.dfl");
            FileStream destination = File.Create(@"D:\text_deflate.txt");

            DeflateStream deCompressor = new DeflateStream(source, CompressionMode.Decompress);

            int theByte = deCompressor.ReadByte();
            while (theByte != -1)
            {
                destination.WriteByte((byte)theByte);
                theByte = deCompressor.ReadByte();
            }

            deCompressor.Close();
        }
        // implementation borrowed from Google's Java API.
        public static XmlDocument UnpackRequest(string packedText)
        {
            // convert from Base64
            byte[] compressedBytes = Convert.FromBase64String(packedText);

            DeflateStream inflateStream = new DeflateStream(new MemoryStream(compressedBytes), CompressionMode.Decompress, false);

            byte[] xmlMessageBytes = new byte[20000];
            int c;
            int resultLength = 0;
            while ((c = inflateStream.ReadByte()) >= 0) {
                if (resultLength >= 20000)
                {
                    throw new Exception("didn't allocate enough space to hold decompressed data");
                }
                xmlMessageBytes[resultLength++] = (byte)c;
            }

            string result = Encoding.UTF8.GetString(xmlMessageBytes, 0, resultLength);

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(result);

            return doc;
        }
Example #5
0
        public Bitmap DecodeImage( Stream inps )
        {
            if ( inps == null ) return null;

              // !!!{{ TODO: add the decoding code here

              DeflateStream ds = new DeflateStream( inps, CompressionMode.Decompress, true );

              int buffer;
              buffer = ds.ReadByte();
              if ( buffer < 0 || buffer != ((MAGIC >> 24) & 0xff) ) return null;
              buffer = ds.ReadByte();
              if ( buffer < 0 || buffer != ((MAGIC >> 16) & 0xff) ) return null;
              buffer = ds.ReadByte();
              if ( buffer < 0 || buffer != ((MAGIC >>  8) & 0xff) ) return null;
              buffer = ds.ReadByte();
              if ( buffer < 0 || buffer != ( MAGIC        & 0xff) ) return null;

              int width, height;
              width = ds.ReadByte();
              if ( width < 0 ) return null;
              buffer = ds.ReadByte();
              if ( buffer < 0 ) return null;
              width = (width << 8) + buffer;
              height = ds.ReadByte();
              if ( height < 0 ) return null;
              buffer = ds.ReadByte();
              if ( buffer < 0 ) return null;
              height = (height << 8) + buffer;

              if ( width < 1 || height < 1 )
            return null;

              Bitmap result = new Bitmap( width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb );

              for ( int y = 0; y < height; y++ )
            for ( int x = 0; x < width; x++ )
            {
              int gr = ds.ReadByte();
              result.SetPixel( x, y, Color.FromArgb( gr, gr, gr ) );
            }

              ds.Close();
              return result;

              // !!!}}
        }
Example #6
0
 public static int ReadI32ZLIB(BinaryReader reader, bool swap)
 {
     int result = -1;
     using (var stream = new DeflateStream(reader.BaseStream, CompressionMode.Decompress))
     using (var dbr = new BinaryReader(stream)) {
         byte[] data = new byte[4];
         for (int i = 0; i < 4; i++)
             data[i] = (byte)stream.ReadByte();
         if (swap) Array.Reverse(data);
         result = BitConverter.ToInt32(data, 0);
     }
     return result;
 }
Example #7
0
        /// <summary>
        /// 使用Http Request获取网页信息
        /// </summary>
        /// <param name="url">Url</param>
        /// <param name="postData">Post的信息</param>
        /// <param name="cookies">Cookies</param>
        /// <param name="userAgent">浏览器标识</param>
        /// <param name="referer">来源页</param>
        /// <param name="cookiesDomain">Cookies的Domian参数,配合cookies使用;为空则取url的Host</param>
        /// <param name="encode">编码方式,用于解析html</param>
        /// <param name="method">提交方式,例如POST或GET,默认通过postData是否为空判断</param>
        /// <param name="proxy"></param>
        /// <param name="encoding"></param>
        /// <param name="contentType"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static HttpResult HttpRequest(string url, string postData = null, CookieContainer cookies = null, string userAgent = null, string referer = null, string cookiesDomain = null, Encoding encode = null, string method = null, IWebProxy proxy = null, string encoding = null, string contentType = null, int timeout = 8000)
        {
            HttpResult httpResponse = new HttpResult();

            try
            {
                HttpWebResponse httpWebResponse = null;
                if (!string.IsNullOrEmpty(postData) || (!string.IsNullOrEmpty(method) && method.ToUpper() == "POST"))
                    httpWebResponse = CreatePostHttpResponse(url, postData, timeout, userAgent, cookies, referer, proxy, contentType);
                else
                    httpWebResponse = CreateGetHttpResponse(url, timeout, userAgent, cookies, referer, proxy, contentType);

                httpResponse.Url = httpWebResponse.ResponseUri.ToString();
                httpResponse.HttpCode = (int)httpWebResponse.StatusCode;
                httpResponse.LastModified = TimeHelper.ConvertDateTimeInt(httpWebResponse.LastModified);

                string Content = null;
                //头部预读取缓冲区,字节形式
                var bytes = new List<byte>();
                //头部预读取缓冲区,字符串
                String cache = string.Empty;

                //创建流对象并解码
                Stream ResponseStream;
                switch (httpWebResponse.ContentEncoding.ToUpperInvariant())
                {
                    case "GZIP":
                        ResponseStream = new GZipStream(
                            httpWebResponse.GetResponseStream(), CompressionMode.Decompress);
                        break;
                    case "DEFLATE":
                        ResponseStream = new DeflateStream(
                            httpWebResponse.GetResponseStream(), CompressionMode.Decompress);
                        break;
                    default:
                        ResponseStream = httpWebResponse.GetResponseStream();
                        break;
                }

                try
                {
                    while (true)
                    {
                        var b = (byte)ResponseStream.ReadByte();
                        if (b < 0 || b == 255) //end of stream
                            break;
                        bytes.Add(b);

                        if (!cache.EndsWith("</head>", StringComparison.OrdinalIgnoreCase))
                            cache += (char)b;
                    }

                    // Charset check: input > NChardet > Parser
                    if (encode == null)
                    {
                        string charset = NChardetHelper.RecogCharset(bytes.ToArray());
                        if (!string.IsNullOrEmpty(charset))
                            encode = Encoding.GetEncoding(charset);

                        if (encode == null)
                        {
                            if (httpWebResponse.CharacterSet == "ISO-8859-1" || httpWebResponse.CharacterSet == "zh-cn")
                            {
                                Match match = Regex.Match(cache, CharsetReg, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                                if (match.Success)
                                {
                                    try
                                    {
                                        charset = match.Groups["Charset"].Value;
                                        encode = Encoding.GetEncoding(charset);
                                    }
                                    catch { }
                                }
                            }

                            if (httpWebResponse.CharacterSet != null && encode == null)
                                encode = Encoding.GetEncoding(httpWebResponse.CharacterSet);
                        }
                    }

                    if (encode == null)
                        encode = Encoding.Default;

                    Content = encode.GetString(bytes.ToArray());
                    ResponseStream.Close();
                }
                catch (Exception ex)
                {
                    httpResponse.Content = ex.ToString();
                    return httpResponse;
                }
                finally
                {
                    httpWebResponse.Close();
                }

                //get the Cookies,support httponly.
                if (string.IsNullOrEmpty(cookiesDomain))
                    cookiesDomain = httpWebResponse.ResponseUri.Host;

                cookies = new CookieContainer();
                CookieCollection httpHeaderCookies = SetCookie(httpWebResponse, cookiesDomain);
                cookies.Add(httpHeaderCookies ?? httpWebResponse.Cookies);

                httpResponse.Content = Content;
            }
            catch
            {
                httpResponse.Content = string.Empty;
            }
            return httpResponse;
        }
Example #8
0
        /// <summary>
        /// 获取网页的内容
        /// </summary>
        /// <param name="url">Url</param>
        /// <param name="postData">Post的信息</param>
        /// <param name="cookies">Cookies</param>
        /// <param name="userAgent">浏览器标识</param>
        /// <param name="referer">来源页</param>
        /// <param name="cookiesDomain">Cookies的Domian参数,配合cookies使用;为空则取url的Host</param>
        /// <param name="encode">编码方式,用于解析html</param>
        /// <returns></returns>
        public static string GetHttpContent(string url, string postData = null, CookieContainer cookies = null, string userAgent = "", string referer = "", string cookiesDomain = "", Encoding encode = null)
        {
            try
            {
                HttpWebResponse httpResponse = null;
                if (!string.IsNullOrWhiteSpace(postData))
                    httpResponse = CreatePostHttpResponse(url, postData, cookies: cookies, userAgent: userAgent, referer: referer);
                else
                    httpResponse = CreateGetHttpResponse(url, cookies: cookies, userAgent: userAgent, referer: referer);

                #region 根据Html头判断
                string Content = null;
                //缓冲区长度
                const int N_CacheLength = 10000;
                //头部预读取缓冲区,字节形式
                var bytes = new List<byte>();
                int count = 0;
                //头部预读取缓冲区,字符串
                String cache = string.Empty;

                //创建流对象并解码
                Stream ResponseStream;
                switch (httpResponse.ContentEncoding.ToUpperInvariant())
                {
                    case "GZIP":
                        ResponseStream = new GZipStream(
                            httpResponse.GetResponseStream(), CompressionMode.Decompress);
                        break;
                    case "DEFLATE":
                        ResponseStream = new DeflateStream(
                            httpResponse.GetResponseStream(), CompressionMode.Decompress);
                        break;
                    default:
                        ResponseStream = httpResponse.GetResponseStream();
                        break;
                }

                try
                {
                    while (
                        !(cache.EndsWith("</head>", StringComparison.OrdinalIgnoreCase)
                          || count >= N_CacheLength))
                    {
                        var b = (byte)ResponseStream.ReadByte();
                        if (b < 0) //end of stream
                        {
                            break;
                        }
                        bytes.Add(b);

                        count++;
                        cache += (char)b;
                    }

                    if (encode == null)
                    {
                        try
                        {
                            if (httpResponse.CharacterSet == "ISO-8859-1" || httpResponse.CharacterSet == "zh-cn")
                            {
                                Match match = Regex.Match(cache, CharsetReg, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                                if (match.Success)
                                {
                                    try
                                    {
                                        string charset = match.Groups["Charset"].Value;
                                        encode = Encoding.GetEncoding(charset);
                                    }
                                    catch { }
                                }
                                else
                                    encode = Encoding.GetEncoding("GB2312");
                            }
                            else
                                encode = Encoding.GetEncoding(httpResponse.CharacterSet);
                        }
                        catch { }
                    }

                    //缓冲字节重新编码,然后再把流读完
                    var Reader = new StreamReader(ResponseStream, encode);
                    Content = encode.GetString(bytes.ToArray(), 0, count) + Reader.ReadToEnd();
                    Reader.Close();
                }
                catch (Exception ex)
                {
                    return ex.ToString();
                }
                finally
                {
                    httpResponse.Close();
                }
                #endregion 根据Html头判断

                //获取返回的Cookies,支持httponly
                if (string.IsNullOrWhiteSpace(cookiesDomain))
                    cookiesDomain = httpResponse.ResponseUri.Host;

                cookies = new CookieContainer();
                CookieCollection httpHeaderCookies = SetCookie(httpResponse, cookiesDomain);
                cookies.Add(httpHeaderCookies ?? httpResponse.Cookies);

                return Content;
            }
            catch
            {
                return string.Empty;
            }
        }
Example #9
0
 public override int ReadByte()
 {
     CheckDeflateStream();
     return(_deflateStream.ReadByte());
 }
Example #10
0
        /// <summary>
        /// 使用Http Request获取网页信息
        /// </summary>
        /// <param name="url">Url</param>
        /// <param name="postData">Post的信息</param>
        /// <param name="cookies">Cookies</param>
        /// <param name="userAgent">浏览器标识</param>
        /// <param name="referer">来源页</param>
        /// <param name="cookiesDomain">Cookies的Domian参数,配合cookies使用;为空则取url的Host</param>
        /// <param name="encode">编码方式,用于解析html</param>
        /// <param name="method">提交方式,例如POST或GET,默认通过postData是否为空判断</param>
        /// <param name="proxy"></param>
        /// <param name="encoding"></param>
        /// <param name="contentType"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static HttpResult HttpRequest(string url, string postData = null, CookieContainer cookies = null, string userAgent = null, string referer = null, string cookiesDomain = null, Encoding encode = null, string method = null, IWebProxy proxy = null, string encoding = null, string contentType = null, int timeout = 8000, Dictionary<string, string> headers = null)
        {
            HttpResult httpResponse = new HttpResult();

            try
            {
                HttpWebResponse httpWebResponse = null;
                if (!string.IsNullOrEmpty(postData) || (!string.IsNullOrEmpty(method) && method.ToUpper() == "POST"))
                    httpWebResponse = CreatePostHttpResponse(url, postData, timeout, userAgent, cookies, referer, proxy, contentType, headers);
                else
                    httpWebResponse = CreateGetHttpResponse(url, timeout, userAgent, cookies, referer, proxy, contentType, headers);

                httpResponse.Url = httpWebResponse.ResponseUri.ToString();
                httpResponse.HttpCode = (int)httpWebResponse.StatusCode;
                httpResponse.LastModified = TimeHelper.ConvertDateTimeInt(httpWebResponse.LastModified);

                string Content = null;
                //头部预读取缓冲区,字节形式
                var bytes = new List<byte>();
                //头部预读取缓冲区,字符串
                String cache = string.Empty;

                //创建流对象并解码
                Stream ResponseStream;
                switch (httpWebResponse.ContentEncoding.ToUpperInvariant())
                {
                    case "GZIP":
                        ResponseStream = new GZipStream(
                            httpWebResponse.GetResponseStream(), CompressionMode.Decompress);
                        break;
                    case "DEFLATE":
                        ResponseStream = new DeflateStream(
                            httpWebResponse.GetResponseStream(), CompressionMode.Decompress);
                        break;
                    default:
                        ResponseStream = httpWebResponse.GetResponseStream();
                        break;
                }

                try
                {
                    while (true)
                    {
                        var b = ResponseStream.ReadByte();
                        if (b < 0) //end of stream
                            break;
                        bytes.Add((byte)b);

                        if (!cache.EndsWith("</head>", StringComparison.OrdinalIgnoreCase))
                            cache += (char)b;
                    }

                    string Ncharset = "";
                    string Hcharset = "";
                    string Rcharset = "";

                    //1,使用解析ContentType,解析Html编码声明,自动编码识别三种来猜测编码,选取任意两者相同的编码
                    if (encode == null)
                    {
                        Match match = Regex.Match(cache, CharsetReg, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                        if (match.Success)
                            Rcharset = match.Groups["Charset"].Value;

                        try
                        {
                            string text = "";
                            if (!string.IsNullOrEmpty(text = httpWebResponse.ContentType))
                            {
                                text = text.ToLower(CultureInfo.InvariantCulture);
                                string[] array = text.Split(new char[] { ';', '=', ' ' });
                                bool flag = false;
                                string[] array2 = array;
                                for (int i = 0; i < array2.Length; i++)
                                {
                                    string text2 = array2[i];
                                    if (text2 == "charset")
                                        flag = true;
                                    else
                                    {
                                        if (flag)
                                            Hcharset = text2;
                                    }
                                }
                            }

                        }
                        catch { }

                        if (!string.IsNullOrEmpty(Rcharset) && !string.IsNullOrEmpty(Hcharset) && Hcharset.ToUpper() == Rcharset.ToUpper())
                            encode = Encoding.GetEncoding(Hcharset);
                        else
                        {
                            Ncharset = NChardetHelper.RecogCharset(bytes.ToArray(), Thrinax.Data.NChardetLanguage.CHINESE, -1);

                            if (!string.IsNullOrEmpty(Ncharset) && (Ncharset.ToUpper() == Rcharset.ToUpper() || Ncharset.ToUpper() == Hcharset.ToUpper()))
                                encode = Encoding.GetEncoding(Ncharset);
                        }

                    }

                    //2,使用人工标注的编码
                    if (encode == null && !string.IsNullOrEmpty(encoding))
                    {
                        try
                        {
                            encode = Encoding.GetEncoding(encoding);
                        }
                        catch { }
                    }

                    //3,使用单一方式识别出的编码,网页自动识别 > 解析ContentType > 解析Html编码声明
                    if (encode == null && !string.IsNullOrEmpty(Ncharset))
                        encode = Encoding.GetEncoding(Ncharset);
                    if(encode == null && !string.IsNullOrEmpty(Hcharset))
                        encode = Encoding.GetEncoding(Hcharset);
                    if (encode == null && !string.IsNullOrEmpty(Rcharset))
                        encode = Encoding.GetEncoding(Rcharset);

                    //4,使用默认编码,听天由命吧
                    if (encode == null)
                        encode = Encoding.Default;

                    Content = encode.GetString(bytes.ToArray());
                    ResponseStream.Close();
                }
                catch (Exception ex)
                {
                    httpResponse.Content = ex.ToString();
                    return httpResponse;
                }
                finally
                {
                    httpWebResponse.Close();
                }

                //get the Cookies,support httponly.
                if (string.IsNullOrEmpty(cookiesDomain))
                    cookiesDomain = httpWebResponse.ResponseUri.Host;

                cookies = new CookieContainer();
                CookieCollection httpHeaderCookies = SetCookie(httpWebResponse, cookiesDomain);
                cookies.Add(httpHeaderCookies ?? httpWebResponse.Cookies);

                httpResponse.Content = Content;
            }
            catch(Exception ex)
            {
                httpResponse.Content = ex.ToString();
                httpResponse.HttpCode = DetermineResultStatus(ex);
            }
            return httpResponse;
        }
Example #11
0
 public static string ReadBytesFromFile()
 {
     FileStream stream = new FileStream(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "deluge.bin"), FileMode.Open);
     DeflateStream decompressStream = new DeflateStream(stream, CompressionMode.Decompress);
     decompressStream.ReadByte();
     return String.Empty;
 }
Example #12
0
        public Bitmap DecodeImage(Stream inps)
        {
            if (inps == null) return null;

            DeflateStream ds = new DeflateStream(inps, CompressionMode.Decompress, true);
            Bitmap decodedImage = null;

            try
            {
                int buffer;

                // read magic number
                buffer = ds.ReadByte();
                if (buffer < 0 || buffer != ((MAGIC >> 24) & 0xff)) return null;
                buffer = ds.ReadByte();
                if (buffer < 0 || buffer != ((MAGIC >> 16) & 0xff)) return null;
                buffer = ds.ReadByte();
                if (buffer < 0 || buffer != ((MAGIC >> 8) & 0xff)) return null;
                buffer = ds.ReadByte();
                if (buffer < 0 || buffer != (MAGIC & 0xff)) return null;

                // read image width
                int width = ds.ReadByte();
                if (width < 0) return null;
                buffer = ds.ReadByte();
                if (buffer < 0) return null;
                width = (width << 8) + buffer;

                // read image height
                int height = ds.ReadByte();
                if (height < 0) return null;
                buffer = ds.ReadByte();
                if (buffer < 0) return null;
                height = (height << 8) + buffer;

                if (width < 1 || height < 1)
                    return null;

                decodedImage = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

                // read dominant color
                int backgroundColor = ds.ReadByte();
                if (backgroundColor < 0) return null;
                int foregroundColor = 1 - backgroundColor;
                // fill the image with the background color
                Color bgDrawingColor = (backgroundColor == 0) ? Color.Black : Color.White;
                for (int y = 0; y < height; y++)
                {
                    for (int x = 0; x < width; x++)
                    {
                        decodedImage.SetPixel(x, y, bgDrawingColor);
                    }
                }

                if (TraceEnabled)
                {
                    Console.WriteLine("Decoding.");
                }

                // compute bit mask for getting directionIndex bits
                int directionBitMask = -(-1 << neighborhood.SignificantBits) - 1;

                Point previousStartingPoint = new Point();

                bool canProcessLines = true;
                while (canProcessLines) {
                    //read starting pixel position - X, Y
                    int readByte = ds.ReadByte();
                    if (readByte < 0)
                    {
                        canProcessLines = false;
                        break;
                    }
                    buffer = readByte;

                    readByte = ds.ReadByte();
                    if (readByte < 0) return null;
                    buffer = (buffer << 8) | readByte;

                    readByte = ds.ReadByte();
                    if (readByte < 0) return null;
                    buffer = (buffer << 8) | readByte;

                    readByte = ds.ReadByte();
                    if (readByte < 0) return null;
                    buffer = (buffer << 8) | readByte;

                    int signX = ((buffer & (1 << 31)) == 0) ? 1 : -1;
                    int diffX = signX * ((buffer & ((-(-1 << 15) - 1) << 16)) >> 16);

                    int signY = ((buffer & (1 << 15)) == 0) ? 1 : -1;
                    int diffY = signY * (buffer & (-(-1 << 15) - 1));

                    if (TraceEnabled)
                    {
                        Console.WriteLine("Diff: [{0}, {1}]", diffX, diffY);
                    }

                    int startX = previousStartingPoint.X + (short) diffX;
                    int startY = previousStartingPoint.Y + (short) diffY;

                    //draw the pixel
                    if (TraceEnabled)
                    {
                        Console.WriteLine("First pixel: [{0}, {1}]", startX, startY);
                    }
                    if (UseFalseColors)
                    {
                        decodedImage.SetPixel(startX, startY, Color.Red);
                    }
                    else
                    {
                        BWImageHelper.SetBWPixel(decodedImage, startX, startY, foregroundColor);
                    }
                    previousStartingPoint.X = startX;
                    previousStartingPoint.Y = startY;

                    //read the count of following directions
                    int directionsCount = ds.ReadByte();
                    if (directionsCount < 0) return null;
                    int directionsRead = 0;
                    int bufferLength = 0;
                    int nextX = startX;
                    int nextY = startY;
                    while (directionsRead < directionsCount)
                    {
                        if (bufferLength < neighborhood.SignificantBits)
                        {
                            buffer &= 0xffff >> (16 - bufferLength);
                            buffer <<= 8;
                            buffer += ds.ReadByte();
                            if (buffer < 0) return null;
                            bufferLength += 8;
                        }

                        //read the directionIndex directionIndex
                        int maskOffset = bufferLength - neighborhood.SignificantBits;
                        int directionIndex = (buffer & (directionBitMask << maskOffset)) >> maskOffset;
                        bufferLength -= neighborhood.SignificantBits;
                        //convert the directions directionIndex to a Point
                        Point direction = neighborhood.Directions[directionIndex];
                        //compute the next pixel and draw it
                        nextX += direction.X;
                        nextY += direction.Y;
                        if (TraceEnabled)
                        {
                            Console.WriteLine("Neighbor pixel: [{0}, {1}]", nextX, nextY);
                            Console.WriteLine("  Direction: {0} ({1})", direction, directionIndex);
                        }
                        if (UseFalseColors)
                        {
                            //decodedImage.SetPixel(nextX, nextY, Color.Green);
                            int linePointIntensity = (int)(127.0 * (1.0 - directionsRead / (double)directionsCount));
                            decodedImage.SetPixel(nextX, nextY, Color.FromArgb(0, linePointIntensity, linePointIntensity));
                        }
                        else
                        {
                            BWImageHelper.SetBWPixel(decodedImage, nextX, nextY, foregroundColor);
                        }
                        directionsRead++;
                    }
                }
                if (TraceEnabled)
                {
                    Console.WriteLine("Successfully decoded.");
                    Console.WriteLine();
                }
            }
            finally
            {
                if (ds != null)
                {
                    ds.Close();
                }
            }
            return decodedImage;
        }
Example #13
0
        public HttpWebResponse GetData(HttpWebRequest httpWebRequest, out string responseText)
        {
            ServicePointManager.Expect100Continue = false; //Resolve http 417 issue

            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

            Encoding encoding = GetEncoding(httpWebResponse.ContentType);

            using (Stream outStream = httpWebResponse.GetResponseStream())
            {
                string contentEncoding = httpWebResponse.ContentEncoding;

                if (contentEncoding.StartsWith("gzip"))
                {
                    MemoryStream ms = new MemoryStream();

                    using (Stream stream = new GZipStream(outStream, CompressionMode.Decompress))
                    {
                        int bit = stream.ReadByte();

                        while (bit > -1)
                        {
                            ms.WriteByte((byte)bit);
                            bit = stream.ReadByte();
                        }

                        responseText = encoding.GetString(ms.ToArray());
                    }
                }
                else if (contentEncoding.StartsWith("deflate"))
                {
                    MemoryStream ms = new MemoryStream();

                    using (Stream stream = new DeflateStream(outStream, CompressionMode.Decompress))
                    {
                        int bit = stream.ReadByte();

                        while (bit > -1)
                        {
                            ms.WriteByte((byte)bit);
                            bit = stream.ReadByte();
                        }

                        responseText = encoding.GetString(ms.ToArray());
                    }
                }
                else
                {
                    using (StreamReader sr = new StreamReader(outStream, encoding))
                    {
                        responseText = sr.ReadToEnd();
                    }
                }
            }

            return httpWebResponse;
        }
Example #14
0
		public void LabTest()
		{
			// x = 8, z = 9
			string test = "78daedcdc109c0200004c1233e125bb32f1b4a836a170acec0bef74b52576f294f36f2f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f73fe10f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002718974bff9ba43b9b1d578f30";
			string test2 = "789ced5dc9721cc711ed8e09c5486341185877872f085c110179df480220099120294ba47ce4cd115ee99dd64aefa6f7332fd09d3cf80374d00f38829f40ff8088b32f7067cfd44cf774d792f5b23bd14065c470d033fdea655657d6cbaa6e80af6459f6bf939393f1789c57acf8340fb6a3a3a39733d0e6fc930991133d833f17e1cfc7444f0ecc3ee93ffe71959f15be007f3eeffff202f0f865fabf320099f422fc4533c6017ef862e33f8a5f26fe053f9b5ee8fa03e10b8f3fae29f34b8f3f1dfe687ac9f94f317e881f76405dfff3790130e3ee9f7fbcd0bfd907e1f452f3ef78c63fc9caf8fbe65fc43fe130cfe9cfc4fc5b51400dfee8f2435d7fb5f9e5eb2f6ef8eaf3ff19e08fa63f23f143f59f80fee7d50a28eb5f7fabf31f73052837fee6facfe0968bdf6c40b0f985d6bf950d0085f8e76d45d0abafbf64f54fe9fa2ff29ff835f47fd15a04bd74fdc1e3971a7fb1035078fe55e257d75f845f447f117ed401b3fe9e5ba6a0ff739b1075fffbdfcb05302bf64ef879f4a2fb5f31fa2fa93f547ff1e985f557833f371ea88dbf65fc4af5472cbfdcfdb799a95cff61eb9f363faebfd8febf84feeaf2afeefff3f8a5f59f1bff19e05f14006c7ed1f9577dfd3d61872fbbfe52ebff45fcbafaa3a5bfa635edfa8b6fa760ff577bfd2f7dffb97f7e75fd8da69ff1830ee8afffb5d75faef9d7ed91ecfaa3853f73778974fccdf07be07726602ffcb9895f5d7f99fc67abfee01bf17f1ee5cf21fd3d03fa87e93fbefe8db7230101c4f517f300ad3f9e3c295e474f80f8eb1e54e680f27b0fbfe8fcb7d2bc8f5e7cfdc976a0077e9703d2fad720f0f00b3fffd5b45ee3b738d039bfcb016d7e8f75b1fe9d4e19f4eaf587bafe4becff02fb1ff8fa934fbf182122facb0fbec63fd7df680146fbdff0c73ae0609f9de07640f6f9eb167e4f0708d4ffc65aeb8feee3cfedeb3faf0392f3efc4a2ffddf32ff63fb8fc92cf1fb65b0ffc3efdefbaff1bebdfaafebae93be167e8bfc40540f7bf859fbfeadd01b0fe13d87f666f40b4e92f107f04ffb4c11fafbf31f5471b7fa40b8eeb3f3bc1e549b7f35f4ffcd6eb9f791d90dc7f6dd15f1fbfe8fd476dfd8fe0efe3fe431ffa6b77a097f8eb365dd1ffbefbbfaeffbefd8fe1afbfa3d9651c80e347f7df65f6bf91f5377fffa15d7fa3f945ea8f2771559067f2e9a1fe57e6470a90b3a0bfb983bf870d7867fc9e0e10baff99c7f24bdc80aed47f2d0499d38191ccf347e6fed3ec6dda2800acfc42cf3fadee3f04172002dbbf3efd73d18bdd7f8d3611fd2bda595f8fa5175aff0af047eb9fbdff7d5b510dfe080f5c97dfc6df76ff61c67f741411bf53ff3c1d2052ffbb1cf0f0775cff7b1c90d43f1b7fc70b2070ff5beef75f22f557ecf9db56fe00fdc3ef7f2af393030715feeaac9305f0c3cf5fadd43f3c7e587f97e38fdbfd65fdb59c7f63e31f3bea3ffffe4787fbbf5e13d1df72fbb5b500f1de0912d25f5b0f4cf9fa7fc4f6c0a9ffecf84b63f263f5a7e6fe9b8cfee93e00a4fefb1f1e077cf58fc4f33ff3fdff567a3277fca8fe78eb0fab0372fc07083fbafe1dfbf4bf537e7ffd67e31fc9ac3ffdfc96f04775fd8fd5dfdcc36f61cf57eb8fb85d007ffd69e7175dff36f923f43f427f4d6366fe595b83f8b91eacaeffd6d6960ef8cca2ffac6180fcfd2919fdd3d65fdd07803cfcdefa5f60fde5e02f4ff13980ea9ff71650d7fa375f8069f1cf1a73ecffdb1c381270a0f2fc85167ff5fecf68340aeeffbafec7df7fa5b60e2625ffa895bf9dbec11fbdff3cce677fffab3d7e0b7b1b7f94fe9af27ba6bf35fa7cddc5dfa63f6c0766fcebeb9386fe97f2cbe58fd1dfbc1a7fbe22bf7c7ebefe56f9fdfabf2c4bacfc8c2d0044fe2af79f587dbe127f34bdd0fd2ff70d0037bddcfac342ef73406cffd1caef70416efe75f33bf4e714f147afff7c8fe074cb5f63afcb0f8f3ffefeeb41b9ff50fcdbaebfaefa4b40ff2afa3b5a71c049dfa2bfb1fa67fefe675bfc16f676fe88f56f957fb5fec85f7238d0ca1fa3bfe38afe33f865f437afe96f117f4d7e1bfcebeb01facb7060b5fe28f86b0e34e20fe167dc0370de7ff7589d9fd1e92df1b75bd608dfce1f39ff7be49fc11f3bff47dfff179a7ffdfadfe5fcefed7fbb030dfe98fd4fe7affff4c01f547f04f203ebbf7ca6c298fe47de7f2d1b2bf71f2cfa1fcc1f7fff3542ffdbe75fa603e3e5ffbfd1a2ffa43f36769bfef23c30f3bf9cfe73d7bfd5fe67f10be9ef32fe207e71fd5dad3f6a2ef4c06fedde9cb7feece2f91337bf8cfec5c72f34ff47ff0a840cbf2f7ebb07c2fae3e0ef52ff42e20fe58f58ff39cbef1ef89d05681ffcb5df7f85f5ff88fdfc53ee5affe6ae2d4011fd5dfeff1badfc0bf2e9b4b1312ca3bf35fe95fdff4afd315ddd1997dd7f6eeeff1bfe08fde7e96f3eef80f24da4fe88d0ff257fad0088e567ff1e40bb6d6c60f8298847f9b5fdd78effbcfbaf3d7ef4f1b9ffa44ef931fc791fbf43c76b8f9f84d7cd7fedf13374fea1e3b5fb4f3fff503c9abf9803faf1ebe2cffbf83beff10f3f7fcf77fe6beb9f365ebbff878f47f3573dff2107f4fb3fe1111bfefc31f8fc831ad8001bf8efa7d9e7a6103f00ce86af7fdafc91f8db5278fdf8d5f317d4cf5ef27707c45b4d3b7f078a17cbbf38fcaddb2fcc7f8af31fc1eface0b9e953c7b3b367bb4c85cafc85e52f8a47f32fe53f8657d27f9dfcdd7eb581e7f19bb18ee0b757f09cf4294ede46f2bf89e7e5ef34cf76eaf3074fbe8babb5534f455efe15f8ed51047e7b6764f9668e8f9e02b4f3571fafb2feace81703bf6d82ad8d7f0ebe25ff99f9d7c4332230644b3c2b7fc8d91d4a8525fe191f1fcd3fa5584bfcc6e2fab1f26fc1bfec7383773730cfff0d9a7f46edf84f03835831edfcc1f1baf74f58fc3bcd328e953e3baf363ee2e117e7c6e9df4633ffb9f9b38ae7e46f891fd5eb0f36ff8afe73f2b7ac352cf91fd2c0023f6dc1bbf37767e9bf2dff5f8c4a24edfc13c85fd5f51f2b7fdaf31fc6070700e2dbc60a33ff1a0d30f3df860fcddf62fea87f1699bf0b3f38fa3bc38f2cf81703f00bfd6fc347e6bf6efef69a7fedfcf0fd9bbef2cf860f0e00c56f34f1bcfcb7ce1f81f96bc787e56ff3b305fe153f7ed15191f95be2b7b35ad270f2b764ddb1f2e7cffc21348cb57eea008fee5f0ecaff96fc3b25f8b0261cf8a006c0fc6b338efe965973cf86f7e6ef2c6bef66d6fc0bc2df8ac65754df92ff117dd8d3fd8baef1d14df48adf6eeee2f69a7f5de223f79f58fa49ffd8f3372c7fee46e397f91b577fcff017ec785ffe4e3bc87f21fd1b46fe39f0b10d88e143ae9d63fe08c2bbf217e50fc9bf96cf58f9333b635a3d31423fa7f42717daf0cf02f11b597bfdeecbbf0a1ec9dfda32a6868f9a834f3c96f0099ff0a7177f3c70ff133ee1133e1e9ff23fe1137eb878347f7d0e9cf6f8133ee1878cd7cedf94ff099ff0f178347fd5f3dfe300489ff009df297ef0f9e769c08f77371080777601187ec2277ca778f5fc05f5d3e74100ded94008de1502e47cc227bcc7069fbf78fe43faeb6b2004efeac47864c227fc39c87fbc7e87f5db154310ded100e2fb79c06baf3fd5f307c57b22f0e371fd44f1b8fec6e79faf8140bcb50f6271a1f8733ffe51bc7afd8ae2f1fc75b9108407ea5f5f0861783c7f6d0d84e26d0d443b1ecaaf8d1f7cfea078547f61fd565dbffa1a08c40f367f7d0d7861d69eeb099ff20fc4c3fbcf285e75fdea6b20101f5d3ffb3c08c6c7e6af278478cfc3f9513cac1f281e1dbff0f8d7c60f3fff06abbf4b43f1ad0ec43333f0eae31f1dbff0f8d7c6a3f9a75fffa2784b03e1f801e72f8cb7747e303ee50f8887f54f1b8feb278a3fcff96b0f60fed5dd7d4e432b7ead6793fb77e2f185138f1f7e17c27ffcc8fff761ac767c927df4701c8f2fec5ff72178f608c43f7e08c13f79fc1284ff37d2fdc94e81dd03f2375bffe4f103207f8f4f9e82f9fbfc3f0f80fc3d3e598f07cbd84718fce9c713553c3a7f648f307832d410fda7f183cc1f94ff083be53f82cfd0fc6715615d18187f81ff0c84c7ae1fcd1f183e196ab75e43d0cfd7eebee03fcb6a70fe3e5fc3f068fe3fc5f019e8bf40feebe2b397417c32d02ed8fe07b12083c72f863f46f110bab0e7285eb7fff0fc07f99369dbf66711b4faf845f1181c36f5f853fe9e7783fe9b9dc1eb1f064f962c1960caf3c731cc0fe293254b166d68fe6ae393254b166fdaf9ab8e479f5f507ffe2159b2e19a7afe6be3c1f9431b9f2c1962f0f8d5cedf84d7c5a7f9eb7cdbc0f5131dff2709af8a4f960c3174fec0c73ff8fc278c87e0eaf864c9104bf90fc1d5f1c9922186d7ffdaf9ab9bff9aebb70b4bbb78e9caebd7ab8797ae5e3bac1eef1e5cbfb13cbeb4bbf7fae18dead77bd70e6f568ef7f6afdda81cefeeed5fbf71ab02dfbf7cfd66e5786ffff2e1e2f8e2c5fd2b07d76ebef1e6fce812f97678ebdb6f19aeddabd76fdc7ce3addbe670efa000bf79fb4e79f6dee52b570f0bf0ed3b6f97715cbe5ab6551cbe4d4ded5e3928da2a0fbfb3f9c75f5e285f7ff8c5b7367ff393af6dbeffc32f6d3eb8f7d5cd77bfff85cdf77ef0c5f2b3dffdec1be5f70f7fbd5b9efbd777f737ff7cffd2e69f7e75b13c36e77cf8e3af2cdee9f5c18fbe5cbe1b2c61e8e72a1f7d46c7bffde9d7cbf3e945bc744cdf932ff4fafdcfbfb938d7bce87b6a97380943af77bef75af939f94f6dd177f432fed2cfd577f283da270c9d6fb0f419f94efd41be5431745cf8b365e2228c899770e483698bdec95783233fe855e04abcf98c7888975ef4b3e1357dfa9777f6ca77ea076a6fde46796cda212e3a3631d3e7744ce7d1cf7f7bef72f9fac70757cb776a93aea56983de4dcce61ad2e7868bcefffbfb57ca9f291e3aa677131b9d6fae17e1e8736ad38c13c29a971947c607331e8cdf669cd08bce31e7198c39e79f1f1e2cf0c617e32bf94ded55fbdff48de977c2527f10c68c6bc29a18cd98a7cfcd982ce2dca297e91b83317d427d6bda32d7cbf46fd1c656c1bf55f4f196191b2646931f86db5c4bea4f3a97ae0b8d71e22ec618f9b0e0a88eadf978d82adad8227fcd18a7b6e6e3abc417afff0309a69f37";
			string test3 = "7801EDDC310D00000803B02508C0BF5B828A3DAD904E920900000000000000000000000000000000000000000000000000000000000000F016000000000000000000000000000000A86BFF03000000000000000000000000000000000000000000000000000000000000000040CF01072DC034";

			//$ordered = zlib_encode(
			//int chunkX) . 
			//int chunkZ) . 
			//$orderedIds . 
			//$orderedData . 
			//$orderedSkyLight .
			//$orderedLight . 
			//$this->biomeIds . 
			//$biomeColors . 
			//$this->tiles


			byte[] val = SoapHexBinary.Parse(test).Value;
			Assert.IsNotNull(val);


			MemoryStream stream = new MemoryStream(val);
			if (stream.ReadByte() != 0x78)
			{
				throw new InvalidDataException("Incorrect ZLib header. Expected 0x78 0x9C");
			}
			stream.ReadByte();
			using (var defStream2 = new DeflateStream(stream, CompressionMode.Decompress, false))
			{
				NbtBinaryReader defStream = new NbtBinaryReader(defStream2, true);
				ChunkColumn chunk = new ChunkColumn();

				chunk.x = IPAddress.NetworkToHostOrder(defStream.ReadInt32());
				chunk.z = IPAddress.NetworkToHostOrder(defStream.ReadInt32());

				int chunkSize = 16*16*128;
				Assert.AreEqual(chunkSize, defStream.Read(chunk.blocks, 0, chunkSize));
				Assert.AreEqual(chunkSize/2, defStream.Read(chunk.metadata.Data, 0, chunkSize/2));
				Assert.AreEqual(chunkSize/2, defStream.Read(chunk.skylight.Data, 0, chunkSize/2));
				Assert.AreEqual(chunkSize/2, defStream.Read(chunk.blocklight.Data, 0, chunkSize/2));

				Assert.AreEqual(256, defStream.Read(chunk.biomeId, 0, 256));

				byte[] ints = new byte[256*4];
				Assert.AreEqual(ints.Length, defStream.Read(ints, 0, ints.Length));
				int j = 0;
				for (int i = 0; i < ints.Length; i = i + 4)
				{
					chunk.biomeColor[j++] = BitConverter.ToInt32(new[] {ints[i], ints[i + 1], ints[i + 2], ints[i + 3]}, 0);
				}

				MemoryStream uncompressed = new MemoryStream();
				int b = -1;
				do
				{
					b = defStream2.ReadByte();
					if (b != -1) uncompressed.WriteByte((byte) b);
				} while (b != -1);

				Assert.AreEqual(0, uncompressed.Length);
				//Assert.AreEqual(83208, uncompressed.Length);
				Assert.AreEqual(8, chunk.x);
				Assert.AreEqual(9, chunk.z);
				byte[] data = chunk.GetBytes();
				Assert.AreEqual(83208, data.Length); // Expected uncompressed length
			}
		}
Example #15
0
    /// <summary>
    ///  Retrieves the AuthnRequest from the encoded and compressed String extracted
    ///  from the URL. The AuthnRequest XML is retrieved in the following order: 
    ///  1. URL decode  2. Base64 decode  3. Inflate  
    ///  Returns the String format of the AuthnRequest XML.
    /// </summary>
    /// <param name="encodedRequestXmlString"></param>
    /// <returns></returns>
    public String decodeAuthnRequestXML(String encodedRequestXmlString)
    {
        //URL decode
        //   Page urlDecode = new Page();

        //   encodedRequestXmlString = urlDecode.Server.UrlDecode(encodedRequestXmlString);

        //Base64 decode
        String decode = "";

        byte[] bytes = Convert.FromBase64String(encodedRequestXmlString);

        //inflate decode
        System.IO.MemoryStream ms = new MemoryStream(bytes);

        //    ms.Position = 0;

        System.IO.Compression.DeflateStream ds = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Decompress,false);

        byte[] bytes2 = new byte[20000];

        int c;

        int resultLength = 0;

        while ((c = ds.ReadByte()) >= 0)
        {
            if (resultLength >= 20000)
            {
                throw new Exception("didn't allocate enough space to hold decompressed data");
            }
            bytes2[resultLength++] = (byte)c;
        }

        //ds.Read(bytes2, 0, bytes.Length);

        //ds.Close();

        decode = System.Text.Encoding.UTF8.GetString(bytes2,0,resultLength);

        return decode;
    }
Example #16
0
        // internal for testing
        internal static unsafe ImmutableArray<byte> DecodeEmbeddedPortablePdbDebugDirectoryData(AbstractMemoryBlock block)
        {
            byte[] decompressed;
            
            const int headerSize = 2 * sizeof(int);

            var headerReader = new BlobReader(block.Pointer, headerSize);

            if (headerReader.ReadUInt32() != PortablePdbVersions.DebugDirectoryEmbeddedSignature)
            {
                throw new BadImageFormatException(SR.UnexpectedEmbeddedPortablePdbDataSignature);
            }

            int decompressedSize = headerReader.ReadInt32();

            try
            {
                decompressed = new byte[decompressedSize];
            }
            catch
            {
                throw new BadImageFormatException(SR.DataTooBig);
            }

            var compressed = new ReadOnlyUnmanagedMemoryStream(block.Pointer + headerSize, block.Size - headerSize);
            var deflate = new DeflateStream(compressed, CompressionMode.Decompress, leaveOpen: true);

            if (decompressedSize > 0)
            {
                int actualLength;

                try
                {
                    actualLength = deflate.TryReadAll(decompressed, 0, decompressed.Length);
                }
                catch (InvalidDataException e)
                {
                    throw new BadImageFormatException(e.Message, e.InnerException);
                }

                if (actualLength != decompressed.Length)
                {
                    throw new BadImageFormatException(SR.SizeMismatch);
                }
            }

            // Check that there is no more compressed data left, 
            // in case the decompressed size specified in the header is smaller 
            // than the actual decompressed size of the data.
            if (deflate.ReadByte() != -1)
            {
                throw new BadImageFormatException(SR.SizeMismatch);
            }

            return ImmutableByteArrayInterop.DangerousCreateFromUnderlyingArray(ref decompressed);
        }