Ejemplo n.º 1
0
    static void DecompressProfile(string srcfile, string dstfile)
    {
        try
        {
            Console.WriteLine("Reading source...");
            byte[] x = File.ReadAllBytes(srcfile); // load all bytes
            byte[] y = new byte[x.Length-0x1A];

            Console.WriteLine("Copying array...");
            Array.Copy(x, 0x1A, y, 0, y.Length); // skip hash (0x14) + uncompresed size (0x4) + zlib compression type (0x2) = 0x1A

            Console.WriteLine("Initializing streams...");
            DeflateStream defStream = new DeflateStream(new MemoryStream(y),CompressionMode.Decompress);
            FileStream fs = File.Create(dstfile);

            Console.WriteLine("Decompressing data to destination...");
            defStream.CopyTo(fs);

            Console.WriteLine("Decompression done.\n" + dstfile);
            defStream.Close();
            fs.Close();
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.GetType().Name + " | " + ex.Message);
            Console.Beep();
        }
        return;
    }
		// netz.compress.ICompress implementation

		public long Compress(string file, string zipFile)
		{
			long length = -1;
			FileStream ifs = null;
			FileStream ofs = null;
			try
			{
				ifs = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read);
				ofs = File.Open(zipFile, FileMode.Create, FileAccess.Write, FileShare.None);
				DeflateStream dos = new DeflateStream(ofs, CompressionMode.Compress, true);
				byte[] buff = new byte[ifs.Length];
				while(true)
				{
					int r = ifs.Read(buff, 0, buff.Length);
					if(r <= 0) break;
					dos.Write(buff, 0, r);
				}
				dos.Flush();
				dos.Close();
				length = ofs.Length;
			}
			finally
			{
				if(ifs != null) ifs.Close();
				if(ofs != null) ofs.Close();
			}
			return length;
		}
Ejemplo n.º 3
0
    public static byte[] Decompress(byte[] data)
    {
        try
        {
            string result = string.Empty;
            byte[] buffer = { };

            MemoryStream ms = new MemoryStream(data);
            Stream s = new DeflateStream(ms, CompressionMode.Decompress);

            int len = 4096;

            while (true)
            {
                int oldLen = buffer.Length;
                Array.Resize(ref buffer, oldLen + len);
                int size = s.Read(buffer, oldLen, len);
                if (size != len)
                {
                    Array.Resize(ref buffer, buffer.Length - (len - size));
                    break;
                }
                if (size <= 0)
                    break;
            }
            s.Close();

            return buffer;
        }
        catch
        {
            return null;
        }
    }
Ejemplo n.º 4
0
        public override void Close()
        {
            if (!initdone)
            {
                DoInit(); // can happen if never called write
            }

            if (closed)
            {
                return;
            }

            closed = true;
            deflateStream?.Close();
            if (crcread is null)
            { // eat trailing 4 bytes
                crcread = new byte[4];
                for (var i = 0; i < 4; i++)
                {
                    crcread[i] = (byte)rawStream.ReadByte();
                }
            }

            if (!LeaveOpen)
            {
                rawStream.Close();
            }
        }
Ejemplo n.º 5
0
 static void CompressProfile(string srcfile, string dstfile)
 {
     try
     {
         Console.WriteLine("Reading source...");
         byte[] x = File.ReadAllBytes(srcfile);
         int usize = x.Length;
         Console.WriteLine("Initializing memory stream...");
         MemoryStream ms = new MemoryStream();
         // write uncompressed size as big endian
         ms.WriteByte((byte)((usize>>24) & 0xFF));
         ms.WriteByte((byte)((usize>>16) & 0xFF));
         ms.WriteByte((byte)((usize>>8) & 0xFF));
         ms.WriteByte((byte)(usize & 0xFF));
         // then, compressed data
         // these two bytes are part of zlib standard, but aren't supported by DeflateStream
         ms.WriteByte(0x78);
         ms.WriteByte(0x9C);
         Console.WriteLine("Compressing data...");
         MemoryStream compData = new MemoryStream();
         DeflateStream ds = new DeflateStream(compData, CompressionMode.Compress);
         ds.Write(x, 0, x.Length);
         ds.Close();
         ms.Write(compData.ToArray(), 0, compData.ToArray().Length);
         // Adler32 checksum as big endian - also not supported by DeflateStream, but required by zlib standard
         int checksum = GetAdler32(x);
         ms.WriteByte((byte)((checksum>>24) & 0xFF));
         ms.WriteByte((byte)((checksum>>16) & 0xFF));
         ms.WriteByte((byte)((checksum>>8) & 0xFF));
         ms.WriteByte((byte)(checksum & 0xFF));
         // start filestream
         Console.WriteLine("Creating file stream...");
         FileStream fs = File.Create(dstfile);
         // write hash
         fs.Write(new SHA1CryptoServiceProvider().ComputeHash(ms.ToArray()), 0, 0x14);
         // write usize + compressed data
         fs.Write(ms.ToArray(), 0, ms.ToArray().Length);
         Console.WriteLine("Compression done.\n" + dstfile);
         fs.Close();
         ms.Close();
         compData.Close();
     }
     catch(Exception ex)
     {
         Console.WriteLine(ex.GetType().Name + " | " + ex.Message);
         Console.Beep();
     }
     return;
 }
Ejemplo n.º 6
0
    public static byte[] Compress(byte[] data)
    {
        try
        {
            MemoryStream ms = new MemoryStream();
            Stream s = new DeflateStream(ms, CompressionMode.Compress);

            s.Write(data, 0, data.Length);
            s.Close();

            return ms.ToArray();
        }
        catch
        {
            return null;
        }
    }
Ejemplo n.º 7
0
    public static byte[] Compress(byte[] data)
    {
        try
        {
            //Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.RealTime;

            MemoryStream ms = new MemoryStream();
            Stream s = new DeflateStream(ms, CompressionMode.Compress);

            s.Write(data, 0, data.Length);
            s.Close();

            //Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.Normal;

            return ms.ToArray();
        }
        catch
        {
            //Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.Normal;
            return null;
        }
    }
Ejemplo n.º 8
0
        /// <summary> </summary>
        public static byte[] Compress(byte[] datas, int len)
        {
            MemoryStream  stream = new MemoryStream(), comp = new MemoryStream();
            DeflateStream zlib = new DeflateStream(comp, CompressionMode.Compress);

            byte[] aComp, result;
            zlib.Write(datas, 0, len);
            zlib.Flush();
            zlib.Close();

            aComp = comp.ToArray();

            stream.WriteByte(0);
            stream.WriteByte(0x78); // Z_DEFLATE(8)    | (0x7 << 4)
            stream.WriteByte(0x9C); // Z_CHECK(11100b) | (Z_DIR(0) << 5) | (Z_LEVEL(2) << 6);
            stream.Write(aComp, 0, aComp.Length);

            result = stream.ToArray();
            stream.Dispose();
            comp.Dispose();
            zlib.Dispose();
            return(result);
        }
Ejemplo n.º 9
0
 private string UnzipContent(string emrContent)
 {
     try
     {
         if (emrContent == string.Empty)
         {
             return("");
         }
         byte[]        rbuff = Convert.FromBase64String(emrContent);
         MemoryStream  ms    = new MemoryStream(rbuff);
         DeflateStream dfs   = new DeflateStream(ms, CompressionMode.Decompress, true);
         StreamReader  sr    = new StreamReader(dfs, Encoding.UTF8);
         string        sXml  = sr.ReadToEnd();
         sr.Close();
         dfs.Close();
         return(sXml);
     }
     catch (Exception e)
     {
         System.Diagnostics.Trace.WriteLine(e);
         return(emrContent);
     }
 }
Ejemplo n.º 10
0
        protected virtual byte[] Unzip(byte[] zippedBytes)
        {
            MemoryStream  memoryStream1 = new MemoryStream(zippedBytes);
            DeflateStream deflateStream = new DeflateStream((Stream)memoryStream1, CompressionMode.Decompress, true);
            MemoryStream  memoryStream2 = new MemoryStream();

            byte[] buffer = new byte[4096];
            int    count;

            do
            {
                count = deflateStream.Read(buffer, 0, 4096);
                if (count > 0)
                {
                    memoryStream2.Write(buffer, 0, count);
                }
            }while (count == 4096);
            deflateStream.Close();
            byte[] array = memoryStream2.ToArray();
            memoryStream2.Close();
            memoryStream1.Close();
            return(array);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// DataSet - > Byte[] Compress
        /// </summary>
        /// <param name="dsData"></param>
        /// <returns></returns>
        public static byte[] CompressDataSet(DataSet dsData)
        {
            //DataSet Serialize
            dsData.RemotingFormat = SerializationFormat.Binary;
            BinaryFormatter bf = new BinaryFormatter();

            using (MemoryStream ms = new MemoryStream())
            {
                bf.Serialize(ms, dsData);
                byte[] bytData = ms.ToArray();
                //Data Compress
                using (MemoryStream objMs = new MemoryStream())
                {
                    using (DeflateStream objDs = new DeflateStream(objMs, CompressionMode.Compress))
                    {
                        objDs.Write(bytData, 0, bytData.Length);
                        objDs.Flush();
                        objDs.Close();
                    }
                    return(objMs.ToArray());
                }
            }
        }
Ejemplo n.º 12
0
        public void Load()
        {
            var file = _world.Folder + Path.DirectorySeparatorChar + FileName;

            if (!File.Exists(file))
            {
                return;
            }

            var stream    = new DeflateStream(File.Open(file, FileMode.Open, FileAccess.Read), CompressionMode.Decompress);
            var formatter = new BinaryFormatter();
            var version   = (uint)formatter.Deserialize(stream);

            while ((bool)formatter.Deserialize(stream))
            {
                var position = (Vector3i)formatter.Deserialize(stream);
                var value    = new UnloadedChunkGeneration();
                value.Load(stream, formatter);
                _generations.TryAdd(position, value);
            }

            stream.Close();
        }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            FileStream archiveStream = File.OpenRead(@"D:\archive_dfl.dfl");

            FileStream destinationStream = File.Create(@"D:\txt_destnation_dfl.txt");

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

            //В прошлых примерах цикл бы неправильный! нужно  do - while
            do
            {
                var theByte = deCompressor.ReadByte();
                if (theByte == -1)
                {
                    break;
                }
                destinationStream.WriteByte((byte)theByte);
            }while (true); //появлялось"я" в файле, потому, что оно записывало -1. пришлось сделать do - while (true) и выход из цикла.


            deCompressor.Close();
            destinationStream.Close();
        }
Ejemplo n.º 14
0
 /// <summary>
 /// Deflate压缩
 /// </summary>
 /// <param name="buffer">字节流</param>
 public static byte[] DeflateCompress(byte[] data)
 {
     if (data == null || data.Length < 1)
     {
         return(data);
     }
     try
     {
         using (MemoryStream stream = new MemoryStream())
         {
             using (DeflateStream gZipStream = new DeflateStream(stream, CompressionMode.Compress))
             {
                 gZipStream.Write(data, 0, data.Length);
                 gZipStream.Close();
             }
             return(stream.ToArray());
         }
     }
     catch (Exception)
     {
         return(data);
     }
 }
Ejemplo n.º 15
0
        public static string Decompress(Stream inputStream, Encoding encoding, int bufferSize)
        {
            using (MemoryStream decompressedStream = new MemoryStream((int)inputStream.Length * 4))
            {
                DeflateStream gzip = new DeflateStream(inputStream, CompressionMode.Decompress, true);

                byte[] buffer = new byte[bufferSize];
                while (true)
                {
                    int readBytes = gzip.Read(buffer, 0, bufferSize);
                    if (readBytes <= 0)
                    {
                        break;
                    }
                    //decompressed.Append(encoding.GetString(buffer, 0, readBytes));
                    decompressedStream.Write(buffer, 0, readBytes);
                }
                gzip.Close();

                decompressedStream.Position = 0;
                return(encoding.GetString(decompressedStream.GetBuffer(), 0, (int)decompressedStream.Length));
            }
        }
Ejemplo n.º 16
0
        [Category("StaticLinkedAotNotWorking")]          // Native MPH loading issues
        public void CheckCompressDecompress()
        {
            byte [] data = new byte[100000];
            for (int i = 0; i < 100000; i++)
            {
                data[i] = (byte)i;
            }
            MemoryStream  dataStream  = new MemoryStream(data);
            MemoryStream  backing     = new MemoryStream();
            DeflateStream compressing = new DeflateStream(backing, CompressionMode.Compress, true);

            CopyStream(dataStream, compressing);
            dataStream.Close();
            compressing.Close();
            backing.Seek(0, SeekOrigin.Begin);
            DeflateStream decompressing = new DeflateStream(backing, CompressionMode.Decompress);
            MemoryStream  output        = new MemoryStream();

            CopyStream(decompressing, output);
            Assert.IsTrue(compare_buffers(data, output.GetBuffer(), (int)output.Length));
            decompressing.Close();
            output.Close();
        }
Ejemplo n.º 17
0
        public static byte[] Decrypt(byte[] data, string key, string salt)
        {
            byte[] dec;

            try
            {
                dec = DecryptData(data, key, salt, PaddingMode.ISO10126);
            }
            catch (Exception e)
            {
                throw e;
            }

            int d_len = BitConverter.ToInt32(dec, 0);

            MemoryStream ms = new MemoryStream(dec);

            ms.Position = 4;

            // Use the newly created memory stream for the compressed data.
            DeflateStream compressedzipStream = new DeflateStream(ms, CompressionMode.Decompress, true);

            //Console.WriteLine("Compression");
            byte[] zdec = new byte[d_len];
            int    cnt  = compressedzipStream.Read(zdec, 0, d_len);

            // Close the stream.
            compressedzipStream.Close();
            ms.Close();

            dec = new byte[cnt];
            Array.ConstrainedCopy(zdec, 0, dec, 0, cnt);

            zdec = null;

            return(dec);
        }
Ejemplo n.º 18
0
        public void SaveBin(string _fileName)
        {
            TaxonUtils.LockMainWindow();
            try
            {
                using (ProgressDialog progressDlg = new ProgressDialog())
                {
                    progressDlg.StartPosition = FormStartPosition.CenterScreen;
                    progressDlg.Show();

                    ProgressItem piSave = progressDlg.Add("Saving ...", null, 0, Count());
                    using (FileStream fs = File.Create(_fileName, 65536, FileOptions.None))
                    {
                        using (DeflateStream deflateStream = new DeflateStream(fs, CompressionMode.Compress))
                        {
                            using (BinaryWriter w = new BinaryWriter(deflateStream))
                            //using (BinaryWriter w = new BinaryWriter(fs))
                            {
                                w.Write(SaveBinVersion);
                                SaveBin(w, new SaveBinProgress(piSave));
                                w.Close();
                                deflateStream.Close();
                                fs.Close();
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Loggers.WriteError(LogTags.Data, "Exception while saving config file : \n    " + _fileName + "\n" + e.Message);
            }
            finally
            {
                TaxonUtils.UnlockMainWindow();
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// 解压缩字节数组.
        /// </summary>
        private void uncompress(string algorithm = "deflate")
        {
            position = 0;

            if (algorithm == "zlib")
            {
                int firstByte = _memoryStream.ReadByte();

                int secondByte = _memoryStream.ReadByte();

                if (((firstByte == 0x78) && (secondByte == 0x9C)) || ((firstByte == 0x78) && (secondByte == 0xDA)) || ((firstByte == 0x58) && (secondByte == 0x85)))
                {
                }
                else
                {
                    position = 0;
                }
            }

            DeflateStream deflateStream = new DeflateStream(_memoryStream, CompressionMode.Decompress, false);

            MemoryStream ms = new MemoryStream();

            deflateStream.CopyTo(ms);

            deflateStream.Close();

            _memoryStream.Close();

            _memoryStream.Dispose();

            _memoryStream = ms;

            _memoryStream.Position = 0;

            Reset();
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Compresses data into zlib format.
        /// </summary>
        /// <param name="data">Byte data to be compressed.</param>
        internal static byte[] CompressZlibData(byte[] data)
        {
            int Adler32(byte[] buf)
            {
                // Source: https://tools.ietf.org/html/rfc1950#page-6
                const int mod = 65521;
                int       s1  = 1;
                int       s2  = 0;

                foreach (var b in buf)
                {
                    s1 = (s1 + b) % mod;
                    s2 = (s2 + s1) % mod;
                }
                return(IPAddress.HostToNetworkOrder((s2 << 16) + s1));
            }

            using (var compressedData = new MemoryStream())
                using (var decompressedData = new MemoryStream(data))
                    using (var deflater = new DeflateStream(compressedData, CompressionMode.Compress, true))
                    {
                        // zlib 2 byte header: CMF + FLG
                        compressedData.WriteByte(0x78); // CMF = deflate + 32k window
                        compressedData.WriteByte(0x9c); // FLG = ? obtained from the reader

                        decompressedData.CopyTo(deflater);
                        deflater.Close(); // DeflateStream needs to be closed in order to write the compressed data

                        // write adler32 checksum
                        using (var binaryWriter = new BinaryWriter(compressedData))
                        {
                            binaryWriter.Write(Adler32(data));
                        }

                        return(compressedData.ToArray());
                    }
        }
Ejemplo n.º 21
0
        /// <summary>
        ///     Loads the Manifest state from the provided File.
        /// </summary>
        /// <remarks>
        ///     This method expects a DEFLATE-compressed XML binary.
        /// </remarks>
        /// <returns>
        ///     Instance of a Manifest type.
        /// </returns>
        /// <exception cref="FileNotFoundException">
        ///     Specified manifest binary does not exist on the filesystem.
        /// </exception>
        public Manifest Load()
        {
            byte[] Inflate(byte[] deflatedBytes)
            {
                using (var inflatedStream = new MemoryStream())
                    using (var deflatedStream = new MemoryStream(deflatedBytes))
                        using (var compressStream = new DeflateStream(deflatedStream, CompressionMode.Decompress))
                        {
                            compressStream.CopyTo(inflatedStream);
                            compressStream.Close();
                            return(inflatedStream.ToArray());
                        }
            }

            if (!System.IO.File.Exists(_file))
            {
                throw new FileNotFoundException("Specified manifest binary does not exist on the filesystem.");
            }

            var deflatedData = System.IO.File.ReadAllBytes(_file);
            var inflatedData = Inflate(deflatedData);
            var utf8AsString = Encoding.UTF8.GetString(inflatedData);

            var serializer = new XmlSerializer(typeof(Manifest));

            using (var reader = new StringReader(utf8AsString))
            {
                try
                {
                    return((Manifest)serializer.Deserialize(reader));
                }
                catch (InvalidOperationException)
                {
                    throw new ManifestException("Failed to deserialise decompressed metadata binary.");
                }
            }
        }
Ejemplo n.º 22
0
        /// <exclude />
        public static string ZipContent(string text)
        {
            if (text.IsNullOrEmpty())
            {
                return(text);
            }

            byte[] bytes = Encoding.UTF8.GetBytes(text);

            byte[] newBytes;

            using (var compressStream = new MemoryStream())
                using (var compressor = new DeflateStream(compressStream, CompressionMode.Compress))
                {
                    compressor.Write(bytes, 0, bytes.Length);
                    compressor.Close();
                    newBytes = compressStream.ToArray();
                }

            string base64 = Convert.ToBase64String(newBytes);

            if (base64.Length <= 512)
            {
                string urlFriendlyBase64 = base64.Replace("+", "_").Replace("/", ".").Replace("=", "-");

                return(urlFriendlyBase64);
            }

            Guid stateId = GetMD5Hash(bytes);

            using (new DataConnection())
            {
                SessionStateManager.DefaultProvider.SetState(stateId, text, DateTime.Now.AddHours(1.0));
            }

            return(SessionUrlPrefix + stateId);
        }
Ejemplo n.º 23
0
        public static String unDeflate(byte[] data, int len, Encoding encoding, String index)
        {
            String        str    = "";
            MemoryStream  ms     = new MemoryStream(data, 0, len);
            DeflateStream ds     = new DeflateStream(ms, CompressionMode.Decompress);
            MemoryStream  outbuf = new MemoryStream();

            byte[] block = new byte[1024];

            try
            {
                while (true)
                {
                    int bytesRead = ds.Read(block, 0, block.Length);
                    if (bytesRead <= 0)
                    {
                        break;
                    }
                    else
                    {
                        outbuf.Write(block, 0, bytesRead);
                    }
                }
                str = encoding.GetString(outbuf.ToArray());
            }
            catch (Exception e)
            {
                Tools.SysLog("解压deflate发生异常----" + e.Message + "----" + index);
            }
            finally
            {
                outbuf.Close();
                ds.Close();
                ms.Close();
            }
            return(str);
        }
Ejemplo n.º 24
0
    public static void WriteFile(string str, string FileName, string CompressionType)
    {
        byte[] buffer = System.Text.Encoding.ASCII.GetBytes(str);

        switch (CompressionType)
        {
        case "gzip":
        {
            FileStream sw = new FileStream(FileName, FileMode.Create);
            GZipStream gz = new GZipStream(sw, CompressionMode.Compress);
            gz.Write(buffer, 0, buffer.Length);
            gz.Close();
            sw.Close();
        }
        break;

        case "deflate":
        {
            FileStream    sw = new FileStream(FileName, FileMode.Create);
            DeflateStream dz = new DeflateStream(sw, CompressionMode.Compress);
            dz.Write(buffer, 0, buffer.Length);
            dz.Close();
            sw.Close();
        }
        break;

        default:
        {
            StreamWriter sw = new StreamWriter(FileName, false);
            sw.Write(str);
            sw.Close();
        }
        break;
        }

        File.SetCreationTime(FileName, DateTime.Now);
    }
Ejemplo n.º 25
0
        //public static string ToDeflatedCompressedBase64String(string inp, string ns)
        //{
        //    StringBuilder sb = new StringBuilder();
        //    TextWriter textWriter = (TextWriter)new StringWriter(sb);
        //    new XmlSerializer(typeof(string), ns).Serialize(textWriter, (object)inp);
        //    textWriter.Close();
        //    sb.ToString();
        //    Deflater deflater = new Deflater(1, true);
        //    MemoryStream memoryStream = new MemoryStream();
        //    byte[] buffer = new byte[256];
        //    deflater.SetInput(new UnicodeEncoding().GetBytes(inp));
        //    deflater.Flush();
        //    int count;
        //    do
        //    {
        //        count = deflater.Deflate(buffer, 0, buffer.Length);
        //        memoryStream.Write(buffer, 0, count);
        //    }
        //    while (count > 0);
        //    return Convert.ToBase64String(memoryStream.ToArray());
        //}

        public static string CompressedBase64ToUnicode(string compressed)
        {
            try
            {
                using (MemoryStream memoryStream1 = new MemoryStream(Convert.FromBase64String(compressed)))
                {
                    DeflateStream deflateStream = new DeflateStream((Stream)memoryStream1, CompressionMode.Decompress, true);
                    byte[]        buffer        = new byte[256];
                    MemoryStream  memoryStream2 = new MemoryStream();
                    int           count;
                    do
                    {
                        count = deflateStream.Read(buffer, 0, buffer.Length);
                        memoryStream2.Write(buffer, 0, count);
                    }while (count > 0);
                    deflateStream.Close();
                    return(new UnicodeEncoding().GetString(memoryStream2.ToArray()));
                }
            }
            catch
            {
                return(string.Empty);
            }
        }
Ejemplo n.º 26
0
        public override void Close()
        {
            if (!initdone)
            {
                DoInit(); // can happen if never called write
            }

            if (closed)
            {
                return;
            }

            closed = true;
            // sigh ... no only must I close the parent stream to force a flush, but I must save a reference
            // raw stream because (apparently) Close() sets it to null (shame on you, MS developers)
            if (deflateStream is object)
            {
                deflateStream.Close();
            }
            else
            {         // second hack: empty input?
                RawStream.WriteByte(3);
                RawStream.WriteByte(0);
            }
            // add crc
            var crcv = adler32.GetValue();

            RawStream.WriteByte((byte)((crcv >> 24) & 0xFF));
            RawStream.WriteByte((byte)((crcv >> 16) & 0xFF));
            RawStream.WriteByte((byte)((crcv >> 8) & 0xFF));
            RawStream.WriteByte((byte)(crcv & 0xFF));
            if (!LeaveOpen)
            {
                RawStream.Close();
            }
        }
Ejemplo n.º 27
0
        public static void ImageCreate()
        {
            Byte[] preData;

            while (!standardSignalObj.IsShutdown)
            {
                bmp = new Bitmap(sc[selectedScreen].WorkingArea.Width, sc[selectedScreen].WorkingArea.Height);
                g   = Graphics.FromImage(bmp);

                try
                {
                    g.CopyFromScreen(new Point(sc[selectedScreen].Bounds.X, sc[selectedScreen].Bounds.Y),
                                     new Point(0, 0), new Size(bmp.Width, bmp.Height));
                } // 가상 데스크톱으로 이동하면 화면을 복사하지 않음.
                catch (Win32Exception) { }

                using (MemoryStream pre_ms = new MemoryStream())
                {
                    bmp.Save(pre_ms, codec, param);
                    preData = pre_ms.ToArray();

                    using (MemoryStream post_ms = new MemoryStream())
                    {
                        using (DeflateStream ds = new DeflateStream(post_ms, CompressionMode.Compress))
                        {
                            ds.Write(preData, 0, preData.Length);
                            ds.Close();
                        }
                        imageData = post_ms.ToArray();
                        post_ms.Close();
                    }
                    pre_ms.Close();
                }
                Array.Clear(preData, 0, preData.Length);
            }
        }
Ejemplo n.º 28
0
        public static byte[] Compress3(byte[] data)
        {
            byte[] compressArray = null;

            try
            {
                using (var memoryStream = new MemoryStream())
                {
                    using (var deflateStream = new DeflateStream(memoryStream, CompressionMode.Compress))
                    {
                        deflateStream.Write(data, 0, data.Length);
                        deflateStream.Close(); //Must!
                    }

                    compressArray = memoryStream.ToArray();
                }
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Error while compressing the channel.");
            }

            return(compressArray);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// 解压文件
        /// </summary>
        /// <param name="filepath">源文件</param>
        /// <param name="dir">目标目录</param>
        /// <returns></returns>
        public void DerFileZip(Stream sourstream, string filepath, int filelen)
        {
            FileStream SerFile = null;

            try
            {
                if (!System.IO.File.Exists(filepath))
                {
                    throw new Exception("解压失败:指定的文件路径(" + filepath + ")不正确");
                }
                byte[] buffer   = new byte[filelen];
                string filename = System.IO.Path.GetFileNameWithoutExtension(filepath);//获取文件名

                CompressedStream = new DeflateStream(sourstream, CompressionMode.Decompress, true);

                int br = CompressedStream.Read(buffer, 0, filelen);

                SerFile = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.Write);
                SerFile.Write(buffer, 0, filelen);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (SerFile != null)
                {
                    SerFile.Close();
                }
                if (CompressedStream != null)
                {
                    CompressedStream.Close();
                }
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// The byte array to data table.
        /// </summary>
        /// <param name="byteDataTable">
        /// The byte data table.
        /// </param>
        /// <returns>
        /// The <see cref="DataTable"/>.
        /// </returns>
        public static DataTable ByteArrayToDataTable(byte[] byteDataTable)
        {
            var outDs = new DataTable();

            var inMs = new MemoryStream(byteDataTable);

            inMs.Seek(0, 0);
            var zipStream = new DeflateStream(inMs, CompressionMode.Decompress, true);

            var outByt = ReadFullStream(zipStream);

            zipStream.Flush();
            zipStream.Close();

            var outMs = new MemoryStream(outByt);

            outMs.Seek(0, 0);
            outDs.RemotingFormat = SerializationFormat.Binary;
            var bf = new BinaryFormatter();

            outDs = (DataTable)bf.Deserialize(outMs, null);

            return(outDs);
        }
        public void PerformPostProcessing(IDictionary <string, object> chunkProcessorState)
        {
            var chunkName = this.GetChunkName();

            if (!chunkProcessorState.ContainsKey(chunkName))
            {
                throw new ArgumentException($"Cannot read {chunkName} key from processor state.");
            }

            var stream = chunkProcessorState[chunkName] as Stream;

            stream.Flush();
            stream.Seek(2, SeekOrigin.Begin);

            var outputStream = new MemoryStream();

            using (var deflateStream = new DeflateStream(stream, CompressionMode.Decompress))
            {
                deflateStream.CopyTo(outputStream);
                deflateStream.Close();
            }

            chunkProcessorState.Add(this.GetOutputStreamKey(), outputStream);
        }
Ejemplo n.º 32
0
        public void Save()
        {
            const uint version       = 0;
            var        regionsFolder = _world.Folder + Path.DirectorySeparatorChar + World2dRegionFolder;

            FolderUtils.CreateRegionFolderIfNotExist(regionsFolder);
            var file = regionsFolder + Path.DirectorySeparatorChar + _position.X + "-" + _position.Y + ".reg";

            var stream = new DeflateStream(File.Open(file, FileMode.OpenOrCreate, FileAccess.Write),
                                           CompressionMode.Compress);
            var formatter = new BinaryFormatter();

            formatter.Serialize(stream, version);

            for (var x = 0; x < RegionLength; x++)
            {
                for (var z = 0; z < RegionLength; z++)
                {
                    var biome              = _biomes[x, z];
                    var height             = _heights[x, z];
                    var interpolatedHeight = _interpolatedHeights[x, z];
                    var interpolatedColor  = _interpolatedGrassColors[x, z];

                    formatter.Serialize(stream, biome.Id);
                    formatter.Serialize(stream, height);
                    formatter.Serialize(stream, interpolatedHeight);
                    formatter.Serialize(stream, interpolatedColor.R);
                    formatter.Serialize(stream, interpolatedColor.G);
                    formatter.Serialize(stream, interpolatedColor.B);
                    formatter.Serialize(stream, interpolatedColor.A);
                    _sunlightData[x, z].Save(stream, formatter);
                }
            }

            stream.Close();
        }
Ejemplo n.º 33
0
        private static void compress(byte[] data, BinaryWriterEx bw)
        {
            byte[] compressed;
            using (MemoryStream cmpStream = new MemoryStream())
                using (MemoryStream dcmpStream = new MemoryStream(data))
                {
                    DeflateStream dfltStream = new DeflateStream(cmpStream, CompressionMode.Compress);
                    dcmpStream.CopyTo(dfltStream);
                    dfltStream.Close();
                    compressed = cmpStream.ToArray();
                }

            bw.WriteASCII("DCX\0");
            bw.WriteInt32(0x10000);
            bw.WriteInt32(0x18);
            bw.WriteInt32(0x24);
            bw.WriteInt32(0x24);
            bw.WriteInt32(0x2C);
            bw.WriteASCII("DCS\0");
            bw.WriteInt32(data.Length);
            // Size includes 78DA
            bw.WriteInt32(compressed.Length + 2);
            bw.WriteASCII("DCP\0");
            bw.WriteASCII("DFLT");
            bw.WriteInt32(0x20);
            bw.WriteInt32(0x9000000);
            bw.WriteInt32(0x0);
            bw.WriteInt32(0x0);
            bw.WriteInt32(0x0);
            bw.WriteInt32(0x00010100);
            bw.WriteASCII("DCA\0");
            bw.WriteInt32(0x8);
            bw.WriteByte(0x78);
            bw.WriteByte(0xDA);
            bw.WriteBytes(compressed);
        }
        /// <summary>
        /// Reads a message. Decomress and then applies the base formatter
        /// </summary>
        /// <param name="message">The message to be read</param>
        /// <returns>The result object - goes to the message Body</returns>
        public object Read(Message message)
        {
            long bodyLength = message.BodyStream.Length;

            OriginalBodyLength   = bodyLength;
            CompressedBodyLength = bodyLength;

            if (bodyLength < MessageHeader.Length)
            {
                return(m_BaseFormatter.Read(message)); // Message appeared to be uncompressed
            }

            MessageHeader messageHeader = new MessageHeader(message.BodyStream);

            if (!messageHeader.PrefixIsValid)
            {
                message.BodyStream.Position = 0;
                return(m_BaseFormatter.Read(message)); // Message appeared to be uncompressed
            }

            OriginalBodyLength = messageHeader.UncompressedBodyLength;
            using (MemoryStream decompressedBodyMemoryStream = new MemoryStream())
            {
                DeflateStream decompressor = new DeflateStream(message.BodyStream, CompressionMode.Decompress);
                decompressor.CopyTo(decompressedBodyMemoryStream);
                decompressor.Close();

                // Create a "clear" message and apply the base format to it
                Message clearMessage = new Message();
                clearMessage.BodyType            = message.BodyType;
                clearMessage.BodyStream          = decompressedBodyMemoryStream;
                clearMessage.BodyStream.Position = 0;

                return(m_BaseFormatter.Read(clearMessage));
            }
        }
Ejemplo n.º 35
0
        public void CompressedUrlRoundtripTest()
        {
            var    snippet = Snippets.GetCode("TableServerSidePaginateExample");
            string urlEncodedBase64compressedCode, base64compressedCode, snippet1;

            byte[] bytes;
            // compression
            using (var uncompressed = new MemoryStream(Encoding.UTF8.GetBytes(snippet)))
                using (var compressed = new MemoryStream())
                    using (var compressor = new DeflateStream(compressed, CompressionMode.Compress))
                    {
                        uncompressed.CopyTo(compressor);
                        compressor.Close();
                        bytes = compressed.ToArray();
                        base64compressedCode = Convert.ToBase64String(bytes);
                        //Console.WriteLine(base64compressedCode);
                        urlEncodedBase64compressedCode = Uri.EscapeDataString(base64compressedCode);
                        Console.WriteLine(urlEncodedBase64compressedCode);
                        Console.WriteLine("Length code: " + snippet.Length);
                        Console.WriteLine("Length compressed: " + urlEncodedBase64compressedCode.Length);
                    }
            // uncompress
            base64compressedCode = Uri.UnescapeDataString(urlEncodedBase64compressedCode);
            bytes = Convert.FromBase64String(base64compressedCode);
            using (var uncompressed = new MemoryStream())
                using (var compressedStream = new MemoryStream(bytes))
                    using (var uncompressor = new DeflateStream(compressedStream, CompressionMode.Decompress))
                    {
                        uncompressor.CopyTo(uncompressed);
                        uncompressor.Close();
                        //uncompressed.Position = 0;
                        snippet1 = Encoding.UTF8.GetString(uncompressed.ToArray());
                    }
            // compare
            snippet1.Should().Be(snippet);
        }
Ejemplo n.º 36
0
        /// <exclude />
        public static string UnZipContent(string zippedContent)
        {
            if (zippedContent.IsNullOrEmpty())
            {
                return(zippedContent);
            }

            if (zippedContent.StartsWith(SessionUrlPrefix))
            {
                Guid stateId = Guid.Parse(zippedContent.Substring(SessionUrlPrefix.Length));

                using (new DataConnection())
                {
                    string urlFromSession;
                    bool   succeed = SessionStateManager.DefaultProvider.TryGetState(stateId, out urlFromSession);

                    Verify.That(succeed, "Failed to extract a url part from session");

                    return(urlFromSession);
                }
            }

            string base64 = zippedContent.Replace("_", "+").Replace(".", "/").Replace("-", "=");

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

            using (var ms = new MemoryStream(bytes))
                using (var result = new MemoryStream())
                    using (var deflateStream = new DeflateStream(ms, CompressionMode.Decompress))
                    {
                        deflateStream.CopyTo(result);
                        deflateStream.Close();

                        return(Encoding.UTF8.GetString(result.ToArray()));
                    }
        }
Ejemplo n.º 37
0
 private static byte[] Decompress(byte[] data)
 {
     MemoryStream stream = new MemoryStream(data, 4, data.Length - 4, false);
     DeflateStream stream2 = new DeflateStream(stream, CompressionMode.Decompress);
     byte[] buffer = new byte[(BitConverter.ToInt32(data, 0) - 1) + 1];
     stream2.Read(buffer, 0, buffer.Length);
     stream2.Close();
     return buffer;
 }
Ejemplo n.º 38
0
    public override void FromXML(XmlNode node)
    {
        if (node != null && node.Name == "layer")
        {
            XmlAttributeCollection attrs = node.Attributes;
            m_name = attrs["name"].Value;
            m_layerDimensions.first = Convert.ToInt32(attrs["width"].Value);
            m_layerDimensions.second = Convert.ToInt32(attrs["height"].Value);
            foreach(XmlNode child in node.ChildNodes)
            {
                if (child.Name == "properties")
                {
                    foreach (XmlNode propertyNode in child)
                    {
                        if (propertyNode.Name != "property")
                            continue;
                        XmlAttributeCollection propertyAtts = propertyNode.Attributes;
                        m_properties[propertyAtts["name"].Value] = propertyAtts["value"].Value;
                    }
                }
                else if (child.Name == "data")
                {
                    m_data = new TileData();
                    attrs = child.Attributes;
                    if (attrs["encoding"]!= null)
                    {
                        string[] encodings = { "", "csv", "base64" };
                        string encodingValue = attrs["encoding"].Value;
                        int encodingIdx = Array.IndexOf(encodings, encodingValue);
                        if (encodingIdx >= 0)
                        {
                            m_data.m_encoding = (TileEncodingType)encodingIdx;
                        }

                        string[] compressions = { "", "gzip", "zlib" };
                        string compression = attrs["compression"].Value;
                        int compressionIdx = Array.IndexOf(compressions, compression);
                        if (compressionIdx >= 0)
                        {
                            m_data.m_compression = (TileCompressionType)compressionIdx;
                        }

                        switch(m_data.m_encoding)
                        {
                            case TileEncodingType.kCSV:
                                {
                                    string text = child.InnerText;
                                    string[] values = text.Split(',');
                                    foreach (string v in values)
                                    {
                                        uint value = Convert.ToUInt32(v);
                                        TileInfo info = new TileInfo();
                                        info.m_horizontalFlip = (value & FLIPPED_HORIZONTALLY_FLAG) != 0;
                                        info.m_verticalFlip = (value & FLIPPED_VERTICALLY_FLAG) != 0;
                                        info.m_diagonalFlip = (value & FLIPPED_DIAGONALLY_FLAG) != 0;
                                        value = value & ~(FLIPPED_DIAGONALLY_FLAG | FLIPPED_HORIZONTALLY_FLAG | FLIPPED_VERTICALLY_FLAG);
                                        info.m_gid = value;
                                        m_data.m_tiles.Add(info);
                                    }
                                    break;
                                }
                            case TileEncodingType.kBase64:
                                {
                                    byte[] bytes = null;
                                    switch(m_data.m_compression)
                                    {
                                        case TileCompressionType.kNone:
                                            {
                                                bytes = Convert.FromBase64String(child.InnerText);
                                                break;
                                            }
                                        case TileCompressionType.kGzip:
                                            {
                                                //Transform string into byte[]
                                                string str = child.InnerText;
                                                byte[] byteArray = new byte[str.Length];
                                                int indexBA = 0;
                                                foreach (char item in str.ToCharArray())
                                                {
                                                    byteArray[indexBA++] = (byte)item;
                                                }

                                                MemoryStream ms = new MemoryStream(byteArray);
                                                GZipStream gzip = new GZipStream(ms, CompressionMode.Decompress);

                                                byteArray = new byte[byteArray.Length];
                                                int rBytes = gzip.Read(byteArray, 0, byteArray.Length);

                                                StringBuilder sb = new StringBuilder(rBytes);
                                                for (int i = 0; i < rBytes; ++i)
                                                {
                                                    sb.Append((char)byteArray[i]);
                                                }

                                                gzip.Close();
                                                ms.Close();
                                                gzip.Dispose();
                                                ms.Dispose();

                                                bytes = Convert.FromBase64String(sb.ToString());
                                                break;
                                            }
                                        case TileCompressionType.kZlib:
                                            {
                                                //Transform string into byte[]
                                                string str = child.InnerText;
                                                byte[] byteArray = new byte[str.Length];
                                                int indexBA = 0;
                                                foreach (char item in str.ToCharArray())
                                                {
                                                    byteArray[indexBA++] = (byte)item;
                                                }

                                                MemoryStream ms = new MemoryStream(byteArray);
                                                DeflateStream zlib = new DeflateStream(ms, CompressionMode.Decompress);

                                                byteArray = new byte[byteArray.Length];
                                                int rBytes = zlib.Read(byteArray, 0, byteArray.Length);

                                                StringBuilder sb = new StringBuilder(rBytes);
                                                for (int i = 0; i < rBytes; ++i)
                                                {
                                                    sb.Append((char)byteArray[i]);
                                                }

                                                zlib.Close();
                                                ms.Close();
                                                zlib.Dispose();
                                                ms.Dispose();

                                                bytes = Convert.FromBase64String(sb.ToString());
                                                break;
                                            }
                                    }
                                    for (int i = 0; i < bytes.Length; i += 4)
                                    {
                                        uint value = (uint)bytes[i] | ((uint)bytes[i + 1] << 8) | ((uint)bytes[i + 2] << 16) | ((uint)bytes[i + 3] << 24);
                                        TileInfo info = new TileInfo();
                                        info.m_horizontalFlip = (value & FLIPPED_HORIZONTALLY_FLAG) != 0;
                                        info.m_verticalFlip = (value & FLIPPED_VERTICALLY_FLAG) != 0;
                                        info.m_diagonalFlip = (value & FLIPPED_DIAGONALLY_FLAG) != 0;
                                        value = value & ~(FLIPPED_DIAGONALLY_FLAG | FLIPPED_HORIZONTALLY_FLAG | FLIPPED_VERTICALLY_FLAG);
                                        info.m_gid = value;
                                        m_data.m_tiles.Add(info);
                                    }
                                    break;
                                }
                            default:
                                {
                                    break;
                                }
                        }
                    }
                    else
                    {
                        m_data.m_encoding = TileEncodingType.kNone;
                        m_data.m_compression = TileCompressionType.kNone;

                        m_data.m_tiles.Clear();
                        foreach(XmlNode tileNode in child.ChildNodes)
                        {
                            if (tileNode.Name != "tile")
                            {
                                continue;
                            }
                            TileInfo info = new TileInfo();
                            uint value = Convert.ToUInt32(tileNode.Attributes["gid"].Value);

                            info.m_horizontalFlip = (value & FLIPPED_HORIZONTALLY_FLAG) != 0;
                            info.m_verticalFlip = (value & FLIPPED_VERTICALLY_FLAG) != 0;
                            info.m_diagonalFlip = (value & FLIPPED_DIAGONALLY_FLAG) != 0;
                            value = value & ~(FLIPPED_DIAGONALLY_FLAG | FLIPPED_HORIZONTALLY_FLAG |FLIPPED_VERTICALLY_FLAG);
                            info.m_gid = value;
                            m_data.m_tiles.Add(info);
                        }
                    }
                }
            }
        }
    }
Ejemplo n.º 39
0
	private static void writeMesh(Mesh m) {
		string filepath = folderName + "/" + m.name + ".mesh";
		if (File.Exists(filepath)) {
			File.Delete(filepath);
		}
		MemoryStream ms = new MemoryStream();
		BinaryWriter bw = new BinaryWriter(ms);
		Debug.Log("Write Mesh:" + m.name + " to disk:" + filepath);
		// write length
		bw.Write(m.name.Length);
		// write name
		bw.Write(m.name.ToCharArray());
		// write matrix
		float[] rawData = new float[]{
			1, 0, 0, 0, 
			0, 1, 0, 0, 
			0, 0, 1, 0
		};
		for (int i = 0; i < rawData.Length; i++) {
			bw.Write(rawData[i]);
		}
		// write sub mesh count
		bw.Write(1);
		// write vertex count
		bw.Write(m.vertices.Length);
		Debug.Log("\tVertices:" + m.vertices.Length);
		foreach (Vector3 vert in m.vertices) {
			bw.Write(vert.x);
			bw.Write(vert.y);
			bw.Write(vert.z);
		}
		// write uv0
		bw.Write(m.uv.Length);
		Debug.Log("\tUV0:" + m.uv.Length);
		foreach (Vector2 uv0 in m.uv) {
			bw.Write(uv0.x);
			bw.Write(1 - uv0.y);
		}
		// write uv1
		bw.Write(m.uv2.Length);
		Debug.Log("\tUV1:" + m.uv2.Length);
		foreach (Vector2 uv1 in m.uv2) {
			bw.Write(uv1.x);
			bw.Write(uv1.y);
		}
		Debug.Log("normals:" + m.normals.Length);
		// write normal
		if (normal) {
			bw.Write(m.normals.Length);
			foreach (Vector3 n in m.normals) {
				bw.Write(n.x);
				bw.Write(n.y);
				bw.Write(n.z);
			}
		} else {
			bw.Write(0);
		}
		Debug.Log("tangent:" + m.tangents.Length);
		// write tangent
		if (tangent) {
			bw.Write(m.tangents.Length);
			foreach (Vector3 t in m.tangents) {
				bw.Write(t.x);
				bw.Write(t.y);
				bw.Write(t.z);
			}
		} else {
			bw.Write(0);
		}
		// skeleton weights
		bw.Write(0);
		// skeleton indices
		bw.Write(0);
		// write indices
		bw.Write(m.triangles.Length);
		for (int i = 0; i < m.triangles.Length; i++) {
			bw.Write(m.triangles[i]);
		}
		// bounds
		bw.Write(m.bounds.min.x);
		bw.Write(m.bounds.min.y);
		bw.Write(m.bounds.min.z);
		bw.Write(m.bounds.max.x);
		bw.Write(m.bounds.max.y);
		bw.Write(m.bounds.max.z);
		bw.Close();
		
		int size = ms.GetBuffer().Length;
		MemoryStream compressionBytes = new MemoryStream();
		// write to disk
		DeflateStream compressionStream = new DeflateStream(compressionBytes, CompressionMode.Compress);
		compressionStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
		compressionStream.Close();
		
		FileStream fs = new FileStream(filepath, FileMode.Create);
		BinaryWriter cbw = new BinaryWriter(fs);
		// write compression type
		cbw.Write(3);
		// write original size
		cbw.Write(size);
		// write compressed data
		cbw.Write(compressionBytes.GetBuffer());

		cbw.Close();
		fs.Close();
	}
Ejemplo n.º 40
0
    public const ResponseDataType DefaultDataType = ResponseDataType.PlainText; //PlainText ZipBinary ZipBase64

    #endregion Fields

    #region Methods

    /// <summary>
    /// 将报表XML数据文本输出到HTTP请求
    /// </summary>
    /// <param name="DataPage"></param>
    /// <param name="DataText"></param>
    /// <param name="DataType"></param>
    public static void ResponseData(System.Web.UI.Page DataPage, ref string DataText, ResponseDataType DataType)
    {
        //报表XML数据的前后不能附加任何其它数据,否则XML数据将不能成功解析,所以调用ClearContent方法清理网页中前面多余的数据
            DataPage.Response.ClearContent();

            if (ResponseDataType.PlainText == DataType)
            {
                // 把xml对象发送给客户端
                //DataPage.Response.ContentType = "text/xml";
                DataPage.Response.Write(DataText);
            }
            else
            {
                //将string数据转换为byte[],以便进行压缩
                System.Text.UTF8Encoding converter = new System.Text.UTF8Encoding();
                byte[] XmlBytes = converter.GetBytes(DataText);

                //在 HTTP 头信息中写入报表数据压缩信息
                DataPage.Response.AppendHeader("gr_zip_type", "deflate");                  //指定压缩方法
                DataPage.Response.AppendHeader("gr_zip_size", XmlBytes.Length.ToString()); //指定数据的原始长度
                DataPage.Response.AppendHeader("gr_zip_encode", converter.HeaderName);     //指定数据的编码方式 utf-8 utf-16 ...

                // 把压缩后的xml数据发送给客户端
                if (ResponseDataType.ZipBinary == DataType)
                {
                    System.IO.Compression.DeflateStream compressedzipStream = new DeflateStream(DataPage.Response.OutputStream, CompressionMode.Compress, true);
                    compressedzipStream.Write(XmlBytes, 0, XmlBytes.Length);
                    compressedzipStream.Close();
                }
                else //ResponseDataType.ZipBase64
                {
                    MemoryStream memStream = new MemoryStream();
                    DeflateStream compressedzipStream = new DeflateStream(memStream, CompressionMode.Compress, true);
                    compressedzipStream.Write(XmlBytes, 0, XmlBytes.Length);
                    compressedzipStream.Close(); //这句很重要,这样数据才能全部写入 MemoryStream

                    // Read bytes from the stream.
                    memStream.Seek(0, SeekOrigin.Begin); // Set the position to the beginning of the stream.
                    int count = (int)memStream.Length;
                    byte[] byteArray = new byte[count];
                    count = memStream.Read(byteArray, 0, count);

                    string Base64Text = Convert.ToBase64String(byteArray);
                    DataPage.Response.Write(Base64Text);
                }
            }

            //报表XML数据的前后不能附加任何其它数据,否则XML数据将不能成功解析,所以调用End方法放弃网页中后面不必要的数据
            DataPage.Response.End();
    }
    public static void DeflateCompressDecompress(string filename)
    {
        Console.WriteLine("Test compression and decompression on file {0}", filename);
        FileStream infile;
        try
        {
            // Open the file as a FileStream object.
            infile = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
            byte[] buffer = new byte[infile.Length];

            // Read the file to ensure it is readable.
            int count = infile.Read(buffer, 0, buffer.Length);
            if (count != buffer.Length)
            {
                infile.Close();
                Console.WriteLine("Test Failed: Unable to read data from file");
                return;
            }
            infile.Close();

            MemoryStream ms = new MemoryStream();
            // Use the newly created memory stream for the compressed data.
            DeflateStream compressedzipStream = new DeflateStream(ms, CompressionMode.Compress, true);
            Console.WriteLine("Compression");
            compressedzipStream.Write(buffer, 0, buffer.Length);
            // Close the stream.
            compressedzipStream.Close();
            Console.WriteLine("Original size: {0}, Compressed size: {1}", buffer.Length, ms.Length);

            // Reset the memory stream position to begin decompression.
            ms.Position = 0;
            DeflateStream zipStream = new DeflateStream(ms, CompressionMode.Decompress);
            Console.WriteLine("Decompression");
            byte[] decompressedBuffer = new byte[buffer.Length + 100];
            // Use the ReadAllBytesFromStream to read the stream.
            int totalCount = DeflateTest.ReadAllBytesFromStream(zipStream, decompressedBuffer);
            Console.WriteLine("Decompressed {0} bytes", totalCount);

            if (!DeflateTest.CompareData(buffer, buffer.Length, decompressedBuffer, totalCount))
            {
                Console.WriteLine("Error. The two buffers did not compare.");
            }
            zipStream.Close();
        } // end try
        catch (InvalidDataException)
        {
            Console.WriteLine("Error: The file being read contains invalid data.");
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("Error:The file specified was not found.");
        }
        catch (ArgumentException)
        {
            Console.WriteLine("Error: path is a zero-length string, contains only white space, or contains one or more invalid characters");
        }
        catch (PathTooLongException)
        {
            Console.WriteLine("Error: The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.");
        }
        catch (DirectoryNotFoundException)
        {
            Console.WriteLine("Error: The specified path is invalid, such as being on an unmapped drive.");
        }
        catch (IOException)
        {
            Console.WriteLine("Error: An I/O error occurred while opening the file.");
        }
        catch (UnauthorizedAccessException)
        {
            Console.WriteLine("Error: path specified a file that is read-only, the path is a directory, or caller does not have the required permissions.");
        }
        catch (IndexOutOfRangeException)
        {
            Console.WriteLine("Error: You must provide parameters for MyGZIP.");
        }
    }
Ejemplo n.º 42
0
        public void Zlib_DisposedException_DeflateStream()
        {
            string TextToCompress = LetMeDoItNow;

                MemoryStream ms1= new MemoryStream();

                Stream compressor= new DeflateStream(ms1, CompressionMode.Compress, false);

                TestContext.WriteLine("Text to compress is {0} bytes: '{1}'",
                                      TextToCompress.Length, TextToCompress);
                TestContext.WriteLine("using compressor: {0}", compressor.GetType().FullName);

                StreamWriter sw = new StreamWriter(compressor, System.Text.Encoding.ASCII);
                sw.Write(TextToCompress);
                sw.Close(); // implicitly closes compressor
                sw.Close(); // implicitly closes compressor, again

                compressor.Close(); // explicitly closes compressor
                var a = ms1.ToArray();
                TestContext.WriteLine("Compressed stream is {0} bytes long", a.Length);

                var ms2 = new MemoryStream(a);
                Stream decompressor  = new DeflateStream(ms2, CompressionMode.Decompress, false);

                TestContext.WriteLine("using decompressor: {0}", decompressor.GetType().FullName);

                var sr = new StreamReader(decompressor, System.Text.Encoding.ASCII);
                string DecompressedText = sr.ReadToEnd();
                sr.Close();

                TestContext.WriteLine("decompressor.CanRead = {0}",decompressor.CanRead);

                TestContext.WriteLine("Read {0} characters: '{1}'", DecompressedText.Length, DecompressedText);
                TestContext.WriteLine("\n");
                Assert.AreEqual<String>(TextToCompress, DecompressedText);

        }
Ejemplo n.º 43
0
        /// <summary>
        /// Decompress and display the update contents
        /// </summary>
        /// <param name="data">data bytes</param>
        private void DecompressDisplay(byte[] data)
        {
            var compressedStream = new MemoryStream(data);
            Int32 x, y, w, h;

            using (MemoryStream clearStream = new MemoryStream()) {
                using (DeflateStream zipStream = new DeflateStream(compressedStream, CompressionMode.Decompress)) {
                    byte[] buffer = new byte[4096];
                    byte[] szBuf = new byte[4];
                    int readAmt;

                    readAmt = zipStream.Read(szBuf, 0, 4);
                    Debug.Assert(readAmt == 4);
                    UInt32 hdr = System.BitConverter.ToUInt32(szBuf, 0);
                    hdr = (UInt32)System.Net.IPAddress.NetworkToHostOrder((Int32)hdr);
                    width = (Int32)(hdr >> 16);
                    height = (Int32)(hdr & 0xFFFF);

                    readAmt = zipStream.Read(szBuf, 0, 4);
                    Debug.Assert(readAmt == 4);
                    hdr = System.BitConverter.ToUInt32(szBuf, 0);
                    hdr = (UInt32)System.Net.IPAddress.NetworkToHostOrder((Int32)hdr);
                    maskX = (Int32)(hdr >> 16);
                    maskY = (Int32)(hdr & 0xFFFF);

                    readAmt = zipStream.Read(szBuf, 0, 4);
                    Debug.Assert(readAmt == 4);
                    hdr = System.BitConverter.ToUInt32(szBuf, 0);
                    hdr = (UInt32)System.Net.IPAddress.NetworkToHostOrder((Int32)hdr);
                    maskWidth = (Int32)(hdr >> 16);
                    maskHeight = (Int32)(hdr & 0xFFFF);

                    if (!((prevMX == maskX) && (prevMY == maskY) && (prevMW == maskWidth) && (prevMH == maskHeight))) {
                        DisplayMask(maskX, maskY, maskWidth, maskHeight, width, height);

                        prevMX = maskX;
                        prevMY = maskY;
                        prevMW = maskWidth;
                        prevMH = maskHeight;
                    }

                    readAmt = zipStream.Read(szBuf, 0, 4);
                    Debug.Assert(readAmt == 4);
                    hdr = System.BitConverter.ToUInt32(szBuf, 0);
                    hdr = (UInt32)System.Net.IPAddress.NetworkToHostOrder((Int32)hdr);
                    x = (Int32)(hdr >> 16);
                    y = (Int32)(hdr & 0xFFFF);

                    readAmt = zipStream.Read(szBuf, 0, 4);
                    Debug.Assert(readAmt == 4);
                    hdr = System.BitConverter.ToUInt32(szBuf, 0);
                    hdr = (UInt32)System.Net.IPAddress.NetworkToHostOrder((Int32)hdr);
                    w = (Int32)(hdr >> 16);
                    h = (Int32)(hdr & 0xFFFF);

                    int read = 0;
                    while (true) {
                        try {
                            read = zipStream.Read(buffer, 0, buffer.Length);
                        } catch (Exception e) {
                            // Trace.WriteLine("{0} Error code: {}.", e.Message, e.ErrorCode);
                            MessageBox.Show("Message: " + e.Message, "FATAL");
                        }
                        if (read > 0)
                            clearStream.Write(buffer, 0, read);
                        else
                            break;
                    }
                    zipStream.Close();
                }

                DisplayUpdate(x, y, w, h, clearStream.ToArray());
            }
        }
Ejemplo n.º 44
0
        void ReadPacket( byte opcode )
        {
            reader.Remove( 1 ); // remove opcode
            lastOpcode = (PacketId)opcode;

            switch( (PacketId)opcode ) {
                case PacketId.Handshake:
                    {
                        byte protocolVer = reader.ReadUInt8();
                        ServerName = reader.ReadAsciiString();
                        ServerMotd = reader.ReadAsciiString();
                        game.LocalPlayer.SetUserType( reader.ReadUInt8() );
                        receivedFirstPosition = false;
                        game.LocalPlayer.ParseHackFlags( ServerName, ServerMotd );
                    } break;

                case PacketId.Ping:
                    break;

                case PacketId.LevelInitialise:
                    {
                        game.Map.Reset();
                        game.SetNewScreen( new LoadingMapScreen( game, ServerName, ServerMotd ) );
                        if( ServerMotd.Contains( "cfg=" ) ) {
                            ReadWomConfigurationAsync();
                        }
                        receivedFirstPosition = false;
                        gzipHeader = new GZipHeaderReader();
                        // Workaround because built in mono stream assumes that the end of stream
                        // has been reached the first time a read call returns 0. (MS.NET doesn't)
                        #if __MonoCS__
                        gzipStream = new DeflateStream( gzippedMap, true );
                        #else
                        gzipStream = new DeflateStream( gzippedMap, CompressionMode.Decompress );
                        if( OpenTK.Configuration.RunningOnMono ) {
                            Utils.LogWarning( "You are running on Mono, but this build does not support the Mono workaround." );
                            Utils.LogWarning( "You should either download the Mono compatible build or define '__MonoCS__' when targeting Mono. " +
                                             "(The Mono compiler already defines this by default)" );
                            Utils.LogWarning( "You will likely experience an 'Internal error (no progress possible) ReadInternal' exception when decompressing the map." );
                        }
                        #endif
                        mapSizeIndex = 0;
                        mapIndex = 0;
                        receiveStart = DateTime.UtcNow;
                    } break;

                case PacketId.LevelDataChunk:
                    {
                        int usedLength = reader.ReadInt16();
                        gzippedMap.Position = 0;
                        gzippedMap.SetLength( usedLength );

                        if( gzipHeader.done || gzipHeader.ReadHeader( gzippedMap ) ) {
                            if( mapSizeIndex < 4 ) {
                                mapSizeIndex += gzipStream.Read( mapSize, mapSizeIndex, 4 - mapSizeIndex );
                            }

                            if( mapSizeIndex == 4 ) {
                                if( map == null ) {
                                    int size = mapSize[0] << 24 | mapSize[1] << 16 | mapSize[2] << 8 | mapSize[3];
                                    map = new byte[size];
                                }
                                mapIndex += gzipStream.Read( map, mapIndex, map.Length - mapIndex );
                            }
                        }
                        reader.Remove( 1024 );
                        byte progress = reader.ReadUInt8();
                        game.Events.RaiseMapLoading( progress );
                    } break;

                case PacketId.LevelFinalise:
                    {
                        game.SetNewScreen( new NormalScreen( game ) );
                        int mapWidth = reader.ReadInt16();
                        int mapHeight = reader.ReadInt16();
                        int mapLength = reader.ReadInt16();

                        double loadingMs = ( DateTime.UtcNow - receiveStart ).TotalMilliseconds;
                        Utils.LogDebug( "map loading took:" + loadingMs );
                        game.Map.UseRawMap( map, mapWidth, mapHeight, mapLength );
                        game.Events.RaiseOnNewMapLoaded();
                        map = null;
                        gzipStream.Close();
                        if( sendWomId && !sentWomId ) {
                            SendChat( "/womid WoMClient-2.0.7" );
                            sentWomId = true;
                        }
                        gzipStream = null;
                        GC.Collect( 0 );
                    } break;

                case PacketId.SetBlock:
                    {
                        int x = reader.ReadInt16();
                        int y = reader.ReadInt16();
                        int z = reader.ReadInt16();
                        byte type = reader.ReadUInt8();
                        if( !game.Map.IsNotLoaded )
                            game.UpdateBlock( x, y, z, type );
                        else
                            Utils.LogWarning( "Server tried to update a block while still sending us the map!" );
                    } break;

                case PacketId.AddEntity:
                    {
                        byte entityId = reader.ReadUInt8();
                        string name = reader.ReadAsciiString();
                        AddEntity( entityId, name, name, true );
                    }  break;

                case PacketId.EntityTeleport:
                    {
                        byte entityId = reader.ReadUInt8();
                        ReadAbsoluteLocation( entityId, true );
                    } break;

                case PacketId.RelPosAndOrientationUpdate:
                    ReadRelativeLocation();
                    break;

                case PacketId.RelPosUpdate:
                    ReadRelativePosition();
                    break;

                case PacketId.OrientationUpdate:
                    ReadOrientation();
                    break;

                case PacketId.RemoveEntity:
                    {
                        byte entityId = reader.ReadUInt8();
                        Player player = game.Players[entityId];
                        if( entityId != 0xFF && player != null ) {
                            game.Events.RaiseEntityRemoved( entityId );
                            player.Despawn();
                            game.Players[entityId] = null;
                        }
                    } break;

                case PacketId.Message:
                    {
                        byte messageType = reader.ReadUInt8();
                        string text = reader.ReadChatString( ref messageType, useMessageTypes );
                        game.Chat.Add( text, (CpeMessage)messageType );
                    } break;

                case PacketId.Kick:
                    {
                        string reason = reader.ReadAsciiString();
                        game.Disconnect( "&eLost connection to the server", reason );
                        Dispose();
                    } break;

                case PacketId.SetPermission:
                    {
                        game.LocalPlayer.SetUserType( reader.ReadUInt8() );
                    } break;

                case PacketId.CpeExtInfo:
                    {
                        string appName = reader.ReadAsciiString();
                        Utils.LogDebug( "Server identified itself as: " + appName );
                        cpeServerExtensionsCount = reader.ReadInt16();
                    } break;

                case PacketId.CpeExtEntry:
                    {
                        string extName = reader.ReadAsciiString();
                        int extVersion = reader.ReadInt32();
                        Utils.LogDebug( "cpe ext: " + extName + " , " + extVersion );
                        if( extName == "HeldBlock" ) {
                            sendHeldBlock = true;
                        } else if( extName == "MessageTypes" ) {
                            useMessageTypes = true;
                        } else if( extName == "ExtPlayerList" ) {
                            UsingExtPlayerList = true;
                        } else if( extName == "PlayerClick" ) {
                            UsingPlayerClick = true;
                        } else if( extName == "EnvMapAppearance" && extVersion == 2 ) {
                            usingTexturePack = true;
                        }
                        cpeServerExtensionsCount--;

                        if( cpeServerExtensionsCount == 0 ) {
                            MakeExtInfo( Utils.AppName, clientExtensions.Length );
                            SendPacket();
                            for( int i = 0; i < clientExtensions.Length; i++ ) {
                                string name = clientExtensions[i];
                                int version = (name == "ExtPlayerList" || name == "EnvMapApperance") ? 2 : 1;
                                MakeExtEntry( name, version );
                                SendPacket();
                            }
                        }
                    } break;

                case PacketId.CpeSetClickDistance:
                    {
                        game.LocalPlayer.ReachDistance = reader.ReadInt16() / 32f;
                    } break;

                case PacketId.CpeCustomBlockSupportLevel:
                    {
                        byte supportLevel = reader.ReadUInt8();
                        MakeCustomBlockSupportLevel( 1 );
                        SendPacket();

                        if( supportLevel == 1 ) {
                            for( int i = (int)Block.CobblestoneSlab; i <= (int)Block.StoneBrick; i++ ) {
                                game.Inventory.CanPlace[i] = true;
                                game.Inventory.CanDelete[i] = true;
                            }
                            game.Events.RaiseBlockPermissionsChanged();
                        } else {
                            Utils.LogWarning( "Server's block support level is {0}, this client only supports level 1.", supportLevel );
                            Utils.LogWarning( "You won't be able to see or use blocks from levels above level 1" );
                        }
                    } break;

                case PacketId.CpeHoldThis:
                    {
                        byte blockType = reader.ReadUInt8();
                        bool canChange = reader.ReadUInt8() == 0;
                        game.Inventory.CanChangeHeldBlock = true;
                        game.Inventory.HeldBlock = (Block)blockType;
                        game.Inventory.CanChangeHeldBlock = canChange;
                    } break;

                case PacketId.CpeExtAddPlayerName:
                    {
                        short nameId = reader.ReadInt16();
                        string playerName = Utils.StripColours( reader.ReadAsciiString() );
                        string listName = reader.ReadAsciiString();
                        string groupName = reader.ReadAsciiString();
                        byte groupRank = reader.ReadUInt8();
                        if( nameId >= 0 && nameId <= 255 ) {
                            CpeListInfo oldInfo = game.CpePlayersList[nameId];
                            CpeListInfo info = new CpeListInfo( (byte)nameId, playerName, listName, groupName, groupRank );
                            game.CpePlayersList[nameId] = info;

                            if( oldInfo != null ) {
                                game.Events.RaiseCpeListInfoChanged( (byte)nameId );
                            } else {
                                game.Events.RaiseCpeListInfoAdded( (byte)nameId );
                            }
                        }
                    } break;

                case PacketId.CpeExtAddEntity:
                    {
                        byte entityId = reader.ReadUInt8();
                        string displayName = reader.ReadAsciiString();
                        string skinName = reader.ReadAsciiString();
                        AddEntity( entityId, displayName, skinName, false );
                    } break;

                case PacketId.CpeExtRemovePlayerName:
                    {
                        short nameId = reader.ReadInt16();
                        if( nameId >= 0 && nameId <= 255 ) {
                            game.Events.RaiseCpeListInfoRemoved( (byte)nameId );
                            game.CpePlayersList[nameId] = null;
                        }
                    } break;

                case PacketId.CpeMakeSelection:
                    {
                        byte selectionId = reader.ReadUInt8();
                        string label = reader.ReadAsciiString();
                        short startX = reader.ReadInt16();
                        short startY = reader.ReadInt16();
                        short startZ = reader.ReadInt16();
                        short endX = reader.ReadInt16();
                        short endY = reader.ReadInt16();
                        short endZ = reader.ReadInt16();

                        byte r = (byte)reader.ReadInt16();
                        byte g = (byte)reader.ReadInt16();
                        byte b = (byte)reader.ReadInt16();
                        byte a = (byte)reader.ReadInt16();

                        Vector3I p1 = Vector3I.Min( startX, startY, startZ, endX, endY, endZ );
                        Vector3I p2 = Vector3I.Max( startX, startY, startZ, endX, endY, endZ );
                        FastColour col = new FastColour( r, g, b, a );
                        game.SelectionManager.AddSelection( selectionId, p1, p2, col );
                    } break;

                case PacketId.CpeRemoveSelection:
                    {
                        byte selectionId = reader.ReadUInt8();
                        game.SelectionManager.RemoveSelection( selectionId );
                    } break;

                case PacketId.CpeEnvColours:
                    {
                        byte variable = reader.ReadUInt8();
                        short red = reader.ReadInt16();
                        short green = reader.ReadInt16();
                        short blue = reader.ReadInt16();
                        bool invalid = red < 0 || red > 255 || green < 0 || green > 255 || blue < 0 || blue > 255;
                        FastColour col = new FastColour( red, green, blue );

                        if( variable == 0 ) { // sky colour
                            game.Map.SetSkyColour( invalid ? Map.DefaultSkyColour : col );
                        } else if( variable == 1 ) { // clouds colour
                            game.Map.SetCloudsColour( invalid ? Map.DefaultCloudsColour : col );
                        } else if( variable == 2 ) { // fog colour
                            game.Map.SetFogColour( invalid ? Map.DefaultFogColour : col );
                        } else if( variable == 3 ) { // ambient light (shadow light)
                            game.Map.SetShadowlight( invalid ? Map.DefaultShadowlight : col );
                        } else if( variable == 4 ) { // diffuse light (sun light)
                            game.Map.SetSunlight( invalid ? Map.DefaultSunlight : col );
                        }
                    } break;

                case PacketId.CpeSetBlockPermission:
                    {
                        byte blockId = reader.ReadUInt8();
                        bool canPlace = reader.ReadUInt8() != 0;
                        bool canDelete = reader.ReadUInt8() != 0;
                        Inventory inv = game.Inventory;

                        if( blockId == 0 ) {
                            for( int i = 1; i < BlockInfo.CpeBlocksCount; i++ ) {
                                inv.CanPlace.SetNotOverridable( canPlace, i );
                                inv.CanDelete.SetNotOverridable( canDelete, i );
                            }
                        } else {
                            inv.CanPlace.SetNotOverridable( canPlace, blockId );
                            inv.CanDelete.SetNotOverridable( canDelete, blockId );
                        }
                        game.Events.RaiseBlockPermissionsChanged();
                    } break;

                case PacketId.CpeChangeModel:
                    {
                        byte playerId = reader.ReadUInt8();
                        string modelName = reader.ReadAsciiString().ToLowerInvariant();
                        Player player = game.Players[playerId];
                        if( player != null ) {
                            player.SetModel( modelName );
                        }
                    } break;

                case PacketId.CpeEnvSetMapApperance:
                    {
                        string url = reader.ReadAsciiString();
                        byte sideBlock = reader.ReadUInt8();
                        byte edgeBlock = reader.ReadUInt8();
                        short waterLevel = reader.ReadInt16();
                        game.Map.SetWaterLevel( waterLevel );
                        game.Map.SetEdgeBlock( (Block)edgeBlock );
                        game.Map.SetSidesBlock( (Block)sideBlock );
                        if( url == String.Empty ) {
                            TexturePackExtractor extractor = new TexturePackExtractor();
                            extractor.Extract( game.defaultTexPack, game );
                        } else {
                            game.Animations.Dispose();
                            if( usingTexturePack )
                                game.AsyncDownloader.DownloadData( url, true, "texturePack" );
                            else
                                game.AsyncDownloader.DownloadImage( url, true, "terrain" );

                        }
                        Utils.LogDebug( "Image url: " + url );
                    } break;

                case PacketId.CpeEnvWeatherType:
                    game.Map.SetWeather( (Weather)reader.ReadUInt8() );
                    break;

                case PacketId.CpeHackControl:
                    {
                        game.LocalPlayer.CanFly = reader.ReadUInt8() != 0;
                        game.LocalPlayer.CanNoclip = reader.ReadUInt8() != 0;
                        game.LocalPlayer.CanSpeed = reader.ReadUInt8() != 0;
                        game.LocalPlayer.CanRespawn = reader.ReadUInt8() != 0;
                        game.CanUseThirdPersonCamera = reader.ReadUInt8() != 0;
                        if( !game.CanUseThirdPersonCamera ) {
                            game.SetCamera( false );
                        }
                        float jumpHeight = reader.ReadInt16() / 32f;
                        if( jumpHeight < 0 ) jumpHeight = 1.4f;
                        game.LocalPlayer.CalculateJumpVelocity( jumpHeight );
                    } break;

                case PacketId.CpeExtAddEntity2:
                    {
                        byte entityId = reader.ReadUInt8();
                        string displayName = reader.ReadAsciiString();
                        string skinName = reader.ReadAsciiString();
                        AddEntity( entityId, displayName, skinName, true );
                    } break;

                case PacketId.CpeDefineBlock:
                case PacketId.CpeDefineLiquid:
                    {
                        byte block = reader.ReadUInt8();
                        BlockInfo info = game.BlockInfo;
                        info.ResetBlockInfo( block );

                        info.Name[block] = reader.ReadAsciiString();
                        info.CollideType[block] = (BlockCollideType)reader.ReadUInt8();
                        // TODO: Liquid collide type not properly supported.
                        info.SpeedMultiplier[block] = (float)Math.Pow( 2, (reader.ReadUInt8() - 128) / 64f );
                        info.SetTop( reader.ReadUInt8(), (Block)block );
                        info.SetSide( reader.ReadUInt8(), (Block)block );
                        info.SetBottom( reader.ReadUInt8(), (Block)block );
                        reader.ReadUInt8(); // opacity hint, but we ignore this.
                        info.BlocksLight[block] = reader.ReadUInt8() == 0;
                        reader.ReadUInt8(); // walk sound, but we ignore this.
                        info.EmitsLight[block] = reader.ReadUInt8() != 0;

                        if( opcode == (byte)PacketId.CpeDefineBlock ) {
                            byte shape = reader.ReadUInt8();
                            if( shape == 1 ) info.Height[block] = 1;
                            else if( shape == 2 ) info.Height[block] = 0.5f;
                            // TODO: upside down slab not properly supported
                            else if( shape == 3 ) info.Height[block] = 0.5f;
                            else if( shape == 4 ) info.IsSprite[block] = true;

                            byte blockDraw = reader.ReadUInt8();
                            if( blockDraw == 0 ) info.IsOpaque[block] = true;
                            else if( blockDraw == 1 ) info.IsTransparent[block] = true;
                            else if( blockDraw == 2 ) info.IsTranslucent[block] = true;
                            else if( blockDraw == 3 ) info.IsTranslucent[block] = true;

                            Console.WriteLine( block + " : " + shape + "," + blockDraw );
                        } else {
                            byte fogDensity = reader.ReadUInt8();
                            info.FogDensity[block] = fogDensity == 0 ? 0 : (fogDensity + 1) / 128f;
                            info.FogColour[block] = new FastColour(
                                reader.ReadUInt8(), reader.ReadUInt8(), reader.ReadUInt8() );
                        }
                        info.SetupCullingCache();
                    } break;

                case PacketId.CpeRemoveBlockDefinition:
                    game.BlockInfo.ResetBlockInfo( reader.ReadUInt8() );
                    break;

                default:
                    throw new NotImplementedException( "Unsupported packet:" + (PacketId)opcode );
            }
        }