Пример #1
0
        /// <summary>
        /// Compress a stream using specified compression strength.
        /// </summary>
        /// <remarks>
        /// This returns a memory stream of the compressed results, if the incoming stream is
        /// very large this will consume a large amount memory.  In this case use the overload
        /// that takes the destination stream as a parameter instead.
        /// </remarks>
        /// <param name="source">The <see cref="Stream"/> to compress.</param>
        /// <param name="strength">The <see cref="CompressionStrength"/> of the compression.</param>
        /// <returns>Returns a <see cref="MemoryStream"/> of the compressed <see cref="Stream"/>.</returns>
        public static MemoryStream Compress(this Stream source, CompressionStrength strength)
        {
            MemoryStream destination = new MemoryStream();

            source.Compress(destination, strength, null);
            return(destination);
        }
Пример #2
0
 private static byte[] CompressToArray(this Stream stream)
 {
     using (var output = stream.Compress())
     {
         output.Close();
         return(output.ToArray());
     }
 }
Пример #3
0
        /// <summary>
        /// Writes the file asynchronous.
        /// </summary>
        /// <param name="usingPartial">if set to <c>true</c> [using partial].</param>
        /// <param name="partialHeader">The partial header.</param>
        /// <param name="fileSize">Size of the file.</param>
        /// <param name="context">The context.</param>
        /// <param name="buffer">The buffer.</param>
        /// <param name="ct">The ct.</param>
        /// <returns>A task representing the write action.</returns>
        protected Task WriteFileAsync(
            bool usingPartial,
            string partialHeader,
            long fileSize,
            IHttpContext context,
            Stream buffer,
            CancellationToken ct)
        {
            long lowerByteIndex = 0;

            if (usingPartial &&
                CalculateRange(partialHeader, fileSize, out lowerByteIndex, out var upperByteIndex))
            {
                if (upperByteIndex > fileSize)
                {
                    // invalid partial request
                    context.Response.StatusCode = 416;
                    context.Response.AddHeader(Headers.ContentRanges, $"bytes */{fileSize}");

                    return(Task.FromResult(0));
                }

                if (upperByteIndex == fileSize)
                {
                    context.Response.ContentLength64 = buffer.Length;
                }
                else
                {
                    context.Response.StatusCode      = 206;
                    context.Response.ContentLength64 = upperByteIndex - lowerByteIndex + 1;

                    context.Response.AddHeader(Headers.ContentRanges,
                                               $"bytes {lowerByteIndex}-{upperByteIndex}/{fileSize}");
                }
            }
            else
            {
                if (UseGzip &&
                    context.RequestHeader(Headers.AcceptEncoding).Contains(Headers.CompressionGzip) &&
                    buffer.Length < MaxGzipInputLength &&

                    // Ignore audio/video from compression
                    context.Response.ContentType?.StartsWith("audio") == false &&
                    context.Response.ContentType?.StartsWith("video") == false)
                {
                    // Perform compression if available
                    buffer = buffer.Compress();
                    context.Response.AddHeader(Headers.ContentEncoding, Headers.CompressionGzip);
                    lowerByteIndex = 0;
                }

                context.Response.ContentLength64 = buffer.Length;
            }

            return(WriteToOutputStream(context.Response, buffer, lowerByteIndex, ct));
        }
Пример #4
0
		public void Serialize(object instance, Stream destination)
		{
			var serializer = GetXmlSerializer(instance.GetType());

			using(var compressed = destination.Compress(true))
			using(var writer = XmlDictionaryWriter.CreateBinaryWriter(compressed, null, null, false))
			{
				serializer.WriteObject(writer, instance);
			}
		}
Пример #5
0
 private void SaveIndex()
 {
     using (FileStream fileStream = File.Open(this.indexFilePath, FileMode.Create))
     {
         using (Stream stream = GetIndexStream(this.indexTable))
         {
             stream.Compress().CopyTo(fileStream);
         }
     }
 }
Пример #6
0
		public void RepackXml(XElement data, Stream destination)
		{
			using(var compressed = destination.Compress(true))
			using(var writer = XmlDictionaryWriter.CreateBinaryWriter(compressed, null, null, false))
			{
				data.Save(writer);
				writer.Flush();
				compressed.Flush();
			}
		}
Пример #7
0
        /// <summary>
        /// Compress the stream to a file (Gzip).
        /// </summary>
        /// <param name="input">the stream to compress</param>
        /// <param name="destinationPath">Path to the compressed file.</param>
        public static void Compress(Stream input, string destinationPath)
        {
            EnsureArg.IsNotNullOrEmpty(destinationPath, nameof(destinationPath));

            using (var destination = File.Create(destinationPath))
            {
                if (input != null)
                {
                    input.Position = 0;
                    input.Compress(destination);
                    destination.Flush();
                }
            }
        }
Пример #8
0
        private async Task <bool> SendAsync(Opcode opcode, Stream stream)
        {
            await _forSend.WaitAsync().ConfigureAwait(false);

            try
            {
                var src        = stream;
                var compressed = false;
                var sent       = false;
                try
                {
                    if (_compression != CompressionMethod.None)
                    {
                        stream     = stream.Compress(_compression);
                        compressed = true;
                    }

                    sent = await SendAsync(opcode, Mask.Unmask, stream, compressed).ConfigureAwait(false);

                    if (!sent)
                    {
                        error("Sending a data has been interrupted.");
                    }
                }
                catch (Exception ex)
                {
                    error("An exception has occurred while sending a data.", ex);
                }
                finally
                {
                    if (compressed)
                    {
                        stream.Dispose();
                    }

                    src.Dispose();
                }

                return(sent);
            }
            finally
            {
                _forSend.Release();
            }
        }
Пример #9
0
        private bool send(Opcode opcode, Stream stream)
        {
            lock (_forSend)
            {
                var src        = stream;
                var compressed = false;
                var sent       = false;
                try
                {
                    if (_compression != CompressionMethod.None)
                    {
                        stream     = stream.Compress(_compression);
                        compressed = true;
                    }

                    sent = send(opcode, Mask.Unmask, stream, compressed);
                    if (!sent)
                    {
                        error("Sending a data has been interrupted.");
                    }
                }
                catch (Exception ex)
                {
                    error("An exception has occurred while sending a data.", ex);
                }
                finally
                {
                    if (compressed)
                    {
                        stream.Dispose();
                    }

                    src.Dispose();
                }

                return(sent);
            }
        }
Пример #10
0
        private bool send(Opcode opcode, Stream stream)
        {
            lock (_forSend)
              {
            var sent = false;

            var src = stream;
            var compressed = false;
            try {
              if (_compression != CompressionMethod.NONE)
              {
            stream = stream.Compress (_compression);
            compressed = true;
              }

              sent = sendFragmented (opcode, stream, _client ? Mask.MASK : Mask.UNMASK, compressed);
            }
            catch (Exception ex) {
              _logger.Fatal (ex.ToString ());
              error ("An exception has occurred.");
            }
            finally {
              if (compressed)
            stream.Dispose ();

              src.Dispose ();
            }

            return sent;
              }
        }
Пример #11
0
        // As server, used to broadcast
        internal void Send(Opcode opcode, Stream stream, Dictionary <CompressionMethod, Stream> cache)
        {
            lock (_forSend)
              {
            try {
              Stream cached;
              if (!cache.TryGetValue (_compression, out cached))
              {
            cached = stream.Compress (_compression);
            cache.Add (_compression, cached);
              }
              else
            cached.Position = 0;

              sendFragmented (opcode, cached, Mask.UNMASK, _compression != CompressionMethod.NONE);
            }
            catch (Exception ex) {
              _logger.Fatal (ex.ToString ());
              error ("An exception has occurred.");
            }
              }
        }
Пример #12
0
    // As server, used to broadcast
    internal void Send (Opcode opcode, Stream stream, Dictionary <CompressionMethod, Stream> cache)
    {
      lock (_forSend) {
        try {
          Stream cached;
          if (!cache.TryGetValue (_compression, out cached)) {
            cached = stream.Compress (_compression);
            cache.Add (_compression, cached);
          }
          else {
            cached.Position = 0;
          }

          send (opcode, cached, _compression != CompressionMethod.None);
        }
        catch (Exception ex) {
          _logger.Fatal (ex.ToString ());
        }
      }
    }
Пример #13
0
    private bool send (Opcode opcode, Stream stream)
    {
      lock (_forSend) {
        var src = stream;
        var compressed = false;
        var sent = false;
        try {
          if (_compression != CompressionMethod.None) {
            stream = stream.Compress (_compression);
            compressed = true;
          }

          sent = send (opcode, stream, compressed);
          if (!sent)
            error ("The sending has been interrupted.", null);
        }
        catch (Exception ex) {
          _logger.Fatal (ex.ToString ());
          error ("An exception has occurred while sending the data.", ex);
        }
        finally {
          if (compressed)
            stream.Dispose ();

          src.Dispose ();
        }

        return sent;
      }
    }
Пример #14
0
        // As server, used to broadcast
        internal void Send(Opcode opcode, Stream stream, Dictionary <CompressionMethod, Stream> cache)
        {
            lock (_forSend) {
            try {
              Stream cached;
              if (!cache.TryGetValue (_compression, out cached)) {
            cached = stream.Compress (_compression);
            cache.Add (_compression, cached);
              }
              else
            cached.Position = 0;

              if (_readyState == WebSocketState.Open)
            sendFragmented (opcode, cached, Mask.Unmask, _compression != CompressionMethod.None);
            }
            catch (Exception ex) {
              _logger.Fatal (ex.ToString ());
              error ("An exception has occurred while sending a data.");
            }
              }
        }
Пример #15
0
        // As server, used to broadcast
        internal void Send(Opcode opcode, Stream stream, Dictionary<CompressionMethod, Stream> cache)
        {
            lock (_forSend)
            {
                try
                {
                    Stream found;
                    if (!cache.TryGetValue(_compression, out found))
                    {
                        found = stream.Compress(_compression);
                        cache.Add(_compression, found);
                    }
                    else
                    {
                        found.Position = 0;
                    }

                    send(opcode, found, _compression != CompressionMethod.None);
                }
                catch (Exception ex)
                {
#if COMPAT
                    Log.Error(ex.ToString());
#else
                    ex.Log();
#endif
                }
            }
        }
Пример #16
0
 internal static Stream Compress(this Stream stream, CompressionMethod method)
 {
     return(method == CompressionMethod.Deflate
            ? stream.Compress()
            : stream);
 }
Пример #17
0
        private bool send(Opcode opcode, Stream stream)
        {
            lock (_forSend)
            {
                var src = stream;
                var compressed = false;
                var sent = false;
                try
                {
                    if (_compression != CompressionMethod.None)
                    {
                        stream = stream.Compress(_compression);
                        compressed = true;
                    }

                    sent = send(opcode, Mask.Unmask, stream, compressed);
                    if (!sent)
                        error("Sending a data has been interrupted.");
                }
                catch (Exception ex)
                {
                    error("An exception has occurred while sending a data.", ex);
                }
                finally
                {
                    if (compressed)
                        stream.Dispose();

                    src.Dispose();
                }

                return sent;
            }
        }
Пример #18
0
 /// <summary>
 /// COMPRESS THE OUTGOING STREAM
 /// </summary>
 private void CompressMessage()
 {
     newStream.Seek(0, SeekOrigin.Begin);
     newStream.Compress(networkStream);
 }
Пример #19
0
        private void send(Opcode opcode, Stream stream)
        {
            if (_compression == CompressionMethod.NONE || _perFrameCompress) {
                send(opcode, stream, false);
                return;
            }

            using (var compressed = stream.Compress(_compression)) {
                send(opcode, compressed, true);
            }
        }