本文整理汇总了C#中ICompressor.Compress方法的典型用法代码示例。如果您正苦于以下问题:C# ICompressor.Compress方法的具体用法?C# ICompressor.Compress怎么用?C# ICompressor.Compress使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ICompressor
的用法示例。
在下文中一共展示了ICompressor.Compress方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ExecuteFileTests
private void ExecuteFileTests(ICompressor compressor, string extension, List<string> exclusions)
{
// Bung the folder name and extension onto each element - makes it easier in testing membership
// Since we don't have linq in .net 2 land :}
for (var i = 0; i < exclusions.Count; i++)
{
exclusions[i] = "Compatability Test Files\\" + exclusions[i] + extension;
}
var sourceFiles = Directory.GetFiles("Compatability Test Files", "*" + extension);
Assume.That(sourceFiles.Length, Is.GreaterThan(0), "No matching source files found, nothing to test");
foreach (var file in Directory.GetFiles("Compatability Test Files", "*" + extension))
{
if (exclusions.Contains(file))
{
continue;
}
var source = File.ReadAllText(file);
var expected = File.ReadAllText(file + ".min");
// Some of the test files have a load of carriage returns at the end, so we should strip those out
while (expected.EndsWith("\n"))
{
expected = expected.Substring(0, expected.Length - 1);
}
// Act
var actual = compressor.Compress(source);
// Assert
Assert.That(actual, Is.EqualTo(expected), file);
}
}
示例2: Performance
public void Performance(ICompressor compressor)
{
results.Add("---------" + compressor.GetType() + "---------");
byte[] indata = Encoding.UTF8.GetBytes(testData);
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
byte[] result = null;
foreach (var i in Enumerable.Range(0,100))
{
result = compressor.Compress(indata);
}
stopwatch.Stop();
long ticks = stopwatch.ElapsedTicks;
results.Add("Compress: " + ticks);
stopwatch.Reset();
stopwatch.Start();
byte[] resurrected;
foreach (var i in Enumerable.Range(0, 100))
{
resurrected = compressor.Decompress(result);
}
stopwatch.Stop();
ticks = stopwatch.ElapsedTicks;
results.Add("Decompress: " + ticks);
results.Add("Compression: " + result.Length / (1.0 * indata.Length));
}
示例3: GetCompressedContents
public static string GetCompressedContents(IEnumerable<string> bundle, string basePath, ICompressor compressor)
{
var fileList = bundle.ToList();
var tempLookup = new ConcurrentDictionary<int, string>();
Parallel.For(0, fileList.Count(), index =>
{
var file = fileList[index];
var filePathName = Path.Combine(basePath, file);
var fileContents = File.ReadAllText(filePathName, Encoding.UTF8);
try
{
fileContents = compressor.Compress(fileContents);
}
catch (Exception)
{
Log.Warn("Error during compression (using uncompressed file) - " + file);
}
tempLookup[index] = fileContents;
});
var contents = new StringBuilder();
for (var index = 0; index < fileList.Count; index++)
{
contents.Append(tempLookup[index]);
}
return contents.ToString();
}
示例4: CompressResponseNormal
private static async Task CompressResponseNormal(IOwinContext context, ICompressor tmpCompressor,
Stream responseStream, CancellationToken cancellationToken)
{
using (var tmpBufferStream = new MemoryStream())
{
await tmpCompressor.Compress(context.Response.Body, tmpBufferStream, cancellationToken);
context.Response.ContentLength = tmpBufferStream.Length;
await BaseCompressor.Pump(tmpBufferStream, responseStream, cancellationToken);
}
}
示例5: UploadFileWithCompress
public static MongoGridFSFileInfo UploadFileWithCompress(this IMongoRepository repository, ICompressor compressor, byte[] data,
string remoteFilename) {
compressor.ShouldNotBeNull("compressor");
var entry = new CompressedFileItem(compressor.GetType(), compressor.Compress(data));
using(var stream = new MemoryStream(FileSerializer.Serialize(entry))) {
return repository.UploadFile(remoteFilename, stream);
}
}
示例6: Compress_decompression_yields_original_data
public void Compress_decompression_yields_original_data(ICompressor compressor)
{
var randomBytes = new byte[2000];
new Randomizer().NextBytes(randomBytes);
var textBytes = Encoding.UTF8.GetBytes(testData);
foreach (var array in new[]{randomBytes,textBytes})
{
var resurrected = compressor.Decompress(compressor.Compress(array));
CollectionAssert.AreEqual(array, resurrected);
}
}
示例7: CompressContentAsync
private static async Task<HttpContent> CompressContentAsync(HttpContent content, ICompressor compressor)
{
using (content)
{
var compressed = new MemoryStream();
await compressor.Compress(await content.ReadAsStreamAsync(), compressed).ConfigureAwait(true);
compressed.Position = 0;
var newContent = new StreamContent(compressed);
newContent.Headers.ContentEncoding.Add(compressor.EncodingType);
newContent.Headers.ContentType = content.Headers.ContentType;
return newContent;
}
}
示例8: Compress
private void Compress(string sourcePath, string destinationPath, ICompressor compressor)
{
using (var originalStream = OpenRead(sourcePath))
{
using (var destinationStream = OpenWrite(destinationPath))
{
using (compressor)
{
using (var compression = compressor.Compress(originalStream))
{
compression.CopyTo(destinationStream);
}
}
}
}
}
示例9: CreateStateEntity
/// <summary>
/// <paramref name="pageState"/> 정보를 직렬화해서, <see cref="IPageStateEntity"/> 객체로 빌드합니다.
/// </summary>
/// <param name="id"></param>
/// <param name="pageState"></param>
/// <param name="compressor"></param>
/// <param name="compressThreshold"></param>
/// <returns></returns>
public static IPageStateEntity CreateStateEntity(string id, object pageState, ICompressor compressor,
int compressThreshold = 40960) {
compressor.ShouldNotBeNull("compressor");
compressThreshold.ShouldBePositive("compressThreshold");
if(IsDebugEnabled)
log.Debug("상태 정보를 가지는 인스턴스를 생성합니다. pageState=[{0}], compressor=[{1}], compressThreshold=[{2}]",
pageState, compressor, compressThreshold);
if(pageState == null)
return new PageStateEntity(id, null, false);
var serializedValue = Serializer.Serialize(pageState);
if(serializedValue.Length > compressThreshold)
return new PageStateEntity(id, compressor.Compress(serializedValue), true);
return new PageStateEntity(id, serializedValue, false);
}
示例10: Compress
private CompressionStats Compress( IGrid grid,
ICompressor compressor,
double[] errors,
string outName,
ProgressViewModel progressBar )
{
double[] leftBorders = new double[grid.ColumnCount];
double[] rightBorders = new double[grid.ColumnCount];
var qs = new IQuantization[grid.ColumnCount];
var distrs = new IDistribution[grid.ColumnCount];
progressBar.Status = "Quantizing columns...";
Parallel.For( 0, grid.ColumnCount, column =>
{
var distr = new EmpiricalDistribution( grid, column );
leftBorders[column] = double.MaxValue;
rightBorders[column] = double.MinValue;
for ( int row = 0; row < grid.RowCount; ++row )
{
double value = grid.GetValue( row, column );
leftBorders[column] = leftBorders[column] < value ? leftBorders[column] : value;
rightBorders[column] = rightBorders[column] > value ? rightBorders[column] : value;
}
var quantizer = new Quantizer( leftBorders[column], rightBorders[column] );
var quantization = quantizer.Quantize( errors[column], distr );
lock ( _lockGuard )
{
progressBar.Progress += 1.0 / ( grid.ColumnCount + 1 );
distrs[column] = distr;
qs[column] = quantization;
}
} );
var quantizations = new List<IQuantization>( qs );
var distributions = new List<IDistribution>( distrs );
progressBar.Status = "Writing archive...";
progressBar.Progress = ( double )grid.ColumnCount / ( grid.ColumnCount + 1 );
ICompressionResult result;
using ( var stream = new FileOutputStream( outName ) )
{
result = compressor.Compress( grid, quantizations, stream );
}
progressBar.Progress = 1.0;
progressBar.TryClose( );
return new CompressionStats
{
CompressionResult = result,
Distributions = distributions,
LeftBorders = leftBorders,
RightBorders = rightBorders,
Quantizations = quantizations
};
}
示例11: RunYuiCompressor
private static string RunYuiCompressor(ICompressor compressor, IList<string> pSourceFilePaths,
string pOutputFilePath, bool pCompressFileContents = true,
string pHeaderComment = null, bool pIncludeGenDateInHeaderComment = true)
{
compressor.CompressionType = pCompressFileContents ? CompressionType.Standard : CompressionType.None;
compressor.LineBreakPosition = 0; //Default is -1 (never add a line break)... 0 (zero) means add a line break after every semicolon (good for debugging)
var sbSourceText = new StringBuilder();
var sbHeadComment = new StringBuilder();
sbHeadComment.AppendLine("/*");
sbHeadComment.AppendLine();
if (pHeaderComment != null)
sbHeadComment.AppendLine(pHeaderComment);
if (pIncludeGenDateInHeaderComment)
sbHeadComment.AppendLineFormat(" Generated: {0}", DateTime.Now);
sbHeadComment.AppendLine(" Merged File List:");
var postpendLength = pSourceFilePaths.Select(Path.GetFileName).Max(x => x.Length) + 4;
string sourceFilePath = null;
foreach (var filepath in pSourceFilePaths)
{
if (string.IsNullOrWhiteSpace(sourceFilePath))
sourceFilePath = Path.GetDirectoryName(filepath);
var contentsOrig = io.ReadASCIITextFile(filepath);
var contentsMin = compressor.Compress(contentsOrig);
var sizeNote = string.Format("[Orig: {0} KB", contentsOrig.Length / 1024);
if (pCompressFileContents)
sizeNote += string.Format(", Min'd: {0} KB", contentsMin.Length / 1024);
sizeNote += "]";
var fileComment = string.Format("{0} : {1}", str.Postpend(Path.GetFileName(filepath), postpendLength, ' '), sizeNote);
sbHeadComment.AppendLineFormat(" -> {0}", fileComment);
sbSourceText.AppendLine(contentsMin); //concat the file contents
}
sbHeadComment.AppendLine();
sbHeadComment.AppendLine("*/");
sbHeadComment.AppendLine();
if (pSourceFilePaths.Count == 1 && !str.ToString(Path.GetFileName(pOutputFilePath)).Contains(".")) //single file w/o a diff filename
io.WriteTextFile(Path.Combine(pOutputFilePath, Path.GetFileName(pSourceFilePaths.First())), sbHeadComment.ToString() + sbSourceText.ToString());
else
io.WriteTextFile(pOutputFilePath, sbHeadComment.ToString() + sbSourceText.ToString()); //bundled file or file w/a diff filename
return sbHeadComment.ToString();
}
示例12: GetOutputStream
private Stream GetOutputStream()
{
if (_outputStreamInitializedFlag.Set())
{
if (HttpHeadersHelpers.IsEncodedContent(_response.Headers))
{
_outputStream = _originalStream;
}
else
{
_compressor = _compressionManager.CreateCompressor(_acceptEncoding);
_outputStream = _compressor.Compress(_originalStream);
}
}
return _outputStream;
}
示例13: CompressResponseChunked
private static async Task CompressResponseChunked(IOwinContext context, ICompressor tmpCompressor,
Stream responseStream, CancellationToken cancellationToken)
{
context.Response.Headers["Transfer-Encoding"] = "chunked";
await tmpCompressor.Compress(context.Response.Body, responseStream, cancellationToken);
}
示例14: DoBenchmark
private void DoBenchmark(ICompressor compressor, int dataSize, int batchCount)
{
var data = _dataCreator.GenerateTestData(dataSize);
byte[] compressedData = null, decompressedData = null;
var stopWatch = Stopwatch.StartNew();
for (var i = 0; i < batchCount; ++i)
{
compressedData = compressor.Compress(data);
decompressedData = compressor.Decompress(compressedData);
}
stopWatch.Stop();
var msPerCycle = (double)stopWatch.ElapsedMilliseconds / batchCount;
var compressionRate = (double)compressedData.Length / data.Length;
Console.WriteLine("\t{0} data {1} compressed {2:P1}: {3}ms per cycle",
TextUtils.GetSizeText(data.Length), TextUtils.GetSizeText(compressedData.Length),
compressionRate, msPerCycle);
}
示例15: TestCompressor
private void TestCompressor(ICompressor compressor)
{
var data = _dataCreator.GenerateTestData(637);
var compressedData = compressor.Compress(data);
var decompressedData = compressor.Decompress(compressedData);
Assert.IsTrue(data.SequenceEqual(decompressedData));
}