예제 #1
0
        public static bool Cache(StreamBlock block)
        {
            if (!block.Header.HasFlag(StreamHeader.CACHEABLE))
            {
                throw new InvalidOperationException("Cannot cache block " + block + ", is not marked as CACHEABLE!");
            }
            CacheItem       cacheItem = new CacheItem(block.ToString(), block);
            CacheItemPolicy policy    = new CacheItemPolicy();

            policy.AbsoluteExpiration = DateTimeOffset.Now.Add(_expiration);
            CacheItem existing = _cache.AddOrGetExisting(cacheItem, policy);

            if (existing != null)
            {
                return(false);
            }
            return(true);
        }
예제 #2
0
        protected static StreamBlock BuildBlock(byte[] rawBlock)
        {
            StreamHeader header   = (StreamHeader)rawBlock.Skip(HEADER_OFFSET).Take(HEADER_LENGTH).First();
            short        streamId = BitConverter.ToInt16(rawBlock.Skip(STREAM_ID_OFFSET).Take(STREAM_ID_LENGTH).ToArray(), 0);

            byte[] checksum = rawBlock.Skip(CHECKSUM_OFFSET).Take(CHECKSUM_LENGTH).ToArray();
            if (header.HasFlag(StreamHeader.CACHEABLE))
            {
                StreamBlock block = StreamCache.GetCache(checksum);
                if (block != null)
                {
                    return(block);
                }
            }
            MD5 md5 = MD5.Create();

            byte[] data = rawBlock.Skip(DATA_OFFSET).ToArray();
            byte[] calculatedChecksum = md5.ComputeHash(data);
            if (!calculatedChecksum.SequenceEqual(checksum))
            {
                throw new InvalidDataException("Checksums did not match when checking data in BuildBlock routine! Calculated: " + BitConverter.ToString(calculatedChecksum) + " | Stored: " + BitConverter.ToString(checksum));
            }
            if (header.HasFlag(StreamHeader.GZIPPED))
            {
                using (GZipStream stream = new GZipStream(new MemoryStream(data), CompressionMode.Decompress))
                {
                    byte[] buffer = new byte[256];
                    using (MemoryStream memory = new MemoryStream())
                    {
                        int count = 0;
                        do
                        {
                            count = stream.Read(buffer, 0, buffer.Length);
                            if (count > 0)
                            {
                                memory.Write(buffer, 0, count);
                            }
                        }while (count > 0);
                        data = memory.ToArray();
                    }
                }
            }
            return(new StreamBlock(streamId, header, checksum, data));
        }