Exemplo n.º 1
0
        private static MemoryStream UnZip(byte[] data)
        {
            if (data == null)
            {
                return(null);
            }
            MemoryStream        memoryStream        = null;
            MemoryStream        memoryStream2       = null;
            InflaterInputStream inflaterInputStream = null;

            try
            {
                memoryStream        = new MemoryStream(data);
                memoryStream2       = new MemoryStream();
                inflaterInputStream = new InflaterInputStream(memoryStream);
                byte[] array = new byte[data.Length];
                while (true)
                {
                    int num = inflaterInputStream.Read(array, 0, array.Length);
                    if (num <= 0)
                    {
                        break;
                    }
                    memoryStream2.Write(array, 0, num);
                }
                memoryStream2.Flush();
                memoryStream2.Seek(0L, SeekOrigin.Begin);
            }
            finally
            {
                if (memoryStream != null)
                {
                    memoryStream.Close();
                }
                if (inflaterInputStream != null)
                {
                    inflaterInputStream.Close();
                }
                memoryStream        = null;
                inflaterInputStream = null;
            }
            return(memoryStream2);
        }
Exemplo n.º 2
0
        private List <byte> Decompress(FileStream data, long offset, long length)
        {
            var    t        = new List <byte>();
            var    inflator = new Inflater();
            Stream stream   = CopyStream(data, offset, (int)length);
            var    in1      = new InflaterInputStream(stream, inflator, 1024 * 8);

            var buffer = new byte[1024 * 8];
            int len;

            while ((len = in1.Read(buffer, 0, 1024 * 8)) > 0)
            {
                for (int i = 0; i < len; i++)
                {
                    t.Add(buffer[i]);
                }
            }
            return(t);
        }
            public override bool Load(Stream input)
            {
                if (this._IsLoaded == true)
                {
                    return(true);
                }

                input.Seek(this._DataOffset, SeekOrigin.Begin);
                this._Data = new byte[this.Size];
                var inflater = new InflaterInputStream(input);

                if (inflater.Read(this._Data, 0, this._Data.Length) != this._Data.Length)
                {
                    throw new InvalidOperationException();
                }

                this._IsLoaded = true;
                return(true);
            }
Exemplo n.º 4
0
        private static byte[] ZlibDecompress(Stream data, int expectedLength)
        {
            // This assumes that Zlib won't be used in combination with another compression type
            byte[] Output = new byte[expectedLength];
            Stream s      = new InflaterInputStream(data);
            int    Offset = 0;

            while (expectedLength > 0)
            {
                int size = s.Read(Output, Offset, expectedLength);
                if (size == 0)
                {
                    break;
                }
                Offset         += size;
                expectedLength -= size;
            }
            return(Output);
        }
Exemplo n.º 5
0
        private static byte[] unpackStageFour(byte[] pkaBuffer3)
        {
            byte[] xmlResult = new byte[(pkaBuffer3[0] * 0x1000000) + (pkaBuffer3[1] * 0x10000) + (pkaBuffer3[2] * 0x100) + (pkaBuffer3[3] * 0x1)]; // first 4 bytes are size
            var    zlibdata  = pkaBuffer3.ToList();

            zlibdata.RemoveRange(0, 4);

            InflaterInputStream inflate = new InflaterInputStream(new MemoryStream(zlibdata.ToArray()));

            inflate.Read(xmlResult, 0, xmlResult.Length);

#if DEBUG
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine(Encoding.UTF8.GetString(xmlResult.ToList().GetRange(0, 420).ToArray()));
            Console.ForegroundColor = ConsoleColor.Gray;
#endif

            return(xmlResult);
        }
Exemplo n.º 6
0
        protected override string DoDownloadSubtitle(string fileName, SubtitleInfo si)
        {
            OPMedia.Runtime.ProTONE.NuSoap.SubtitleDownload sd = new OPMedia.Runtime.ProTONE.NuSoap.SubtitleDownload();
            int x = 0;

            int.TryParse(si.IDSubtitleFile, out x);

            sd.cod_subtitle_file = x;
            sd.movie_hash        = si.MovieHash;

            string destPath = Path.ChangeExtension(fileName, si.SubFormat);

            SubtitleArchive[] archives = _wsdl.downloadSubtitles(new OPMedia.Runtime.ProTONE.NuSoap.SubtitleDownload[] { sd });

            if (archives != null && archives.Length > 0)
            {
                byte[] decodedBytes = Convert.FromBase64String(archives[0].data);

                using (MemoryStream compressedSubtitle = new MemoryStream(decodedBytes))
                {
                    using (InflaterInputStream str = new InflaterInputStream(compressedSubtitle))
                    {
                        using (FileStream outputSubtitle = new FileStream(destPath, FileMode.Create, FileAccess.Write, FileShare.Read))
                        {
                            byte[] buffer = new byte[65536];
                            int    read   = 0;
                            do
                            {
                                read = str.Read(buffer, 0, buffer.Length);
                                if (read > 0)
                                {
                                    outputSubtitle.Write(buffer, 0, read);
                                }
                            }while (read > 0);
                        }
                    }
                }

                return(destPath);
            }

            return(string.Empty);
        }
Exemplo n.º 7
0
    public static byte[] DeCompress(byte[] data)
    {
        MemoryStream memory = new MemoryStream();

        byte[] writeData = new byte[4096];
        using (InflaterInputStream stream = new InflaterInputStream(new MemoryStream(data)))
        {
            while (true)
            {
                int size = stream.Read(writeData, 0, writeData.Length);
                if (size <= 0)
                {
                    break;
                }
                memory.Write(writeData, 0, size);
            }
        }
        return(memory.ToArray());
    }
Exemplo n.º 8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="dataOffset"></param>
        /// <param name="fileDataOffset"></param>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public byte[] ReadFileDataZipped(long dataOffset, long fileDataOffset, long bytes)
        {
            InflaterInputStream zipped = null;

            try
            {
                byte []      compressed = ReadFileData(dataOffset, fileDataOffset, bytes);
                MemoryStream ms         = new MemoryStream(compressed, 0, compressed.Length);
                ms.Seek(0, SeekOrigin.Begin);
                zipped = new InflaterInputStream(ms);

                if (bytes <= int.MaxValue)
                {
                    byte[] byteArr = new byte[bytes];
                    int    size    = 0;
                    int    offset  = 0;

                    try
                    {
                        do
                        {
                            size    = zipped.Read(byteArr, offset, byteArr.Length);
                            offset += size;
                        } while (size > 0);
                    }
                    catch (RelicTools.Exceptions.Exception ex)
                    {
                        throw new FileNotZippedException(ex);
                    }

                    return(byteArr);
                }
                else
                {
                    throw new RelicTools.Exceptions.Exception("File larger than 2GB!");
                }
            }
            finally
            {
                zipped.Close();
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// 解压
        /// </summary>
        /// <param name="inputdata"></param>
        /// <param name="ds"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public static bool Decompress(string inputdata, ref DataSet ds, ref string error)
        {
            try
            {
                //inputdata = inputdata.Replace("-", "+").Replace("_", "/").Replace(".", "=");
                byte[]       bb   = Convert.FromBase64String(inputdata);
                MemoryStream data = new MemoryStream(bb);

                //int s1 = (int)data.Length;

                using (MemoryStream m = new MemoryStream())
                {
                    using (InflaterInputStream mem = new InflaterInputStream(data))
                    {
                        byte[] buffer = new byte[4096];
                        while (true)
                        {
                            int size = mem.Read(buffer, 0, buffer.Length);
                            m.Write(buffer, 0, size);
                            if (size == 0)
                            {
                                break;
                            }
                        }
                        mem.Close();
                        mem.Dispose();
                    }

                    m.Seek(0, SeekOrigin.Begin);
                    BinaryFormatter bf = new BinaryFormatter();
                    ds = bf.Deserialize(m) as DataSet;
                    m.Close();
                    m.Dispose();
                }
                return(true);
            }
            catch (Exception ex)
            {
                error = ex.Message;
                return(false);
            }
        }
Exemplo n.º 10
0
        public static MemoryStream UnZip(byte[] data)
        {
            InflaterInputStream zipStream = new InflaterInputStream(new MemoryStream(data));

            byte[]       buffer      = new byte[data.Length];
            MemoryStream upZipStream = new MemoryStream();

            while (true)
            {
                int num = zipStream.Read(buffer, 0, buffer.Length);
                if (num <= 0)
                {
                    break;
                }
                upZipStream.Write(buffer, 0, num);
            }
            upZipStream.Flush();
            upZipStream.Seek(0, SeekOrigin.Begin);
            return(upZipStream);
        }
Exemplo n.º 11
0
        public static void Decompress(Stream output, byte[] input)
        {
            using var stream   = new MemoryStream(input);
            using var inflater = new InflaterInputStream(stream);

            stream.Position = 0;

            int  count = 0;
            long start = output.Position;

            byte[] buffer = new byte[2048];

            while ((count = inflater.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, count);
            }

            output.Flush();
            output.Position = start;
        }
Exemplo n.º 12
0
        protected void addDecompressedProgramChecksum(FileStream pFileStream, ref Crc32 pChecksum)
        {
            if (this.compressedProgramLength > 0)
            {
                InflaterInputStream inflater;
                int    read;
                byte[] data = new byte[READ_CHUNK_SIZE];

                pFileStream.Seek((long)(RESERVED_SECTION_OFFSET + this.reservedSectionLength), SeekOrigin.Begin);
                inflater = new InflaterInputStream(pFileStream);

                while ((read = inflater.Read(data, 0, READ_CHUNK_SIZE)) > 0)
                {
                    pChecksum.Update(data, 0, read);
                }

                inflater.Close();
                inflater.Dispose();
            }
        }
Exemplo n.º 13
0
        public static byte[] Decompress(byte[] data)
        {
            using var stream   = new MemoryStream(data);
            using var inflater = new InflaterInputStream(stream);
            var result = new List <byte>();
            var buffer = new byte[512];

            while (true)
            {
                var bytes = inflater.Read(buffer);
                result.AddRange(buffer.Take(bytes));

                if (bytes < buffer.Length)
                {
                    break;
                }
            }

            return(result.ToArray());
        }
Exemplo n.º 14
0
        public static MemoryStream ProcessData(byte[] data)
        {
            if (data == null)
            {
                return(null);
            }
            MemoryStream        baseInputStream = null;
            MemoryStream        stream2;
            InflaterInputStream stream3 = null;

            try
            {
                baseInputStream = new MemoryStream(data);
                stream2         = new MemoryStream();
                stream3         = new InflaterInputStream(baseInputStream);
                byte[] buffer = new byte[data.Length];
                while (true)
                {
                    int count = stream3.Read(buffer, 0, buffer.Length);
                    if (count <= 0)
                    {
                        break;
                    }
                    stream2.Write(buffer, 0, count);
                }
                stream2.Flush();
                stream2.Seek(0L, SeekOrigin.Begin);
            }
            finally
            {
                if (baseInputStream != null)
                {
                    baseInputStream.Close();
                }
                if (stream3 != null)
                {
                    stream3.Close();
                }
            }
            return(stream2);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Decompresses data with format 'Deflate'. 对应 php.gzuncompress
        /// 调用该函数记得加try...catch...
        /// </summary>
        public static byte[] DecompressDeflate(byte[] data)
        {
            MemoryStream outputStream = new MemoryStream();

            MemoryStream inputStream = new MemoryStream(data);

            using (InflaterInputStream decompressZipStream = new InflaterInputStream(inputStream))
            {
                int    count;
                byte[] buffer = new byte[128];
                while ((count = decompressZipStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    outputStream.Write(buffer, 0, count);
                }
            }

            byte[] output = outputStream.ToArray();
            outputStream.Close();

            return(output);
        }
Exemplo n.º 16
0
 private byte[] DecompressData(byte[] data)
 {
     using (var input = new MemoryStream(data))
         using (var stream = new InflaterInputStream(input))
         {
             byte[] buffer = new byte[4096];
             using (var output = new MemoryStream())
             {
                 int bytesRead = 0;
                 do
                 {
                     bytesRead = stream.Read(buffer, 0, 4096);
                     if (bytesRead > 0)
                     {
                         output.Write(buffer, 0, bytesRead);
                     }
                 }while (bytesRead > 0);
                 return(output.ToArray());
             }
         }
 }
Exemplo n.º 17
0
        private string Decompress(byte[] data)
        {
            string result = null;

            using (var memory = new MemoryStream())
            {
                using (var zlib = new InflaterInputStream(new MemoryStream(data)))
                {
                    var buffer = new byte[0x1000];
                    var count  = 0;
                    while ((count = zlib.Read(buffer, 0, 0x1000)) > 0)
                    {
                        memory.Write(buffer, 0, count);
                    }
                    zlib.Close();
                }
                result = Encoding.UTF8.GetString(memory.ToArray());
                memory.Close();
            }
            return(result);
        }
Exemplo n.º 18
0
        /// <summary>
        /// SharpZip½âѹËõ
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public static byte[] DecompressSharpZip(byte[] buffer)
        {
            if (buffer == null || buffer.Length == 0)
            {
                return(buffer);
            }

            using (MemoryStream inStream = new MemoryStream(buffer))
            {
                InflaterInputStream unCompressStream = new InflaterInputStream(inStream);
                MemoryStream        outStream        = new MemoryStream();
                int    mSize;
                Byte[] mWriteData = new Byte[4096];
                while ((mSize = unCompressStream.Read(mWriteData, 0, mWriteData.Length)) > 0)
                {
                    outStream.Write(mWriteData, 0, mSize);
                }
                unCompressStream.Close();
                return(outStream.ToArray());
            }
        }
Exemplo n.º 19
0
        public static void DecompressData(byte[] inData, out byte[] outData, int tgt_size)
        {
            ICSharpCode.SharpZipLib.Zip.Compression.Inflater infl =
                new ICSharpCode.SharpZipLib.Zip.Compression.Inflater(false);
            var inStream = new InflaterInputStream(new MemoryStream(inData), infl);

            outData = new byte[tgt_size];
            try
            {
                int numRead = inStream.Read(outData, 0, tgt_size);
                if (numRead != tgt_size)
                {
                    throw  new Exception();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unexpected exception - '{0}'", ex.Message);
                throw;
            }
        }
Exemplo n.º 20
0
        public void EncodeDecode(CompressionLevel compression)
        {
            const int count     = 2 * 4096 * 4;
            var       expected  = GetBuffer(count);
            var       reference = new byte[count];
            var       actual    = new byte[count];

            using (var compressed = new MemoryStream())
            {
                using (var deflate = new ZlibOutputStream(compressed, compression))
                {
                    deflate.Write(expected);
                }

                compressed.Position = 0;

                using (var refInflate = new InflaterInputStream(compressed))
                {
                    refInflate.IsStreamOwner = false;
                    refInflate.Read(reference);
                }

                compressed.Position = 0;

                using (var inflate = new ZlibInputStream(compressed))
                {
                    inflate.Read(actual);
                }
            }

            for (int i = 0; i < expected.Length; i++)
            {
                byte e = expected[i];
                byte r = reference[i];
                byte a = actual[i];

                Assert.Equal(e, r);
                Assert.Equal(e, a);
            }
        }
Exemplo n.º 21
0
        public void Export(string path)
        {
            try
            {
                var        fi  = new FileInfo(path + @"\" + this.ID.ToString() + " " + this.FileName);
                FileStream fs  = fi.Open(FileMode.Create, FileAccess.Write);
                var        ms  = new MemoryStream(this.ZipSize);
                var        inf = new Inflater();
                var        s   = new InflaterInputStream(ms, inf, this.ZipSize);
                // put the compressed file contents into a memory stream
                ms.Write(this.FileContents, 0, this.ZipSize);
                ms.Position = 0;
                // decompress the stream into the file stream
                // using a 4KB buffer
                int bytes  = 4096;
                var buffer = new Byte[bytes];
                while (true)
                {
                    bytes = s.Read(buffer, 0, buffer.Length);
                    if (bytes > 0)
                    {
                        fs.Write(buffer, 0, bytes);
                    }
                    else
                    {
                        break;
                    }
                }
                // close all streams
                ms.Close();
                s.Close();
                fs.Close();

                LogMessageToFile(@"Exported " + fi);
            }
            catch (Exception e)
            {
                LogMessageToFile(@"Unable to export document " + this.FileName + @"ERROR: " + e.Message);
            }
        }
Exemplo n.º 22
0
        void ReadRecord(Record record, bool compressed)
        {
            //Log($"Recd: {record.Header.Type}");
            if (!compressed)
            {
                record.Read(_r, FilePath, Format);
                return;
            }
            var newDataSize = _r.ReadUInt32();
            var data        = _r.ReadBytes((int)record.Header.DataSize - 4);
            var newData     = new byte[newDataSize];

            using (var s = new MemoryStream(data))
                using (var gs = new InflaterInputStream(s))
                    gs.Read(newData, 0, newData.Length);
            // read record
            record.Header.Position = 0;
            record.Header.DataSize = newDataSize;
            using (var s = new MemoryStream(newData))
                using (var r = new BinaryFileReader(s))
                    record.Read(r, FilePath, Format);
        }
        private static byte[] Inflate(MemoryStream ms, int length)
        {
            ms.Seek(0L, 0);
            Inflater            inflater            = new Inflater(false);
            InflaterInputStream inflaterInputStream = new InflaterInputStream(ms, inflater);

            byte[] array = new byte[length];
            int    num   = 0;
            int    num2  = array.Length;

            try
            {
                while (true)
                {
                    int num3 = inflaterInputStream.Read(array, num, num2);
                    if (num3 <= 0)
                    {
                        break;
                    }
                    num  += num3;
                    num2 -= num3;
                }
            }
            catch (Exception ex)
            {
                LocalStorageAPI.s_log.LogWarning("EXCEPTION (Inflate): {0}", new object[]
                {
                    ex.get_Message()
                });
                byte[] result = null;
                return(result);
            }
            if (num != length)
            {
                LocalStorageAPI.s_log.LogWarning("Decompressed size does not equal expected size.");
                return(null);
            }
            return(array);
        }
Exemplo n.º 24
0
        public static GenericReader Decompress(GenericReader gr)
        {
            int uncompressedLength = gr.ReadInt32();

            byte[] input  = gr.ReadBytes((int)gr.Remaining);
            byte[] output = new byte[uncompressedLength];
            gr.Close();
            InflaterInputStream istream = new InflaterInputStream(new MemoryStream(input));
            int offset = 0;

            while (true)
            {
                int size = istream.Read(output, offset, uncompressedLength);
                if (size == uncompressedLength)
                {
                    break;
                }
                offset             += size;
                uncompressedLength -= size;
            }
            return(new GenericReader(new MemoryStream(output)));
        }
Exemplo n.º 25
0
        /// <summary>
        /// Inflater解压
        /// </summary>
        /// <param name="baseBytes"></param>
        /// <returns></returns>
        public static byte[] Decompress(byte[] baseBytes)
        {
            try
            {
#if (DEBUG)
                if (baseBytes != null && baseBytes.Length > 0)
                {
                    string resultStr = string.Empty;
                    using (MemoryStream memoryStream = new MemoryStream(baseBytes))
                    {
                        using (InflaterInputStream inf = new InflaterInputStream(memoryStream))
                        {
                            using (MemoryStream buffer = new MemoryStream())
                            {
                                byte[] result = new byte[1024];
                                int    resLen;
                                while ((resLen = inf.Read(result, 0, result.Length)) > 0)
                                {
                                    buffer.Write(result, 0, resLen);
                                }
                                //resultStr = Encoding.UTF8.GetString(result);
                                byte[] bytes = buffer.ToArray();
                                //resultStr = Encoding.UTF8.GetString(bytes);
                                return(bytes);
                            }
                        }
                    }
                }
                else
                {
                    return(new byte[0]);
                }
#endif
            }
            catch (Exception e)
            {
                return(new byte[0]);
            }
        }
Exemplo n.º 26
0
        public static byte[] DeCompress(byte[] pBytes)
        {
            MemoryStream mMemory = new MemoryStream();

            using (InflaterInputStream mStream = new InflaterInputStream(new MemoryStream(pBytes)))
            {
                Int32  mSize;
                byte[] mWriteData = new byte[4096];
                while (true)
                {
                    mSize = mStream.Read(mWriteData, 0, mWriteData.Length);
                    if (mSize > 0)
                    {
                        mMemory.Write(mWriteData, 0, mSize);
                    }
                    else
                    {
                        break;
                    }
                }
            }
            return(mMemory.ToArray());
        }
Exemplo n.º 27
0
        public string Decompress(byte[] baseBytes)
        {
            string resultStr = string.Empty;

            using (MemoryStream memoryStream = new MemoryStream(baseBytes))
            {
                using (InflaterInputStream inf = new InflaterInputStream(memoryStream))
                {
                    using (MemoryStream buffer = new MemoryStream())
                    {
                        byte[] result = new byte[1024];

                        int resLen;
                        while ((resLen = inf.Read(result, 0, result.Length)) > 0)
                        {
                            buffer.Write(result, 0, resLen);
                        }
                        resultStr = Encoding.Default.GetString(result);
                    }
                }
            }
            return(resultStr);
        }
Exemplo n.º 28
0
        private static byte[] ZlibDecompress(Stream Data, int ExpectedLength)
        {
            // This assumes that Zlib won't be used in combination with another compression type
            var Output = new byte[ExpectedLength];
            var s      = new InflaterInputStream(Data);
            var Offset = 0;

            while (true)
            {
                if (ExpectedLength == 0)
                {
                    break;
                }
                var size = s.Read(Output, Offset, ExpectedLength);
                if (size == 0)
                {
                    break;
                }
                Offset         += size;
                ExpectedLength -= size;
            }
            return(Output);
        }
Exemplo n.º 29
0
        public static byte[] DeCompress(byte [] b)
        {
            Stream s2 = new InflaterInputStream(new MemoryStream(b));

            try
            {
                byte [] dest = null;
                int     size = s2.Read(writeData, 0, writeData.Length);
                if (size > 0)
                {
                    dest = new byte[size];
                    Buffer.BlockCopy(writeData, 0, dest, 0, size);
                }
                s2.Flush();
                s2.Close();
                return(dest);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(null);
            }
        }
Exemplo n.º 30
0
 /// <summary>
 /// Decompresses the provided data, returning the inflated result.
 /// </summary>
 /// <param name="data">the deflated picture data.</param>
 /// <returns>the inflated picture data.</returns>
 private static byte[] InflatePictureData(byte[] data)
 {
     using (MemoryStream out1 = new MemoryStream()) {
         try {
             using (MemoryStream ms = new MemoryStream(data)) {
                 Inflater inflater = new Inflater(false);
                 using (InflaterInputStream in1 = new InflaterInputStream(ms, inflater)) {
                     byte[] buf = new byte[4096];
                     int    ReadBytes;
                     while ((ReadBytes = in1.Read(buf, 0, buf.Length)) > 0)
                     {
                         out1.Write(buf, 0, ReadBytes);
                     }
                     return(out1.ToArray());
                 }
             }
         }
         catch (IOException e) {
             log.Log(POILogger.INFO, "Possibly corrupt compression or non-compressed data", e);
             return(data);
         }
     }
 }
Exemplo n.º 31
0
        public List<String> TD_Request_NonAsyncChart_Snapshot(string _streamStockSymbol, string chartSource, int nDays)
        {

            List<String> cSortedLines = new List<string>();

            try
            {
                string _streamerCommand = "S=" + chartSource.ToUpper() + "&C=GET&P=" + _streamStockSymbol.ToUpper() + ",0,610," + nDays.ToString() + "d,1m";

                if (this.TD_loginStatus == true)
                {

                    XMLHTTP xmlHttp_ = new XMLHTTP();
                    StringBuilder cpostdata = new StringBuilder();
                    string lcPostUrl = string.Empty;

                    cpostdata.Append("!U=" + _accountid);
                    cpostdata.Append("&W=" + _token);
                    cpostdata.Append("&A=userid=" + _accountid);
                    cpostdata.Append("&token=" + _token);
                    cpostdata.Append("&company=" + _company);
                    cpostdata.Append("&segment=" + _segment);
                    cpostdata.Append("&cddomain=" + _cdDomain);
                    cpostdata.Append("&usergroup=" + _usergroup);
                    cpostdata.Append("&accesslevel=" + _accesslevel);
                    cpostdata.Append("&authorized=" + _authorized);
                    cpostdata.Append("&acl=" + _acl);
                    cpostdata.Append("&timestamp=" + _timestamp);
                    cpostdata.Append("&appid=" + _appid);
                    cpostdata.Append("|" + _streamerCommand);

                    string encodedString = Encode_URL(cpostdata.ToString());
                    cpostdata = new StringBuilder();
                    cpostdata.Append(encodedString);

                    lcPostUrl = "http://" + this._streamerurl + "/" + cpostdata;


                    /*/
                     *   Read the response and decompress the chart data
                     * 
                    /*/


                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(lcPostUrl);
                    req.ContentType = "application/x-www-form-urlencoded";
                    req.Accept = "Accept image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, application/x-shockwave-flash, */*";
                    req.Method = "GET";
                    req.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
                    req.Timeout = 60000;
                    req.ServicePoint.ConnectionLimit = 50;



                    //req.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
                    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

                    Stream respStream = resp.GetResponseStream();


                    byte[] chunk = new byte[65535 * 10];
                    byte[] ChartByteArray = new byte[65535 * 10];

                    int bytesRead = respStream.Read(ChartByteArray, 0, ChartByteArray.Length);
                    string compressedText = Convert.ToBase64String(ChartByteArray);
                    byte[] gzBuffer = Convert.FromBase64String(compressedText);

                    respStream.Flush();
                    resp.Close();
                    respStream.Close();


                    MemoryStream ms = new MemoryStream();


                    int nFieldNDX = 0;
                    int nStartPos = 21;
                    int msgLength = BitConverter.ToInt32(gzBuffer, 0);
                    ms.Write(gzBuffer, 64, gzBuffer.Length - 64);


                    byte[] nMsg = new byte[sizeof(Int32)];


                    /*/
                     * S = Streaming
                     * N = Snapshot
                    /*/

                    nMsg[0] = gzBuffer[nFieldNDX++];
                    string cRequestType = System.Text.Encoding.ASCII.GetString(nMsg, 0, 1);

                    // Skip these next 4 bytes
                    nFieldNDX = nFieldNDX + 4;


                    // Get message length
                    nMsg = new byte[sizeof(Int32)];
                    nMsg[0] = gzBuffer[nFieldNDX++];
                    nMsg[1] = gzBuffer[nFieldNDX++];
                    nMsg[2] = gzBuffer[nFieldNDX++];
                    nMsg[3] = gzBuffer[nFieldNDX++];
                    Array.Reverse(nMsg);
                    string nTotalMessageLength = TD_GetResponseValue(100, nMsg, nStartPos, 0);


                    /*/
                     * 52 / 82 - NASDAQ Chart
                     * 53 / 83 - NYSE Chart
                     * 55 / 85 - Indices Chart
                    /*/
                    nMsg = new byte[sizeof(short)];
                    nMsg[1] = gzBuffer[nFieldNDX++];
                    nMsg[0] = gzBuffer[nFieldNDX++];
                    int nSID = BitConverter.ToInt16(nMsg, 0);
                    string cStreamingRequestChart = string.Empty;
                    switch (nSID)
                    {

                        case 82:
                            cStreamingRequestChart = " NASDAQ Chart";
                            break;
                        case 83:
                            cStreamingRequestChart = " NYSE Chart";
                            break;
                        case 85:
                            cStreamingRequestChart = " Indices Chart";
                            break;
                    }


                    // Get stock symbol length
                    nMsg = new byte[sizeof(short)];
                    nMsg[1] = gzBuffer[nFieldNDX++];
                    nMsg[0] = gzBuffer[nFieldNDX++];
                    int nSymbolLength = BitConverter.ToInt16(nMsg, 0);


                    // Get stock symbol
                    nStartPos = nFieldNDX;
                    nMsg = new byte[nSymbolLength];
                    Array.Copy(gzBuffer, nStartPos, nMsg, 0, nSymbolLength);
                    string cSymbol = TD_GetResponseValue(0, nMsg, 0, nSymbolLength);

                    nFieldNDX = nFieldNDX + nSymbolLength;


                    // Get status
                    nMsg = new byte[sizeof(short)];
                    nMsg[1] = gzBuffer[nFieldNDX++];
                    nMsg[0] = gzBuffer[nFieldNDX++];
                    int nStatus = BitConverter.ToInt16(nMsg, 0);


                    // Get length of compressed data
                    nMsg = new byte[sizeof(Int32)];
                    nMsg[0] = gzBuffer[nFieldNDX++];
                    nMsg[1] = gzBuffer[nFieldNDX++];
                    nMsg[2] = gzBuffer[nFieldNDX++];
                    nMsg[3] = gzBuffer[nFieldNDX++];
                    Array.Reverse(nMsg);
                    string nTotalLenOfCompressedData = TD_GetResponseValue(100, nMsg, nStartPos, 0);

                    ms.Close();

                    byte[] CompressedData = new byte[Convert.ToInt32(nTotalLenOfCompressedData)];
                    Array.Copy(gzBuffer, nFieldNDX, CompressedData, 0, Convert.ToInt32(nTotalLenOfCompressedData));


                    StringBuilder cTempData = new StringBuilder();
                    int totalLength = 0;
                    byte[] writeData = new byte[65535 * 10];
                    Stream s2 = new InflaterInputStream(new MemoryStream(CompressedData));

                    try
                    {
                        while (true)
                        {
                            int size = s2.Read(writeData, 0, writeData.Length);
                            if (size > 0)
                            {
                                totalLength += size;
                                cTempData.Append(System.Text.Encoding.ASCII.GetString(writeData, 0, size));
                            }
                            else
                            {
                                break;
                            }
                        }
                        s2.Close();

                        string[] cLines = cTempData.ToString().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (string cs in cLines)
                        {
                            cSortedLines.Add(cs);
                        }


                    }
                    catch (Exception) { s2.Close(); return cSortedLines; }

                }


                GC.Collect();
            }
            catch (Exception) { }


            return cSortedLines;
        }
Exemplo n.º 32
0
            public void process_AsyncChartSnapshot(IAsyncResult asyncResult)
            {

                try
                {


                    // Get the RequestState object from the asyncresult
                    RequestState rs = (RequestState)asyncResult.AsyncState;

                    if (rs.lNewStockSymbol == true)
                    {
                        rs.CloseStream(rs);

                        return;

                    }


                    if (rs.Request.ServicePoint.CurrentConnections > 0)
                    {

                        List<String> cSortedLines = new List<string>();


                        // Pull out the ResponseStream that was set in RespCallback
                        Stream responseStream = rs.ResponseStream;

                        // At this point rs.BufferRead should have some data in it.
                        // Read will tell us if there is any data there

                        int read = responseStream.EndRead(asyncResult);


                        if (read > 0)
                        {
                            // Make sure we store all the incoming data until we reach the end.

                            Array.Copy(rs.BufferRead, 0, ChartByteArray2, ChartByteArray2NDx, read);
                            ChartByteArray2NDx = ChartByteArray2NDx + read;

                            // Make another call so that we continue retrieving any all incoming data                                    
                            IAsyncResult ar = responseStream.BeginRead(rs.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), rs);

                        }
                        else
                        {

                            ChartByteArray2NDx = 0;

                            // If we have not more bytes read, then the server has finished sending us data.
                            if (read == 0)
                            {

                                string compressedText = Convert.ToBase64String(ChartByteArray2);
                                byte[] gzBuffer = Convert.FromBase64String(compressedText);


                                MemoryStream ms = new MemoryStream();


                                int nFieldNDX = 0;
                                int nStartPos = 21;
                                int msgLength = BitConverter.ToInt32(gzBuffer, 0);
                                ms.Write(gzBuffer, 64, gzBuffer.Length - 64);


                                byte[] nMsg = new byte[sizeof(Int32)];


                                /*/
                                 * S = Streaming
                                 * N = Snapshot
                                /*/

                                nMsg[0] = gzBuffer[nFieldNDX++];
                                string cRequestType = System.Text.Encoding.ASCII.GetString(nMsg, 0, 1);

                                // Skip these next 4 bytes
                                nFieldNDX = nFieldNDX + 4;


                                // Get message length
                                nMsg = new byte[sizeof(Int32)];
                                nMsg[0] = gzBuffer[nFieldNDX++];
                                nMsg[1] = gzBuffer[nFieldNDX++];
                                nMsg[2] = gzBuffer[nFieldNDX++];
                                nMsg[3] = gzBuffer[nFieldNDX++];
                                Array.Reverse(nMsg);
                                string nTotalMessageLength = TD_GetResponseValue(100, nMsg, nStartPos, 0);


                                /*/
                                 * 52 / 82 - NASDAQ Chart
                                 * 53 / 83 - NYSE Chart
                                 * 55 / 85 - Indices Chart
                                /*/

                                nMsg = new byte[sizeof(short)];
                                nMsg[1] = gzBuffer[nFieldNDX++];
                                nMsg[0] = gzBuffer[nFieldNDX++];
                                int nSID = BitConverter.ToInt16(nMsg, 0);
                                string cStreamingRequestChart = string.Empty;
                                switch (nSID)
                                {

                                    case 82:
                                        cStreamingRequestChart = " NASDAQ Chart";

                                        break;
                                    case 83:
                                        cStreamingRequestChart = " NYSE Chart";

                                        break;
                                    case 85:
                                        cStreamingRequestChart = " Indices Chart";

                                        break;
                                }


                                // Get stock symbol length
                                nMsg = new byte[sizeof(short)];
                                nMsg[1] = gzBuffer[nFieldNDX++];
                                nMsg[0] = gzBuffer[nFieldNDX++];
                                int nSymbolLength = BitConverter.ToInt16(nMsg, 0);


                                // Get stock symbol
                                nStartPos = nFieldNDX;
                                nMsg = new byte[nSymbolLength];
                                Array.Copy(gzBuffer, nStartPos, nMsg, 0, nSymbolLength);
                                string cSymbol = TD_GetResponseValue(0, nMsg, 0, nSymbolLength);

                                nFieldNDX = nFieldNDX + nSymbolLength;


                                // Get status
                                nMsg = new byte[sizeof(short)];
                                nMsg[1] = gzBuffer[nFieldNDX++];
                                nMsg[0] = gzBuffer[nFieldNDX++];
                                int nStatus = BitConverter.ToInt16(nMsg, 0);


                                // Get length of compressed data
                                nMsg = new byte[sizeof(Int32)];
                                nMsg[0] = gzBuffer[nFieldNDX++];
                                nMsg[1] = gzBuffer[nFieldNDX++];
                                nMsg[2] = gzBuffer[nFieldNDX++];
                                nMsg[3] = gzBuffer[nFieldNDX++];
                                Array.Reverse(nMsg);
                                string nTotalLenOfCompressedData = TD_GetResponseValue(100, nMsg, nStartPos, 0);


                                ms.Close();

                                byte[] CompressedData = new byte[Convert.ToInt32(nTotalLenOfCompressedData)];
                                Array.Copy(gzBuffer, nFieldNDX, CompressedData, 0, Convert.ToInt32(nTotalLenOfCompressedData));


                                StringBuilder cTempData = new StringBuilder();
                                int totalLength = 0;
                                byte[] writeData = new byte[BUFFER_SIZE];
                                Stream s2 = new InflaterInputStream(new MemoryStream(CompressedData));

                                try
                                {
                                    while (true)
                                    {
                                        int size = s2.Read(writeData, 0, writeData.Length);
                                        if (size > 0)
                                        {
                                            totalLength += size;
                                            cTempData.Append(System.Text.Encoding.ASCII.GetString(writeData, 0, size));
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }
                                    s2.Close();

                                    string[] cLines = cTempData.ToString().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                                    foreach (string cs in cLines)
                                    {
                                        cSortedLines.Add(cs);
                                    }

                                    rs.SendHistoricalChartData(cSortedLines, rs.stockSymbol, rs.ServiceName);

                                }
                                catch (Exception)
                                {
                                    s2.Close();
                                }

                            }
                        }
                    }
                }
                catch (Exception exc) { }
            }