Ejemplo n.º 1
0
        static Patch processChunk(byte[] orig, byte[] mod, int chunkStart, int chunkEnd)
        {
            int patchSize = chunkEnd - chunkStart;

            Debug.Assert(patchSize < Patch.MaxPatchSize);
            int matchAreaSize = Patch.MatchAreaSize(patchSize);
            int matchBefore   = (matchAreaSize - patchSize) / 2;
            int matchAfter    = matchAreaSize - (patchSize + matchBefore);

            Debug.Assert(matchBefore <= chunkStart);
            Debug.Assert(chunkEnd + matchAfter <= orig.Length);

            byte[] origBytes  = new byte[matchAreaSize];
            byte[] patchBytes = new byte[patchSize];
            Array.ConstrainedCopy(orig, chunkStart - matchBefore, origBytes, 0, matchAreaSize);
            Array.ConstrainedCopy(mod, chunkStart, patchBytes, 0, patchSize);
            MemoryStream  ms   = new MemoryStream();
            DeflateStream comp = new DeflateStream(ms, CompressionMode.Compress);

            comp.WriteByte(0);
            comp.Flush();
            long base_len = ms.Length;

            comp.Write(origBytes, 0, origBytes.Length);
            comp.Flush();
            return(new Patch(origBytes, patchBytes, matchBefore, Convert.ToInt32(ms.Length - base_len)));
        }
Ejemplo n.º 2
0
        public void DoubleFlush()
        {
            var ms = new MemoryStream();
            var ds = new DeflateStream(ms, CompressionMode.Compress);

            ds.Flush();
            ds.Flush();
        }
Ejemplo n.º 3
0
        [Category("StaticLinkedAotNotWorking")]          // Native MPH loading issues
        public void Bug28777_DoubleFlush()
        {
            byte[]        buffer      = new byte [4096];
            MemoryStream  backing     = new MemoryStream();
            DeflateStream compressing = new DeflateStream(backing, CompressionLevel.Fastest, true);

            compressing.Write(buffer, 0, buffer.Length);
            compressing.Flush();
            compressing.Flush();
            compressing.Close();
            backing.Close();
        }
Ejemplo n.º 4
0
		// 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.º 5
0
        public void Save(Stream stream, bool compress)
        {
            char[] header = new char[2] {
                'X', '1'
            };
            using (var outStream = new MemoryStream()) {
                outStream.WriteByte((byte)header[0]);
                outStream.WriteByte((byte)header[1]);

                var serializer = new SerialWriter(new BinaryWriter(outStream));
                Serialize(document.Root, serializer);
                outStream.Position = 0;
                string data = new StreamReader(outStream).ReadToEnd();
                outStream.Position = 0;

                if (compress)
                {
                    var writer = new BinaryWriter(stream);
                    writer.Write(Encoding.UTF8.GetBytes("l33t"));
                    writer.Write((int)outStream.Length);
                    writer.Write((byte)0x78);
                    writer.Write((byte)0x9C);
                    using (var decompStream = new DeflateStream(stream, CompressionMode.Compress, true)) {
                        outStream.CopyTo(decompStream);
                        decompStream.Flush();
                    }
                }
                else
                {
                    outStream.CopyTo(stream);
                }
            }
        }
Ejemplo n.º 6
0
 public void Dispose()
 {
     ZipStream.Flush();
     ZipStream.Close();
     ZipStream.Dispose();
     FileStream.Dispose();
 }
Ejemplo n.º 7
0
 public override void Flush()
 {
     if (deflateStream != null)
     {
         deflateStream.Flush();
     }
 }
        /// <summary>
        /// Send data to the web socket
        /// </summary>
        /// <param name="buffer">the buffer containing data to send</param>
        /// <param name="messageType">The message type. Can be Text or Binary</param>
        /// <param name="endOfMessage">True if this message is a standalone message (this is the norm)
        /// If it is a multi-part message then false (and true for the last message)</param>
        /// <param name="cancellationToken">the cancellation token</param>
        public override async Task SendAsync(ArraySegment <byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken)
        {
            using (MemoryStream stream = _recycledStreamFactory())
            {
                WebSocketOpCode opCode = GetOppCode(messageType);

                if (_usePerMessageDeflate)
                {
                    // NOTE: Compression is currently work in progress and should NOT be used in this library.
                    // The code below is very inefficient for small messages. Ideally we would like to have some sort of moving window
                    // of data to get the best compression. And we don't want to create new buffers which is bad for GC.
                    using (MemoryStream temp = new MemoryStream())
                    {
                        DeflateStream deflateStream = new DeflateStream(temp, CompressionMode.Compress);
                        deflateStream.Write(buffer.Array, buffer.Offset, buffer.Count);
                        deflateStream.Flush();
                        ArraySegment <byte> compressedBuffer = new ArraySegment <byte>(temp.ToArray());
                        WebSocketFrameWriter.Write(opCode, compressedBuffer, stream, endOfMessage, _isClient);
                        Events.Log.SendingFrame(_guid, opCode, endOfMessage, compressedBuffer.Count, true);
                    }
                }
                else
                {
                    WebSocketFrameWriter.Write(opCode, buffer, stream, endOfMessage, _isClient);
                    Events.Log.SendingFrame(_guid, opCode, endOfMessage, buffer.Count, false);
                }

                await WriteStreamToNetwork(stream, cancellationToken);

                // TODO: is this correct??
                _isContinuationFrame = !endOfMessage;
            }
        }
        /// <summary>
        /// Send data to the web socket
        /// </summary>
        /// <param name="buffer">the buffer containing data to send</param>
        /// <param name="messageType">The message type. Can be Text or Binary</param>
        /// <param name="endOfMessage">True if this message is a standalone message (this is the norm)
        /// If it is a multi-part message then false (and true for the last message)</param>
        /// <param name="cancellationToken">the cancellation token</param>
        public override async Task SendAsync(ArraySegment <byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken)
        {
            using (MemoryStream stream = _recycledStreamFactory())
            {
                WebSocketOpCode opCode = GetOppCode(messageType);

                if (_usePerMessageDeflate)
                {
                    using (MemoryStream temp = new MemoryStream())
                    {
                        DeflateStream deflateStream = new DeflateStream(temp, CompressionMode.Compress);
                        deflateStream.Write(buffer.Array, buffer.Offset, buffer.Count);
                        deflateStream.Flush();
                        var compressedBuffer = new ArraySegment <byte>(temp.ToArray());
                        WebSocketFrameWriter.Write(opCode, compressedBuffer, stream, endOfMessage, _isClient);
                        Events.Log.SendingFrame(_guid, opCode, endOfMessage, compressedBuffer.Count, true);
                    }
                }
                else
                {
                    WebSocketFrameWriter.Write(opCode, buffer, stream, endOfMessage, _isClient);
                    Events.Log.SendingFrame(_guid, opCode, endOfMessage, buffer.Count, false);
                }

                await WriteStreamToNetwork(stream, cancellationToken);

                _isContinuationFrame = !endOfMessage;
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Serializes an object as a base 64 encoded string.
        /// </summary>
        /// <typeparam name="T">Type of object to serialize.</typeparam>
        /// <param name="obj">The object to serialize.</param>
        /// <returns>The object serialized as a base 64 encoded string.</returns>
        public static string Serialize <T>(this T obj) where T : class
        {
            if (obj == null)
            {
                return(null);
            }

            using (var stream = new MemoryStream())
            {
                using (var compressionStream = new DeflateStream(stream, CompressionMode.Compress, true))
                {
                    var formatter         = new BinaryFormatter();
                    var surrogateSelector = new SurrogateSelector();

                    // Add the serialization surrogate to allow SelectListItem to be serialized
                    surrogateSelector.AddSurrogate(typeof(SelectListItem), new StreamingContext(StreamingContextStates.All), new SelectListItemSerializationSurrogate());
                    formatter.SurrogateSelector = surrogateSelector;

                    // Serialize object to stream
                    formatter.Serialize(compressionStream, obj);

                    compressionStream.Flush();
                }

                stream.Position = 0;

                return(Convert.ToBase64String(stream.ToArray()));
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// 解压缩二进制格式数据,得到数据集
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static DataSet DecompressionDataSet1(byte[] bytes)
        {
            // 初始化流,设置读取位置
            MemoryStream mStream = new MemoryStream(bytes);

            mStream.Seek(0, SeekOrigin.Begin);
            // 解压缩流得到byte[]格式数据
            DeflateStream unZipStream = new DeflateStream(mStream, CompressionMode.Decompress, true);

            byte[] unzipBytes = StreamOperator.ReadWholeStream(unZipStream);
            unZipStream.Flush();
            unZipStream.Close();
            // 将数据装入内存
            MemoryStream resultStream = new MemoryStream(unzipBytes);

            resultStream.Seek(0, SeekOrigin.Begin);
            // 反序列化
            DataSet resultDataSet = new DataSet();

            resultDataSet.RemotingFormat = SerializationFormat.Binary;
            BinaryFormatter bFormatter = new BinaryFormatter();

            resultDataSet = (DataSet)bFormatter.Deserialize(resultStream, null);
            //
            return(resultDataSet);
        }
Ejemplo n.º 12
0
 // Binary serialization
 public byte[] Serialize()
 {
     using (MemoryStream stream = new MemoryStream())
     {
         using (DeflateStream ds = new DeflateStream(stream, CompressionMode.Compress, true))
         {
             BinaryFormatter formatter = new BinaryFormatter();
             formatter.Serialize(ds, this);
             ds.Flush();
         }
         byte[] bytes  = stream.GetBuffer();
         byte[] bytes2 = new byte[stream.Length];
         Buffer.BlockCopy(bytes, 0, bytes2, 0, (int)stream.Length);
         //                Array.Copy(bytes, bytes2, stream.Length);
         if (this.MustEncrypt)
         {
             bytes2 = RijndaelEncrptor.Instance.Encrypt(bytes2);
         }
         // Create a buffer large enough to hold the encrypted message and size bytes
         byte[] data = new byte[8 + bytes2.Length];
         // Add the message size
         BitConverter.GetBytes(bytes2.Length).CopyTo(data, 0);
         BitConverter.GetBytes(this.MustEncrypt).CopyTo(data, 4);
         // Add the message data
         bytes2.CopyTo(data, 8);
         return(data);
     }
 }
Ejemplo n.º 13
0
        public DataSet DecompressDataSet(byte[] bytDs)
        {
            DataSet      outDs = new DataSet();
            MemoryStream inMs  = new MemoryStream(bytDs);

            inMs.Seek(0, 0); //스트림으로 가져오기

            //1. 압축객체 생성- 압축 풀기
            DeflateStream zipStream = new DeflateStream(inMs,
                                                        CompressionMode.Decompress, true);

            byte[] outByt = ReadFullStream(zipStream);
            zipStream.Flush();
            zipStream.Close();
            MemoryStream outMs = new MemoryStream(outByt);

            outMs.Seek(0, 0); //2. 스트림으로 다시변환
            outDs.RemotingFormat = SerializationFormat.Binary;

            //3. 데이터셋으로 Deserialize
            BinaryFormatter bf = new BinaryFormatter();

            outDs = (DataSet)bf.Deserialize(outMs, null);
            return(outDs);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// 문자열을 받아 데이터 셋을 리턴합니다.
        /// </summary>
        /// <param name="str">압축문자열.</param>
        /// <returns>데이터 셋</returns>
        public static DataSet DecompressDataSet(string str)
        {
            try
            {
                byte[] bytDs = Convert.FromBase64String(str);

                DataSet outDs = new DataSet();


                MemoryStream inMs = new MemoryStream(bytDs);
                inMs.Seek(0, 0);


                DeflateStream zipStream = new DeflateStream(inMs, CompressionMode.Decompress, true);
                byte[]        outByt    = ReadFullStream(zipStream);
                zipStream.Flush();
                zipStream.Close();


                MemoryStream outMs = new MemoryStream(outByt);
                outMs.Seek(0, 0);
                outDs.RemotingFormat = SerializationFormat.Binary;


                BinaryFormatter bf = new BinaryFormatter();
                outDs = (DataSet)bf.Deserialize(outMs, null);
                return(outDs);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// 데이터 셋을 받아 바이트로 리턴합니다.
        /// </summary>
        /// <param name="ds">The ds.</param>
        /// <returns></returns>
        private static byte[] CompressDataSet(DataSet ds)
        {
            try
            {
                //1. 데이터셋 Serialize
                ds.RemotingFormat = SerializationFormat.Binary;
                BinaryFormatter bf = new BinaryFormatter();
                MemoryStream    ms = new MemoryStream();
                bf.Serialize(ms, ds);
                byte[] inbyt = ms.ToArray();

                //2. 데이터 압축
                System.IO.MemoryStream objStream = new MemoryStream();
                DeflateStream          objZS     = new DeflateStream(objStream, CompressionMode.Compress);
                objZS.Write(inbyt, 0, inbyt.Length);
                objZS.Flush();
                objZS.Close();

                //3. 데이터 리턴
                return(objStream.ToArray());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 16
0
 //------------------------------------------------------------------------------------------
 /// <summary>
 /// Compress and returns the supplied source bytes-array data. Optionally the use of the GZip algorithm can be specified (default is Deflate).
 /// NOTE: Usage of the GZip algorithm adds cyclic-redudancy checks, which is well suitted for publishing the result externally (as in files).
 /// </summary>
 public static byte[] Compress(byte[] Source, bool AsGZip = false)
 {
     using (var Result = new MemoryStream())
     {
         if (AsGZip)
         {
             using (var Compressor = new GZipStream(Result, CompressionMode.Compress))
             {
                 Compressor.Write(Source, 0, Source.Length);
                 Compressor.Flush();
                 Compressor.Close();
                 return(Result.ToArray());
             }
         }
         else
         {
             using (var Compressor = new DeflateStream(Result, CompressionMode.Compress))
             {
                 Compressor.Write(Source, 0, Source.Length);
                 Compressor.Flush();
                 Compressor.Close();
                 return(Result.ToArray());
             }
         }
     }
 }
Ejemplo n.º 17
0
        public static byte[] CompressPacketsForWrapper(List <Packet> packets, CompressionLevel compressionLevel = CompressionLevel.Fastest)
        {
            long length = 0;

            foreach (Packet packet in packets)
            {
                length += packet.Encode().Length;
            }

            compressionLevel = length > 1000 ? compressionLevel : CompressionLevel.NoCompression;

            using (MemoryStream stream = MiNetServer.MemoryStreamManager.GetStream())
            {
                int checksum;
                using (var compressStream = new DeflateStream(stream, compressionLevel, true))
                {
                    foreach (Packet packet in packets)
                    {
                        byte[] bs = packet.Encode();
                        if (bs != null && bs.Length > 0)
                        {
                            BatchUtils.WriteLength(compressStream, bs.Length);
                            compressStream.Write(bs, 0, bs.Length);
                        }
                        packet.PutPool();
                    }
                    compressStream.Flush();
                }

                byte[] bytes = stream.ToArray();
                return(bytes);
            }
        }
Ejemplo n.º 18
0
        static unsafe byte[] CompressFlipRb3(byte[] data, int height, int stride)
        {
            using var compressStream = new MemoryStream();
            compressStream.Write(FakeDeflateHeader, 0, FakeDeflateHeader.Length);

            using (var compressor = new DeflateStream(compressStream, CompressionLevel.Fastest))
            {
                fixed(byte *srcPtr = data)
                {
                    byte *srcPtrOff = srcPtr;

                    for (int v = 0; v < height; v++)
                    {
                        compressor.WriteByte(0);
                        for (int u = 0; u < stride; u += 3, srcPtrOff += 3)
                        {
                            byte tmp = srcPtrOff[0];
                            srcPtrOff[0] = srcPtrOff[2];
                            srcPtrOff[2] = tmp;
                        }

                        compressor.Write(data, v * stride, stride);
                    }
                }

                compressor.Flush();
                compressor.Close();
            }

            return(compressStream.ToArray());
        }
Ejemplo n.º 19
0
        public byte[] Decompress(byte[] byteArray_DeflateCompressedData)
        {
            MemoryStream memoryStream_CompressedData = new MemoryStream(byteArray_DeflateCompressedData, 0, byteArray_DeflateCompressedData.Length);

            memoryStream_DecompressedData.SetLength(0);

            memoryStream_CompressedData.Position = 0;

            DeflateStream deflateStream_obj = new DeflateStream(memoryStream_CompressedData, CompressionMode.Decompress, true);

            int int_DecompressedByte = 0;

            for (; ;)
            {
                int_DecompressedByte = deflateStream_obj.ReadByte();

                if (int_DecompressedByte == -1)
                {
                    break;
                }

                memoryStream_DecompressedData.WriteByte((byte)int_DecompressedByte);
            }

            deflateStream_obj.Flush();
            deflateStream_obj.Close();

            memoryStream_CompressedData.Close();

            memoryStream_DecompressedData.SetLength(memoryStream_DecompressedData.Position);

            return(memoryStream_DecompressedData.ToArray());
        }
Ejemplo n.º 20
0
 public static byte[] GZipDecompress(this byte[] bin)
 {
     try
     {
         using (System.IO.MemoryStream msCommpressed = new System.IO.MemoryStream())
         {
             msCommpressed.Write(bin, 0, bin.Length);
             msCommpressed.Flush();
             msCommpressed.Position = 0;
             //msCommpressed.Position = 0;
             using (DeflateStream zip = new DeflateStream(msCommpressed, CompressionMode.Decompress))
             {
                 using (System.IO.MemoryStream msDecompressed = new MemoryStream())
                 {
                     zip.CopyTo(msDecompressed);
                     zip.Flush();
                     zip.Close();
                     //msDecompressed.Position = 0;
                     msDecompressed.Flush();
                     msCommpressed.Close();
                     return(msDecompressed.ToArray());
                 }
             }
         }
     }
     catch (Exception x)
     {
         throw x;
     }
 }
Ejemplo n.º 21
0
 public void OnSerialize(BinaryWriter writer)
 {
     using (MemoryStream memoryStream1 = new MemoryStream())
     {
         using (BinaryWriter blockWriter = new BinaryWriter(memoryStream1))
         {
             blockWriter.Write(xStart);
             blockWriter.Write(yStart);
             blockWriter.Write(width);
             blockWriter.Write(height);
             WriteTileBlock(blockWriter, xStart, yStart, width, height);
             memoryStream1.Position = 0L;
             MemoryStream memoryStream2 = new MemoryStream();
             using (DeflateStream deflateStream = new DeflateStream(memoryStream2, CompressionMode.Compress, true))
             {
                 memoryStream1.CopyTo(deflateStream);
                 deflateStream.Flush();
             }
             if (memoryStream1.Length <= memoryStream2.Length)
             {
                 writer.Write((byte)0);
                 writer.BaseStream.Write(memoryStream1.GetBuffer(), 0, (int)memoryStream2.Length);
             }
             else
             {
                 writer.Write((byte)1);
                 writer.BaseStream.Write(memoryStream2.GetBuffer(), 0, (int)memoryStream2.Length);
             }
         }
     }
 }
Ejemplo n.º 22
0
 public static byte[] Deflate(byte[] data, bool compress)
 {
     if (compress)
     {
         using (MemoryStream ms = new MemoryStream())
         {
             using (DeflateStream zs = new DeflateStream(ms, CompressionMode.Compress))
             {
                 zs.Write(data, 0, data.Length);
                 zs.Flush();
             }
             return(ms.ToArray());
         }
     }
     else
     {
         using (MemoryStream ms = new MemoryStream(data))
             using (MemoryStream md = new MemoryStream())
             {
                 using (DeflateStream zs = new DeflateStream(ms, CompressionMode.Decompress))
                 {
                     byte[] buf = new byte[4096];
                     int    len = 0;
                     while ((len = zs.Read(buf, 0, buf.Length)) > 0)
                     {
                         md.Write(buf, 0, len);
                     }
                 }
                 return(md.ToArray());
             }
     }
 }
Ejemplo n.º 23
0
        // BEGIN CALLOUT A
        public static SqlBytes fn_compress(SqlBytes blob)
        // END CALLOUT A
        {
            if (blob.IsNull)
            {
                return(blob);
            }
            // BEGIN CALLOUT B
            // Retrieve the BLOB's data.
            byte[] blobData = blob.Buffer;
            // END CALLOUT B
            // BEGIN CALLOUT C
            // Prepare for compression.
            MemoryStream  compressedData = new MemoryStream();
            DeflateStream compressor     = new DeflateStream(compressedData,
                                                             CompressionMode.Compress, true);

            // Write the uncompressed data using a DeflateStream compressor.
            compressor.Write(blobData, 0, blobData.Length);
            // Close the compressor to allow all the compressed bytes to be written.
            compressor.Flush();
            compressor.Close();
            compressor = null;
            // END CALLOUT C
            // Return the compressed blob.
            return(new SqlBytes(compressedData));
        }
Ejemplo n.º 24
0
        /// <summary>压缩数据流</summary>
        /// <param name="inStream">输入流</param>
        /// <param name="outStream">输出流。如果不指定,则内部实例化一个内存流</param>
        /// <remarks>返回输出流,注意此时指针位于末端</remarks>
        public static Stream Compress(this Stream inStream, Stream outStream = null)
        {
            var ms = outStream ?? new MemoryStream();

            // 第三个参数为true,保持数据流打开,内部不应该干涉外部,不要关闭外部的数据流
#if NET4
            using (var stream = new DeflateStream(ms, CompressionMode.Compress, true))
            {
                inStream.CopyTo(stream);
                stream.Flush();
            }
#else
            using (var stream = new DeflateStream(ms, CompressionLevel.Optimal, true))
            {
                inStream.CopyTo(stream);
                stream.Flush();
            }
#endif

            // 内部数据流需要把位置指向开头
            if (outStream == null)
            {
                ms.Position = 0;
            }

            return(ms);
        }
Ejemplo n.º 25
0
        DeflateStream CompressedStream = null;//压缩流

        /// <summary>
        /// 压缩文件
        /// </summary>
        /// <param name="filepath">源文件</param>
        /// <param name="dir">目标目录</param>
        /// <returns></returns>
        public MemoryStream SerFileZip(string filepath)
        {
            FileStream   SourceFile = null;
            MemoryStream SerFile    = new MemoryStream();

            try
            {
                byte[] buffer;
                string filename = System.IO.Path.GetFileNameWithoutExtension(filepath);//获取文件名
                SourceFile = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read);
                buffer     = new byte[SourceFile.Length];
                SourceFile.Read(buffer, 0, buffer.Length);//读取源文件

                CompressedStream = new DeflateStream(SerFile, CompressionMode.Compress, true);
                CompressedStream.Write(buffer, 0, buffer.Length);//压缩
                CompressedStream.Flush();
                return(SerFile);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (SourceFile != null)
                {
                    SourceFile.Close();
                }

                if (CompressedStream != null)
                {
                    CompressedStream.Close();
                }
            }
        }
Ejemplo n.º 26
0
        static public DataTable DecompressionDataTable(byte[] bytes)
        {
            MemoryStream mStream = new MemoryStream(bytes);

            mStream.Seek(0, SeekOrigin.Begin);

            DeflateStream unZipStream = new DeflateStream(mStream, CompressionMode.Decompress, true);

            byte[] unZipBytes = StreamOperator.ReadWholeStream(unZipStream);
            unZipStream.Flush();
            unZipStream.Close();

            MemoryStream resultStream = new MemoryStream(unZipBytes);

            resultStream.Seek(0, SeekOrigin.Begin);

            DataTable dtResult = new DataTable();

            dtResult.RemotingFormat = SerializationFormat.Binary;
            BinaryFormatter bFormatter = new BinaryFormatter();

            dtResult = (DataTable)bFormatter.Deserialize(resultStream, null);

            return(dtResult);
        }
Ejemplo n.º 27
0
        //**********************************************************************************************************//
        // Object
        //**********************************************************************************************************//

        /// <summary>
        /// Object를 Base64 형태의 스트링으로 압축하여 리턴한다.
        /// </summary>
        /// <param name="type"></param>
        /// <param name="object_value"></param>
        /// <returns></returns>
        public string CompressObject(Type type, object object_value)
        {
            var _result = "";

            //1. 데이터셋 Serialize
            using (MemoryStream _is = new MemoryStream())
            {
                XmlSerializer _xs = new XmlSerializer(type);
                _xs.Serialize(_is, object_value);

                //2. 데이터 압축
                using (MemoryStream _os = new MemoryStream())
                {
                    using (DeflateStream _zs = new DeflateStream(_os, CompressionMode.Compress))
                    {
                        byte[] _pbuff = _is.ToArray();
                        _zs.Write(_pbuff, 0, _pbuff.Length);
                        _zs.Flush();
                    }

                    //3. 데이터 리턴
                    byte[] _zbuff = _os.ToArray();
                    _result = Convert.ToBase64String(_zbuff, 0, _zbuff.Length);
                }
            }

            return(_result);
        }
Ejemplo n.º 28
0
        /// Send data to the web socket
        public void Send(ArraySegment <byte> buffer, WebSocketMessageType messageType, bool endOfMessage)
        {
            using (MemoryStream stream = _recycledStreamFactory())
            {
                WebSocketOpCode opCode = GetOppCode(messageType);

                if (_usePerMessageDeflate)
                {
                    // NOTE: Compression is currently work in progress and should NOT be used in this library.
                    // The code below is very inefficient for small messages. Ideally we would like to have some sort of moving window
                    // of data to get the best compression. And we don't want to create new buffers which is bad for GC.
                    using (MemoryStream temp = new MemoryStream())
                    {
                        DeflateStream deflateStream = new DeflateStream(temp, CompressionMode.Compress);
                        deflateStream.Write(buffer.Array, buffer.Offset, buffer.Count);
                        deflateStream.Flush();
                        var compressedBuffer = new ArraySegment <byte>(temp.ToArray());
                        WebSocketFrameWriter.Write(opCode, compressedBuffer, stream, endOfMessage, _isClient);
                        _logger(LogLevel.Debug, $"websocket.SendingFrame: {opCode}, {endOfMessage}, {compressedBuffer.Count}, compressed");
                    }
                }
                else
                {
                    WebSocketFrameWriter.Write(opCode, buffer, stream, endOfMessage, _isClient);
                    _logger(LogLevel.Debug, $"websocket.SendingFrame: {opCode}, {endOfMessage}, {buffer.Count}, uncompressed");
                }

                WriteStreamToNetwork(stream);
                _isContinuationFrame = !endOfMessage; // TODO: is this correct??
            }
        }
Ejemplo n.º 29
0
        //**********************************************************************************************************//
        // DataSet
        //**********************************************************************************************************//

        /// <summary>
        /// DataSet을 Base64 형태의 스트링으로 압축하여 리턴한다.
        /// </summary>
        /// <param name="plain_data_set"></param>
        /// <returns></returns>
        public string CompressDataSet(DataSet plain_data_set)
        {
            var _result = "";

            using (MemoryStream _is = new MemoryStream())
            {
                //1. 데이터셋 Serialize
                plain_data_set.RemotingFormat = SerializationFormat.Binary;

                BinaryFormatter _bform = new BinaryFormatter();
                _bform.Serialize(_is, plain_data_set);

                //2. 데이터 압축
                using (MemoryStream _os = new MemoryStream())
                {
                    using (DeflateStream _zs = new DeflateStream(_os, CompressionMode.Compress))
                    {
                        byte[] _pbuff = _is.ToArray();
                        _zs.Write(_pbuff, 0, _pbuff.Length);
                        _zs.Flush();
                    }

                    //3. 데이터 리턴
                    byte[] _zbuff = _os.ToArray();
                    _result = Convert.ToBase64String(_zbuff, 0, _zbuff.Length);
                }
            }

            return(_result);
        }
Ejemplo n.º 30
0
        private void EncodeTextMessage(WebSocketPackage package)
        {
            var encoder = _encoding.GetEncoder();
            var text    = package.Message.AsSpan();

            var completed = false;

            var outputStream = new WritableSequenceStream();

            using (var stream = new DeflateStream(outputStream, CompressionMode.Compress))
            {
                while (!completed)
                {
                    var         buffer = _arrayPool.Rent(_deflateBufferSize);
                    Span <byte> span   = buffer;

                    encoder.Convert(text, span, false, out int charsUsed, out int bytesUsed, out completed);

                    if (charsUsed > 0)
                    {
                        text = text.Slice(charsUsed);
                    }

                    stream.Write(buffer, 0, bytesUsed);
                }

                stream.Flush();
            }

            package.Data = outputStream.GetUnderlyingSequence();
        }
Ejemplo n.º 31
0
        public async Task Flush()
        {
            var ms = new MemoryStream();
            var ds = new DeflateStream(ms, CompressionMode.Compress);
            ds.Flush();
            await ds.FlushAsync();

            // Just ensuring Flush doesn't throw
        }
Ejemplo n.º 32
0
 public void FlushFailsAfterDispose()
 {
     var ms = new MemoryStream();
     var ds = new DeflateStream(ms, CompressionMode.Compress);
     ds.Dispose();
     Assert.Throws<ObjectDisposedException>(() => { ds.Flush(); });
 }
Ejemplo n.º 33
0
 public void DoubleFlush()
 {
     var ms = new MemoryStream();
     var ds = new DeflateStream(ms, CompressionMode.Compress);
     ds.Flush();
     ds.Flush();
 }
Ejemplo n.º 34
0
 public void FlushThenDispose()
 {
     var ms = new MemoryStream();
     var ds = new DeflateStream(ms, CompressionMode.Compress);
     ds.Flush();
     ds.Dispose();
 }
Ejemplo n.º 35
0
 public async Task Flush()
 {
     var ms = new MemoryStream();
     var ds = new DeflateStream(ms, CompressionMode.Compress);
     ds.Flush();
     await ds.FlushAsync();
 }