Пример #1
0
 internal ZipArchiveEntry(ZipArchive archive, string entryName)
 {
     this._archive                      = archive;
     this._originallyInArchive          = false;
     this._diskNumberStart              = 0;
     this._versionToExtract             = ZipVersionNeededValues.Default;
     this._generalPurposeBitFlag        = (ZipArchiveEntry.BitFlagValues) 0;
     this.CompressionMethod             = ZipArchiveEntry.CompressionMethodValues.Deflate;
     this._lastModified                 = DateTimeOffset.Now;
     this._compressedSize               = (long)0;
     this._uncompressedSize             = (long)0;
     this._externalFileAttr             = 0;
     this._offsetOfLocalHeader          = (long)0;
     this._storedOffsetOfCompressedData = null;
     this._crc32                  = 0;
     this._compressedBytes        = null;
     this._storedUncompressedData = null;
     this._currentlyOpenForWrite  = false;
     this._everOpenedForWrite     = false;
     this._outstandingWriteStream = null;
     this.FullName                = entryName;
     this._cdUnknownExtraFields   = null;
     this._lhUnknownExtraFields   = null;
     this._fileComment            = null;
     this._compressionLevel       = null;
     if ((int)this._storedEntryNameBytes.Length > 65535)
     {
         throw new ArgumentException(Messages.EntryNamesTooLong);
     }
     if (this._archive.Mode == ZipArchiveMode.Create)
     {
         this._archive.AcquireArchiveStream(this);
     }
 }
Пример #2
0
        private ZipArchiveEntry DoCreateEntry(string entryName, CompressionLevel?compressionLevel)
        {
            Contract.Ensures(Contract.Result <ZipArchiveEntry>() != null);

            if (entryName == null)
            {
                throw new ArgumentNullException(nameof(entryName));
            }

            if (string.IsNullOrEmpty(entryName))
            {
                throw new ArgumentException(SR.CannotBeEmpty, nameof(entryName));
            }

            if (_mode == ZipArchiveMode.Read)
            {
                throw new NotSupportedException(SR.CreateInReadMode);
            }

            ThrowIfDisposed();


            ZipArchiveEntry entry = compressionLevel.HasValue
                                        ? new ZipArchiveEntry(this, entryName, compressionLevel.Value)
                                        : new ZipArchiveEntry(this, entryName);

            AddEntry(entry);

            return(entry);
        }
Пример #3
0
        private ZipArchiveEntry DoCreateEntry(string entryName, CompressionLevel?compressionLevel)
        {
            if (entryName == null)
            {
                throw new ArgumentNullException(nameof(entryName));
            }

            if (string.IsNullOrEmpty(entryName))
            {
                throw new ArgumentException(SR.CannotBeEmpty, nameof(entryName));
            }

            if (_mode == ZipArchiveMode.Read)
            {
                throw new NotSupportedException(SR.CreateInReadMode);
            }

            if (_entriesDictionary.ContainsKey(entryName))
            {
                throw new InvalidOperationException(string.Format(SR.EntryNameAlreadyExists, entryName));
            }

            ThrowIfDisposed();


            ZipArchiveEntry entry = compressionLevel.HasValue ?
                                    new ZipArchiveEntry(this, entryName, compressionLevel.Value) :
                                    new ZipArchiveEntry(this, entryName);

            AddEntry(entry);

            return(entry);
        }
        public static HttpContextServerCallContext CreateServerCallContext(
            HttpContext?httpContext = null,
            List <ICompressionProvider>?compressionProviders = null,
            string?responseCompressionAlgorithm       = null,
            CompressionLevel?responseCompressionLevel = null,
            int?maxSendMessageSize    = null,
            int?maxReceiveMessageSize = null,
            ILogger?logger            = null,
            bool initialize           = true)
        {
            var options = CreateMethodOptions(
                compressionProviders,
                responseCompressionAlgorithm,
                responseCompressionLevel,
                maxSendMessageSize,
                maxReceiveMessageSize);

            var context = new HttpContextServerCallContext(
                httpContext ?? new DefaultHttpContext(),
                options,
                typeof(object),
                typeof(object),
                logger ?? NullLogger.Instance);

            if (initialize)
            {
                context.Initialize();
            }

            return(context);
        }
Пример #5
0
        private static IDeflater CreateDeflater(CompressionLevel?compressionLevel)
        {
            // The deflator type (zlib or managed) is normally determined by s_deflatorType,
            // which is initialized by the provider based on what's available on the system.
            // But for testing purposes, we sometimes want to override this, forcing
            // compression/decompression to use a particular type.
            WorkerType deflatorType = s_deflaterType;

#if DEBUG
            if (s_forcedTestingDeflaterType != WorkerType.Unknown)
            {
                deflatorType = s_forcedTestingDeflaterType;
            }
#endif

            if (deflatorType == WorkerType.ZLib)
            {
                return(compressionLevel.HasValue ?
                       new DeflaterZLib(compressionLevel.Value) :
                       new DeflaterZLib());
            }
            else
            {
                Debug.Assert(deflatorType == WorkerType.Managed);
                return(new DeflaterManaged());
            }
        }
Пример #6
0
        private ZipArchiveEntry DoCreateEntry(string entryName, CompressionLevel?compressionLevel)
        {
            if (entryName == null)
            {
                throw new ArgumentNullException(nameof(entryName));
            }

            if (string.IsNullOrEmpty(entryName))
            {
                throw new ArgumentException(nameof(entryName));
            }

            if (_mode == ZipArchiveMode.Read)
            {
                throw new NotSupportedException();
            }

            ThrowIfDisposed();


            ZipArchiveEntry entry = compressionLevel.HasValue ?
                                    new ZipArchiveEntry(this, entryName, compressionLevel.Value) :
                                    new ZipArchiveEntry(this, entryName);

            AddEntry(entry);

            return(entry);
        }
Пример #7
0
        public byte[] Compress(string src, CompressionLevel?compressionLevel = null)
        {
            if (string.IsNullOrEmpty(src))
            {
                return(null);
            }

            var byteArray       = Encoding.UTF8.GetBytes(src);
            var byteArrayLength = byteArray.Length;

            byte[] zip;

            using (var ms = new MemoryStream())
            {
                using (var zs = GetGZipStream(ms, CompressionMode.Compress, compressionLevel))
                {
                    zs.Write(byteArray, 0, byteArrayLength);
                    zs.Close();
                    zip = ms.ToArray();
                }
            }

            if (zip.Length <= 0)
            {
                return(null);
            }

            var sizeArray = BitConverter.GetBytes(byteArrayLength);
            var buffer    = new List <byte>(sizeArray);

            buffer.AddRange(zip);
            return(buffer.ToArray());
        }
Пример #8
0
        private static void DoCreateFromDirectory(String sourceDirectoryName, String destinationArchiveFileName,
                                                  CompressionLevel?compressionLevel, Boolean includeBaseDirectory,
                                                  Encoding entryNameEncoding)
        {
            // Rely on Path.GetFullPath for validation of sourceDirectoryName and destinationArchive

            // Checking of compressionLevel is passed down to DeflateStream and the IDeflater implementation
            // as it is a pluggable component that completely encapsulates the meaning of compressionLevel.

            sourceDirectoryName        = Path.GetFullPath(sourceDirectoryName);
            destinationArchiveFileName = Path.GetFullPath(destinationArchiveFileName);

            using (ZipArchive archive = Open(destinationArchiveFileName, ZipArchiveMode.Create, entryNameEncoding))
            {
                bool directoryIsEmpty = true;

                //add files and directories
                DirectoryInfo di = new DirectoryInfo(sourceDirectoryName);

                string basePath = di.FullName;

                if (includeBaseDirectory && di.Parent != null)
                {
                    basePath = di.Parent.FullName;
                }

                foreach (FileSystemInfo file in di.EnumerateFileSystemInfos("*", SearchOption.AllDirectories))
                {
                    directoryIsEmpty = false;

                    Int32 entryNameLength = file.FullName.Length - basePath.Length;
                    Debug.Assert(entryNameLength > 0);

                    String entryName = EntryFromPath(file.FullName, basePath.Length, entryNameLength);

                    if (file is FileInfo)
                    {
                        // Create entry for file:
                        ZipFileExtensions.DoCreateEntryFromFile(archive, file.FullName, entryName, compressionLevel);
                    }
                    else
                    {
                        // Entry marking an empty dir:
                        DirectoryInfo possiblyEmpty = file as DirectoryInfo;
                        if (possiblyEmpty != null && IsDirEmpty(possiblyEmpty))
                        {
                            // FullName never returns a directory separator character on the end,
                            // but Zip archives require it to specify an explicit directory:
                            archive.CreateEntry(entryName + PathSeparator);
                        }
                    }
                }  // foreach

                // If no entries create an empty root directory entry:
                if (includeBaseDirectory && directoryIsEmpty)
                {
                    archive.CreateEntry(EntryFromPath(di.Name, 0, di.Name.Length) + PathSeparator);
                }
            } // using
        }     // DoCreateFromDirectory
Пример #9
0
 internal ZipArchiveEntry(ZipArchive archive, ZipCentralDirectoryFileHeader cd)
 {
     this._archive                      = archive;
     this._originallyInArchive          = true;
     this._diskNumberStart              = cd.DiskNumberStart;
     this._versionToExtract             = (ZipVersionNeededValues)cd.VersionNeededToExtract;
     this._generalPurposeBitFlag        = (ZipArchiveEntry.BitFlagValues)cd.GeneralPurposeBitFlag;
     this.CompressionMethod             = (ZipArchiveEntry.CompressionMethodValues)cd.CompressionMethod;
     this._lastModified                 = new DateTimeOffset(ZipHelper.DosTimeToDateTime(cd.LastModified));
     this._compressedSize               = cd.CompressedSize;
     this._uncompressedSize             = cd.UncompressedSize;
     this._externalFileAttr             = cd.ExternalFileAttributes;
     this._offsetOfLocalHeader          = cd.RelativeOffsetOfLocalHeader;
     this._storedOffsetOfCompressedData = null;
     this._crc32                  = cd.Crc32;
     this._compressedBytes        = null;
     this._storedUncompressedData = null;
     this._currentlyOpenForWrite  = false;
     this._everOpenedForWrite     = false;
     this._outstandingWriteStream = null;
     this.FullName                = this.DecodeEntryName(cd.Filename);
     this._lhUnknownExtraFields   = null;
     this._cdUnknownExtraFields   = cd.ExtraFields;
     this._fileComment            = cd.FileComment;
     this._compressionLevel       = null;
 }
Пример #10
0
        private MethodOptions(
            Dictionary <string, ICompressionProvider> compressionProviders,
            InterceptorCollection interceptors,
            int?maxSendMessageSize,
            int?maxReceiveMessageSize,
            bool?enableDetailedErrors,
            string?responseCompressionAlgorithm,
            CompressionLevel?responseCompressionLevel)
        {
            CompressionProviders         = compressionProviders;
            Interceptors                 = interceptors;
            HasInterceptors              = interceptors.Count > 0;
            MaxSendMessageSize           = maxSendMessageSize;
            MaxReceiveMessageSize        = maxReceiveMessageSize;
            EnableDetailedErrors         = enableDetailedErrors;
            ResponseCompressionAlgorithm = responseCompressionAlgorithm;
            ResponseCompressionLevel     = responseCompressionLevel;

            if (ResponseCompressionAlgorithm != null)
            {
                if (!CompressionProviders.TryGetValue(ResponseCompressionAlgorithm, out var _))
                {
                    throw new InvalidOperationException($"The configured response compression algorithm '{ResponseCompressionAlgorithm}' does not have a matching compression provider.");
                }
            }
        }
Пример #11
0
        private ZipArchiveEntry DoCreateEntry(String entryName, CompressionLevel?compressionLevel)
        {
            //Contract.Ensures(Contract.Result<ZipArchiveEntry>() != null);

            // Checking of compressionLevel is passed down to DeflateStream and the IDeflater implementation
            // as it is a pugable component that completely encapsulates the meaning of compressionLevel.

            if (entryName == null)
            {
                throw new ArgumentNullException("entryName");
            }

            if (String.IsNullOrEmpty(entryName))
            {
                throw new ArgumentException(SR.CannotBeEmpty, "entryName");
            }

            if (_mode == ZipArchiveMode.Read)
            {
                throw new NotSupportedException(SR.CreateInReadMode);
            }

            ThrowIfDisposed();


            ZipArchiveEntry entry = compressionLevel.HasValue
                                        ? new ZipArchiveEntry(this, entryName, compressionLevel.Value)
                                        : new ZipArchiveEntry(this, entryName);

            AddEntry(entry);

            return(entry);
        }
Пример #12
0
 internal static ZipArchiveEntry DoCreateEntryFromFile(
     ZipArchive destination,
     string sourceFileName,
     string entryName,
     CompressionLevel?compressionLevel)
 {
     if (destination == null)
     {
         throw new ArgumentNullException(nameof(destination));
     }
     if (sourceFileName == null)
     {
         throw new ArgumentNullException(nameof(sourceFileName));
     }
     if (entryName == null)
     {
         throw new ArgumentNullException(nameof(entryName));
     }
     using (Stream stream = (Stream)File.Open(sourceFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
     {
         ZipArchiveEntry zipArchiveEntry = compressionLevel.HasValue ? destination.CreateEntry(entryName, compressionLevel.Value) : destination.CreateEntry(entryName);
         DateTime        dateTime        = File.GetLastWriteTime(sourceFileName);
         if (dateTime.Year < 1980 || dateTime.Year > 2107)
         {
             dateTime = new DateTime(1980, 1, 1, 0, 0, 0);
         }
         zipArchiveEntry.LastWriteTime = (DateTimeOffset)dateTime;
         using (Stream destination1 = zipArchiveEntry.Open())
             stream.CopyTo(destination1);
         return(zipArchiveEntry);
     }
 }
Пример #13
0
        //Initializes, attaches it to archive
        internal ZipArchiveEntry(ZipArchive archive, ZipCentralDirectoryFileHeader cd, CompressionLevel compressionLevel)

            : this(archive, cd)
        {
            // Checking of compressionLevel is passed down to DeflateStream and the IDeflater implementation
            // as it is a pugable component that completely encapsulates the meaning of compressionLevel.

            _compressionLevel = compressionLevel;
        }
 /// <summary>
 /// Create a new compression stream.
 /// </summary>
 /// <param name="stream">The stream that compressed data is written to.</param>
 /// <param name="compressionLevel">The compression level.</param>
 /// <returns>A stream used to compress data.</returns>
 public Stream CreateCompressionStream(Stream stream, CompressionLevel?compressionLevel)
 {
     // As described in RFC 2616, the deflate content-coding is actually
     // the "zlib" format (RFC 1950) in combination with the "deflate"
     // compression algrithm (RFC 1951).  So while potentially
     // counterintuitive based on naming, this needs to use ZLibStream
     // rather than DeflateStream.
     return(new ZLibStream(stream, compressionLevel ?? _defaultCompressionLevel));
 }
Пример #15
0
        public ImageOptions(CompressionLevel?compressionLevel, ImageDimensions dimensions)
        {
            if (dimensions == null)
            {
                throw new ArgumentNullException("dimensions");
            }

            _compressionLevel = compressionLevel;
            _dimensions       = dimensions;
        }
Пример #16
0
 /// <summary>
 /// Add Sentry Serilog Sink.
 /// </summary>
 /// <param name="loggerConfiguration">The logger configuration .<seealso cref="LoggerSinkConfiguration"/></param>
 /// <param name="dsn">The Sentry DSN. <seealso cref="SentryOptions.Dsn"/></param>
 /// <param name="minimumEventLevel">Minimum log level to send an event. <seealso cref="SentrySerilogOptions.MinimumEventLevel"/></param>
 /// <param name="minimumBreadcrumbLevel">Minimum log level to record a breadcrumb. <seealso cref="SentrySerilogOptions.MinimumBreadcrumbLevel"/></param>
 /// <param name="formatProvider">The Serilog format provider. <seealso cref="IFormatProvider"/></param>
 /// <param name="textFormatter">The Serilog text formatter. <seealso cref="ITextFormatter"/></param>
 /// <param name="sendDefaultPii">Whether to include default Personal Identifiable information. <seealso cref="SentryOptions.SendDefaultPii"/></param>
 /// <param name="isEnvironmentUser">Whether to report the <see cref="System.Environment.UserName"/> as the User affected in the event. <seealso cref="SentryOptions.IsEnvironmentUser"/></param>
 /// <param name="serverName">Gets or sets the name of the server running the application. <seealso cref="SentryOptions.ServerName"/></param>
 /// <param name="attachStackTrace">Whether to send the stack trace of a event captured without an exception. <seealso cref="SentryOptions.AttachStacktrace"/></param>
 /// <param name="maxBreadcrumbs">Gets or sets the maximum breadcrumbs. <seealso cref="SentryOptions.MaxBreadcrumbs"/></param>
 /// <param name="sampleRate">The rate to sample events. <seealso cref="SentryOptions.SampleRate"/></param>
 /// <param name="release">The release version of the application. <seealso cref="SentryOptions.Release"/></param>
 /// <param name="environment">The environment the application is running. <seealso cref="SentryOptions.Environment"/></param>
 /// <param name="maxQueueItems">The maximum number of events to keep while the worker attempts to send them. <seealso cref="SentryOptions.MaxQueueItems"/></param>
 /// <param name="shutdownTimeout">How long to wait for events to be sent before shutdown. <seealso cref="SentryOptions.ShutdownTimeout"/></param>
 /// <param name="decompressionMethods">Decompression methods accepted. <seealso cref="SentryOptions.DecompressionMethods"/></param>
 /// <param name="requestBodyCompressionLevel">The level of which to compress the <see cref="SentryEvent"/> before sending to Sentry. <seealso cref="SentryOptions.RequestBodyCompressionLevel"/></param>
 /// <param name="requestBodyCompressionBuffered">Whether the body compression is buffered and the request 'Content-Length' known in advance. <seealso cref="SentryOptions.RequestBodyCompressionBuffered"/></param>
 /// <param name="debug">Whether to log diagnostics messages. <seealso cref="SentryOptions.Debug"/></param>
 /// <param name="diagnosticLevel">The diagnostics level to be used. <seealso cref="SentryOptions.DiagnosticLevel"/></param>
 /// <param name="reportAssemblies">Whether or not to include referenced assemblies in each event sent to sentry. Defaults to <see langword="true"/>. <seealso cref="SentryOptions.ReportAssemblies"/></param>
 /// <param name="deduplicateMode">What modes to use for event automatic de-duplication. <seealso cref="SentryOptions.DeduplicateMode"/></param>
 /// <param name="initializeSdk">Whether to initialize this SDK through this integration. <seealso cref="SentrySerilogOptions.InitializeSdk"/></param>
 /// <param name="defaultTags">Defaults tags to add to all events. <seealso cref="SentryOptions.DefaultTags"/></param>
 /// <returns><see cref="LoggerConfiguration"/></returns>
 /// <example>This sample shows how each item may be set from within a configuration file:
 /// <code>
 /// {
 ///     "Serilog": {
 ///         "Using": [
 ///             "Serilog",
 ///             "Sentry",
 ///         ],
 ///         "WriteTo": [{
 ///                 "Name": "Sentry",
 ///                 "Args": {
 ///                     "dsn": "https://[email protected]",
 ///                     "minimumBreadcrumbLevel": "Verbose",
 ///                     "minimumEventLevel": "Error",
 ///                     "outputTemplate": "{Timestamp:o} [{Level:u3}] ({Application}/{MachineName}/{ThreadId}) {Message}{NewLine}{Exception}"///
 ///                     "sendDefaultPii": false,
 ///                     "isEnvironmentUser": false,
 ///                     "serverName": "MyServerName",
 ///                     "attachStackTrace": false,
 ///                     "maxBreadcrumbs": 20,
 ///                     "sampleRate": 0.5,
 ///                     "release": "0.0.1",
 ///                     "environment": "staging",
 ///                     "maxQueueItems": 100,
 ///                     "shutdownTimeout": "00:00:05",
 ///                     "decompressionMethods": "GZip",
 ///                     "requestBodyCompressionLevel": "NoCompression",
 ///                     "requestBodyCompressionBuffered": false,
 ///                     "debug": false,
 ///                     "diagnosticLevel": "Debug",
 ///                     "reportAssemblies": false,
 ///                     "deduplicateMode": "All",
 ///                     "initializeSdk": true,
 ///                     "defaultTags": {
 ///                         "key-1", "value-1",
 ///                         "key-2", "value-2"
 ///                     }
 ///                 }
 ///             }
 ///         ]
 ///     }
 /// }
 /// </code>
 /// </example>
 public static LoggerConfiguration Sentry(
     this LoggerSinkConfiguration loggerConfiguration,
     string?dsn = null,
     LogEventLevel minimumBreadcrumbLevel = LogEventLevel.Information,
     LogEventLevel minimumEventLevel      = LogEventLevel.Error,
     IFormatProvider?formatProvider       = null,
     ITextFormatter?textFormatter         = null,
     bool?sendDefaultPii      = null,
     bool?isEnvironmentUser   = null,
     string?serverName        = null,
     bool?attachStackTrace    = null,
     int?maxBreadcrumbs       = null,
     float?sampleRate         = null,
     string?release           = null,
     string?environment       = null,
     int?maxQueueItems        = null,
     TimeSpan?shutdownTimeout = null,
     DecompressionMethods?decompressionMethods    = null,
     CompressionLevel?requestBodyCompressionLevel = null,
     bool?requestBodyCompressionBuffered          = null,
     bool?debug = null,
     SentryLevel?diagnosticLevel     = null,
     bool?reportAssemblies           = null,
     DeduplicateMode?deduplicateMode = null,
     bool?initializeSdk = null,
     Dictionary <string, string>?defaultTags = null)
 {
     return(loggerConfiguration.Sentry(o => ConfigureSentrySerilogOptions(o,
                                                                          dsn,
                                                                          minimumEventLevel,
                                                                          minimumBreadcrumbLevel,
                                                                          formatProvider,
                                                                          textFormatter,
                                                                          sendDefaultPii,
                                                                          isEnvironmentUser,
                                                                          serverName,
                                                                          attachStackTrace,
                                                                          maxBreadcrumbs,
                                                                          sampleRate,
                                                                          release,
                                                                          environment,
                                                                          maxQueueItems,
                                                                          shutdownTimeout,
                                                                          decompressionMethods,
                                                                          requestBodyCompressionLevel,
                                                                          requestBodyCompressionBuffered,
                                                                          debug,
                                                                          diagnosticLevel,
                                                                          reportAssemblies,
                                                                          deduplicateMode,
                                                                          initializeSdk,
                                                                          defaultTags)));
 }
Пример #17
0
        public string Decompress(byte[] src, CompressionLevel?compressionLevel = null)
        {
            if (src == null)
            {
                return(null);
            }

            var srcLength = src.Length;

            if (srcLength == 0)
            {
                return(null);
            }

            const int intSize = sizeof(int);

            if (srcLength <= intSize)
            {
                return(null);
            }

            var zip = new byte[srcLength - intSize];

            Array.Copy(src, intSize, zip, 0, zip.Length);

            var unzipLength = BitConverter.ToInt32(src, 0);

            if (unzipLength <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(unzipLength), "zip lenght must be greater than 0");
            }

            var unzip = new byte[unzipLength];

            using (var ms = new MemoryStream(zip))
            {
                using (var zs = GetGZipStream(ms, CompressionMode.Decompress, compressionLevel))
                {
                    unzipLength = zs.Read(unzip, 0, unzipLength);
                    if (unzipLength <= 0)
                    {
                        return(null);
                    }

                    zs.Close();
                }
            }

            var result = Encoding.UTF8.GetString(unzip);

            return(result);
        }
Пример #18
0
        /// <summary>
        /// Creates method options by merging together the settings the specificed <see cref="GrpcServiceOptions"/> collection.
        /// The <see cref="GrpcServiceOptions"/> should be ordered with items arranged in ascending order of precedence.
        /// When interceptors from multiple options are merged together they will be executed in reverse order of precendence.
        /// </summary>
        /// <param name="serviceOptions">A collection of <see cref="GrpcServiceOptions"/> instances, arranged in ascending order of precedence.</param>
        /// <returns>A new <see cref="MethodOptions"/> instanced with settings merged from specifid <see cref="GrpcServiceOptions"/> collection.</returns>
        public static MethodOptions Create(IEnumerable <GrpcServiceOptions> serviceOptions)
        {
            // This is required to get ensure that service methods without any explicit configuration
            // will continue to get the global configuration options
            var              resolvedCompressionProviders    = new Dictionary <string, ICompressionProvider>(StringComparer.Ordinal);
            var              tempInterceptors                = new List <InterceptorRegistration>();
            int?             maxSendMessageSize              = null;
            var              maxSendMessageSizeConfigured    = false;
            int?             maxReceiveMessageSize           = GrpcServiceOptionsSetup.DefaultReceiveMaxMessageSize;
            var              maxReceiveMessageSizeConfigured = false;
            bool?            enableDetailedErrors            = null;
            string?          responseCompressionAlgorithm    = null;
            CompressionLevel?responseCompressionLevel        = null;

            foreach (var options in serviceOptions.Reverse())
            {
                AddCompressionProviders(resolvedCompressionProviders, options.CompressionProviders);
                tempInterceptors.InsertRange(0, options.Interceptors);
                if (!maxSendMessageSizeConfigured && options._maxSendMessageSizeConfigured)
                {
                    maxSendMessageSize           = options.MaxSendMessageSize;
                    maxSendMessageSizeConfigured = true;
                }
                if (!maxReceiveMessageSizeConfigured && options._maxReceiveMessageSizeConfigured)
                {
                    maxReceiveMessageSize           = options.MaxReceiveMessageSize;
                    maxReceiveMessageSizeConfigured = true;
                }
                enableDetailedErrors ??= options.EnableDetailedErrors;
                responseCompressionAlgorithm ??= options.ResponseCompressionAlgorithm;
                responseCompressionLevel ??= options.ResponseCompressionLevel;
            }

            var interceptors = new InterceptorCollection();

            interceptors.AddRange(tempInterceptors);

            return(new MethodOptions
                   (
                       compressionProviders: resolvedCompressionProviders,
                       interceptors: interceptors,
                       maxSendMessageSize: maxSendMessageSize,
                       maxReceiveMessageSize: maxReceiveMessageSize,
                       enableDetailedErrors: enableDetailedErrors,
                       responseCompressionAlgorithm: responseCompressionAlgorithm,
                       responseCompressionLevel: responseCompressionLevel
                   ));
        }
Пример #19
0
        // Initializes new entry
        internal ZipArchiveEntry(ZipArchive archive, string entryName)
        {
            _archive = archive;

            _originallyInArchive = false;

            _diskNumberStart            = 0;
            _versionMadeByPlatform      = CurrentZipPlatform;
            _versionMadeBySpecification = ZipVersionNeededValues.Default;
            _versionToExtract           = ZipVersionNeededValues.Default; // this must happen before following two assignment
            _generalPurposeBitFlag      = 0;
            CompressionMethod           = CompressionMethodValues.Deflate;
            _lastModified = DateTimeOffset.Now;

            _compressedSize               = 0; // we don't know these yet
            _uncompressedSize             = 0;
            _externalFileAttr             = 0;
            _offsetOfLocalHeader          = 0;
            _storedOffsetOfCompressedData = null;
            _crc32 = 0;

            _compressedBytes        = null;
            _storedUncompressedData = null;
            _currentlyOpenForWrite  = false;
            _everOpenedForWrite     = false;
            _outstandingWriteStream = null;

            FullName = entryName;

            _cdUnknownExtraFields = null;
            _lhUnknownExtraFields = null;
            _fileComment          = null;

            _compressionLevel = null;

            if (_storedEntryNameBytes.Length > ushort.MaxValue)
            {
                throw new ArgumentException();
            }

            // grab the stream if we're in create mode
            if (_archive.Mode == ZipArchiveMode.Create)
            {
                _archive.AcquireArchiveStream(this);
            }
        }
Пример #20
0
        public static void ZLibCompress(Stream stream, Stream targetStream, CompressionLevel?level = null)
        {
            using (var zs = new ZLIBStream(targetStream, level ?? CompressionLevel.Optimal, true)) {
                int    bytesLeidos = 0;
                byte[] buffer      = new byte[1024];

                stream.Seek(0, SeekOrigin.Begin);

                while ((bytesLeidos = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    zs.Write(buffer, 0, bytesLeidos);
                }
            }

            using (var bw = new BinaryWriter(targetStream))
                bw.Write((uint)stream.Length);
        }
Пример #21
0
        private static IDeflater CreateDeflater(CompressionLevel?compressionLevel)
        {
            switch (GetDeflaterType())
            {
            case WorkerType.Managed:
                return(new DeflaterManaged());

            default:
                // We do not expect this to ever be thrown.
                // But this is better practice than returning null.
#if NETFX_CORE
                throw new Exception("Program entered an unexpected state.");
#else
                throw new SystemException("Program entered an unexpected state.");
#endif
            }
        }
Пример #22
0
        protected ImageOptions GenerateImageOptions(
            ImageConfiguration configuration,
            Imaging.ImageFormat imageFormat,
            ImageDimensions imageDimensions)
        {
            CompressionLevel?compressionLevel = null;

            if (CanUseImageFormatCompression(configuration) && !configuration.HasEmbeddedImage)
            {
                compressionLevel = configuration.Compression.Level;
            }
            else if (configuration.HasEmbeddedImage && imageFormat.SupportsCompression)
            {
                compressionLevel = CompressionLevel.Standard;
            }

            return(new ImageOptions(compressionLevel, imageDimensions));
        }
        public static MethodOptions CreateMethodOptions(
            List <ICompressionProvider>?compressionProviders = null,
            string?responseCompressionAlgorithm       = null,
            CompressionLevel?responseCompressionLevel = null,
            int?maxSendMessageSize             = null,
            int?maxReceiveMessageSize          = null,
            InterceptorCollection?interceptors = null)
        {
            var serviceOptions = new GrpcServiceOptions();

            serviceOptions.CompressionProviders = compressionProviders ?? new List <ICompressionProvider>();
            serviceOptions.Interceptors.AddRange(interceptors ?? new InterceptorCollection());
            serviceOptions.MaxSendMessageSize           = maxSendMessageSize;
            serviceOptions.MaxReceiveMessageSize        = maxReceiveMessageSize;
            serviceOptions.ResponseCompressionAlgorithm = responseCompressionAlgorithm;
            serviceOptions.ResponseCompressionLevel     = responseCompressionLevel;

            return(MethodOptions.Create(new[] { serviceOptions }));
        }
Пример #24
0
        internal static byte[] CompressMessage(string compressionEncoding, CompressionLevel?compressionLevel, List <ICompressionProvider> compressionProviders, byte[] messageData)
        {
            foreach (var compressionProvider in compressionProviders)
            {
                if (string.Equals(compressionEncoding, compressionProvider.EncodingName, StringComparison.Ordinal))
                {
                    var output = new MemoryStream();
                    using (var compressionStream = compressionProvider.CreateCompressionStream(output, compressionLevel))
                    {
                        compressionStream.Write(messageData, 0, messageData.Length);
                    }

                    return(output.ToArray());
                }
            }

            // Should never reach here
            throw new InvalidOperationException($"Could not find compression provider for '{compressionEncoding}'.");
        }
Пример #25
0
        private ZipArchiveEntry DoCreateEntry(string entryName, CompressionLevel?compressionLevel)
        {
            if (entryName == null)
            {
                throw new ArgumentNullException("entryName");
            }
            if (string.IsNullOrEmpty(entryName))
            {
                throw new ArgumentException(Messages.CannotBeEmpty, "entryName");
            }
            if (this._mode == ZipArchiveMode.Read)
            {
                throw new NotSupportedException(Messages.CreateInReadMode);
            }
            this.ThrowIfDisposed();
            ZipArchiveEntry zipArchiveEntry = (compressionLevel.HasValue ? new ZipArchiveEntry(this, entryName, compressionLevel.Value) : new ZipArchiveEntry(this, entryName));

            this.AddEntry(zipArchiveEntry);
            return(zipArchiveEntry);
        }
 public static MethodContext CreateMethodContext(
     Dictionary <string, ICompressionProvider>?compressionProviders = null,
     string?responseCompressionAlgorithm       = null,
     CompressionLevel?responseCompressionLevel = null,
     int?maxSendMessageSize             = null,
     int?maxReceiveMessageSize          = null,
     InterceptorCollection?interceptors = null)
 {
     return(new MethodContext
            (
                requestType: typeof(object),
                responseType: typeof(object),
                compressionProviders: compressionProviders ?? new Dictionary <string, ICompressionProvider>(),
                interceptors: interceptors ?? new InterceptorCollection(),
                maxSendMessageSize: maxSendMessageSize,
                maxReceiveMessageSize: maxReceiveMessageSize,
                enableDetailedErrors: null,
                responseCompressionAlgorithm: responseCompressionAlgorithm,
                responseCompressionLevel: responseCompressionLevel
            ));
 }
Пример #27
0
        private void CopyEntries(ArcArchive inputArchive, ArcArchive outputArchive, IProgress?progress)
        {
            foreach (var inputEntry in inputArchive.GetEntries())
            {
                progress?.SetMessage(inputEntry.Name);

                CompressionLevel?compressionLevel = PreserveStore && (int)inputEntry.EntryType == 1
                        ? CompressionLevel.NoCompression
                        : (CompressionLevel?)null;

                var outputEntry = outputArchive.CreateEntry(inputEntry.Name);

                {
                    using var inputStream  = inputEntry.Open();
                    using var outputStream = outputEntry.OpenWrite(compressionLevel);
                    CopyStream(inputStream, outputStream, progress);
                }

                outputEntry.Timestamp = inputEntry.Timestamp;
            }
        }
Пример #28
0
        private Stream GetCompressionStream(Stream innerStream, CompressionType compressionType,
                                            CompressionMode compressionMode, CompressionLevel?compressionLevel)
        {
            switch (compressionType)
            {
            case CompressionType.Gzip:
                switch (compressionMode)
                {
                case CompressionMode.Compress:
                    return(compressionLevel == null
                                ? new GZipStream(innerStream, CompressionMode.Compress)
                                : new GZipStream(innerStream, compressionLevel.Value, true));

                case CompressionMode.Decompress:
                    return(new GZipStream(innerStream, CompressionMode.Decompress, true));

                default:
                    throw new ArgumentOutOfRangeException(nameof(compressionMode), compressionMode, null);
                }

            case CompressionType.Deflate:
                switch (compressionMode)
                {
                case CompressionMode.Compress:
                    return(compressionLevel == null
                                ? new DeflateStream(innerStream, CompressionMode.Compress)
                                : new DeflateStream(innerStream, compressionLevel.Value, true));

                case CompressionMode.Decompress:
                    return(new DeflateStream(innerStream, CompressionMode.Decompress, true));

                default:
                    throw new ArgumentOutOfRangeException(nameof(compressionMode), compressionMode, null);
                }

            default:
                throw new ArgumentOutOfRangeException(nameof(compressionType), compressionType, null);
            }
        }
Пример #29
0
        private static IDeflater CreateDeflater(CompressionLevel?compressionLevel)
        {
            switch (GetDeflaterType())
            {
            case WorkerType.Managed:
                return(new DeflaterManaged());

            case WorkerType.ZLib:
                if (compressionLevel.HasValue)
                {
                    return(new DeflaterZLib(compressionLevel.Value));
                }
                else
                {
                    return(new DeflaterZLib());
                }

            default:
                // We do not expect this to ever be thrown.
                // But this is better practice than returning null.
                throw new SystemException("Program entered an unexpected state.");
            }
        }
Пример #30
0
        private byte[] CompressInternal(byte[] data, CompressionType compressionType,
                                        CompressionLevel?compressionLevel)
        {
            if (compressionType == CompressionType.None)
            {
                return(data);
            }
            if (data.Length == 0)
            {
                return(new byte[0]);
            }
            using (var memStream = new MemoryStream())
            {
                var compressionStream = GetCompressionStream(memStream, compressionType, CompressionMode.Compress,
                                                             compressionLevel);
                using (compressionStream)
                {
                    compressionStream.Write(data, 0, data.Length);
                }

                return(memStream.ToArray());
            }
        }
Пример #31
0
        // Initializes, attaches it to archive
        internal ReadOnlyZipArchiveEntry(ReadOnlyZipArchive archive, ZipCentralDirectoryFileHeader cd)
        {
            _archive = archive;

            _originallyInArchive = true;

            _diskNumberStart            = cd.DiskNumberStart;
            _versionMadeByPlatform      = ( ZipVersionMadeByPlatform )cd.VersionMadeByCompatibility;
            _versionMadeBySpecification = ( ZipVersionNeededValues )cd.VersionMadeBySpecification;
            _versionToExtract           = ( ZipVersionNeededValues )cd.VersionNeededToExtract;
            _generalPurposeBitFlag      = ( BitFlagValues )cd.GeneralPurposeBitFlag;
            CompressionMethod           = ( CompressionMethodValues )cd.CompressionMethod;
            _lastModified        = new DateTimeOffset(ZipHelper.DosTimeToDateTime(cd.LastModified));
            _compressedSize      = cd.CompressedSize;
            _uncompressedSize    = cd.UncompressedSize;
            _externalFileAttr    = cd.ExternalFileAttributes;
            _offsetOfLocalHeader = cd.RelativeOffsetOfLocalHeader;
            // we don't know this yet: should be _offsetOfLocalHeader + 30 + _storedEntryNameBytes.Length + extrafieldlength
            // but entryname/extra length could be different in LH
            _storedOffsetOfCompressedData = null;
            _crc32 = cd.Crc32;

            _compressedBytes        = null;
            _storedUncompressedData = null;
            _currentlyOpenForWrite  = false;
            _everOpenedForWrite     = false;
            _outstandingWriteStream = null;

            FullName = DecodeEntryName(cd.Filename);

            _lhUnknownExtraFields = null;
            // the cd should have these as null if we aren't in Update mode
            _cdUnknownExtraFields = cd.ExtraFields;
            _fileComment          = cd.FileComment;

            _compressionLevel = null;
        }
Пример #32
0
        //Initializes new entry
        internal ZipArchiveEntry(ZipArchive archive, String entryName, CompressionLevel compressionLevel)

            : this(archive, entryName)
        {
            // Checking of compressionLevel is passed down to DeflateStream and the IDeflater implementation
            // as it is a pugable component that completely encapsulates the meaning of compressionLevel.

            _compressionLevel = compressionLevel;
        }
Пример #33
0
        //Initializes, attaches it to archive
        internal ZipArchiveEntry(ZipArchive archive, ZipCentralDirectoryFileHeader cd)
        {
            _archive = archive;

            _originallyInArchive = true;

            _diskNumberStart = cd.DiskNumberStart;
            _versionMadeByPlatform = (ZipVersionMadeByPlatform)cd.VersionMadeByCompatibility;
            _versionMadeBySpecification = (ZipVersionNeededValues)cd.VersionMadeBySpecification;
            _versionToExtract = (ZipVersionNeededValues)cd.VersionNeededToExtract;
            _generalPurposeBitFlag = (BitFlagValues)cd.GeneralPurposeBitFlag;
            CompressionMethod = (CompressionMethodValues)cd.CompressionMethod;
            _lastModified = new DateTimeOffset(ZipHelper.DosTimeToDateTime(cd.LastModified));
            _compressedSize = cd.CompressedSize;
            _uncompressedSize = cd.UncompressedSize;
            _offsetOfLocalHeader = cd.RelativeOffsetOfLocalHeader;
            /* we don't know this yet: should be _offsetOfLocalHeader + 30 + _storedEntryNameBytes.Length + extrafieldlength
                * but entryname/extra length could be different in LH
                */
            _storedOffsetOfCompressedData = null;
            _crc32 = cd.Crc32;

            _compressedBytes = null;
            _storedUncompressedData = null;
            _currentlyOpenForWrite = false;
            _everOpenedForWrite = false;
            _outstandingWriteStream = null;

            FullName = DecodeEntryName(cd.Filename);

            _lhUnknownExtraFields = null;
            //the cd should have these as null if we aren't in Update mode
            _cdUnknownExtraFields = cd.ExtraFields;
            _fileComment = cd.FileComment;

            _compressionLevel = null;
        }
Пример #34
0
        //Initializes, attaches it to archive
        internal ZipArchiveEntry(ZipArchive archive, ZipCentralDirectoryFileHeader cd, CompressionLevel compressionLevel)

            : this(archive, cd)
        {
            _compressionLevel = compressionLevel;
        }
Пример #35
0
        //Initializes new entry
        internal ZipArchiveEntry(ZipArchive archive, String entryName)
        {
            _archive = archive;

            _originallyInArchive = false;

            _diskNumberStart = 0;
            _versionMadeByPlatform = CurrentZipPlatform;
            _versionMadeBySpecification = ZipVersionNeededValues.Default;
            _versionToExtract = ZipVersionNeededValues.Default; //this must happen before following two assignment
            _generalPurposeBitFlag = 0;
            CompressionMethod = CompressionMethodValues.Deflate;
            _lastModified = DateTimeOffset.Now;

            _compressedSize = 0; //we don't know these yet
            _uncompressedSize = 0;
            _offsetOfLocalHeader = 0;
            _storedOffsetOfCompressedData = null;
            _crc32 = 0;

            _compressedBytes = null;
            _storedUncompressedData = null;
            _currentlyOpenForWrite = false;
            _everOpenedForWrite = false;
            _outstandingWriteStream = null;

            FullName = entryName;

            _cdUnknownExtraFields = null;
            _lhUnknownExtraFields = null;
            _fileComment = null;

            _compressionLevel = null;

            if (_storedEntryNameBytes.Length > UInt16.MaxValue)
                throw new ArgumentException(SR.EntryNamesTooLong);

            //grab the stream if we're in create mode
            if (_archive.Mode == ZipArchiveMode.Create)
            {
                _archive.AcquireArchiveStream(this);
            }
        }
Пример #36
0
        //Initializes new entry
        internal ZipArchiveEntry(ZipArchive archive, String entryName, CompressionLevel compressionLevel)

            : this(archive, entryName)
        {
            _compressionLevel = compressionLevel;
        }