public static void CheckThrowCancel(Cancelable cancelable, object userState = null) { if (cancelable != null && cancelable(userState) == CancelMode.Cancel) { throw new OperationCanceledException(Magic); } }
public void DiscoverReaders(StripeDiscoveryConfiguration config, Action <IList <StripeTerminalReader> > readers, Action scanTimeoutCallback) { // this assures the discovery succeeds on Android. Old code, ignores this, leading to lack of success in finding other types of readers except for Chipper2x var deviceType = DeviceType.Chipper2x; switch (config.DeviceType) { case "Chipper2X": deviceType = DeviceType.Chipper2x; break; case "VerifoneP400": deviceType = DeviceType.VerifoneP400; break; case "WisePad3": deviceType = DeviceType.Wisepad3; break; } var configuration = new DiscoveryConfiguration(config.TimeOut, deviceType, isSimulated: config.IsSimulated); _onReadersDiscoveredAction = readers; _discoveryCancelable?.Cancel(new GenericCallback((ex) => { // Do Nothing... })); _discoveryCancelable = StripeTerminal.Instance.DiscoverReaders(configuration, this, new GenericCallback((ex) => { // Do Nothing... scanTimeoutCallback(); })); }
public void When_CancelFalse_is_called_Then_first_exception_should_not_prevent_rest_from_being_called() { var c = new Cancelable(Sys.Scheduler); var callbacks = new AtomicCounter(0); c.Token.Register(() => { throw new Exception("Something wonderful has happened."); }); c.Token.Register(() => callbacks.IncrementAndGet()); c.Token.Register(() => { throw new Exception("Your AKKA is alive!!!"); }); try { //First callback should prevent the second one from being called c.Cancel(throwOnFirstException: false); } catch (AggregateException aggregateException) { aggregateException = aggregateException.Flatten(); foreach (var e in aggregateException.InnerExceptions) { if (!e.Message.StartsWith("Your") && !e.Message.StartsWith("Something")) { throw new Exception("Invalid exception received: " + e, e); } } } //HACK: Using the fact that when Cancel is called, callbacks are executed synchronously callbacks.Current.ShouldBe(1); c.IsCancellationRequested.ShouldBeTrue(); c.Token.IsCancellationRequested.ShouldBeTrue(); }
/// <summary> /// Sends a message to the tail chopping router's collection of routees. /// </summary> /// <param name="message">The message to send.</param> /// <param name="sender">The sender of the message.</param> public override void Send(object message, IActorRef sender) { _routees.Shuffle(); var routeeIndex = new AtomicCounter(0); var completion = new TaskCompletionSource <object>(); var cancelable = new Cancelable(_scheduler); _scheduler.Advanced.ScheduleRepeatedly(TimeSpan.Zero, _interval, async() => { var currentIndex = routeeIndex.GetAndIncrement(); if (currentIndex < _routees.Length) { completion.TrySetResult(await((Task <object>)_routees[currentIndex].Ask(message, null))); } }, cancelable); _scheduler.Advanced.ScheduleOnce(_within, () => { completion.TrySetException(new TimeoutException(String.Format("Ask timed out on {0} after {1}", sender, _within))); }, cancelable); var request = completion.Task; completion.Task.ContinueWith(task => { cancelable.Cancel(false); }); request.PipeTo(sender); }
public void Should_not_be_cancelled_initially() { var c = new Cancelable(Sys.Scheduler); c.IsCancellationRequested.ShouldBeFalse(); c.Token.IsCancellationRequested.ShouldBeFalse(); }
private void SendHostShardMessage(String shard, IActorRef region) { region.Tell(new HostShard(shard)); var cancelable = new Cancelable(Context.System.Scheduler); Context.System.Scheduler.ScheduleTellOnce(Settings.TunningParameters.ShardStartTimeout, Self, new ResendShardHost(shard, region), Self, cancelable); _unAckedHostShards = _unAckedHostShards.SetItem(shard, cancelable); }
public void When_cancel_has_been_called_Should_be_cancelled() { var c = new Cancelable(Sys.Scheduler); c.Cancel(); c.IsCancellationRequested.ShouldBeTrue(); c.Token.IsCancellationRequested.ShouldBeTrue(); }
public PerformanceCounterActor(string seriesName, Func <PerformanceCounter> performanceCounterGenerator) { _seriesName = seriesName; _performanceCounterGenerator = performanceCounterGenerator; _subscriptions = new HashSet <IActorRef>(); _cancelable = new Cancelable(Context.System.Scheduler); }
public void CancelDiscover() { _discoveryCancelable?.Cancel(new GenericCallback((ex) => { // Do Nothing... })); _discoveryCancelable = null; _discoveredReaders.Clear(); }
/// <summary> /// Collect payment details /// </summary> public void RetreivePaymentIntent(string clientPaymentSecret, Action <string> onSuccess, Action <string> onFailure) { StripeTerminal.Instance.RetrievePaymentIntent(clientPaymentSecret, new PaymentIntentCallback((newIntent, retrievePaymentIntentException) => { if (retrievePaymentIntentException != null) { onFailure(retrievePaymentIntentException.ErrorMessage); } else { _cancelable = StripeTerminal.Instance.CollectPaymentMethod(newIntent, this, new PaymentIntentCallback((authorizedIntent, collectPaymentMethodException) => { if (collectPaymentMethodException != null) { _cancelable = null; onFailure(collectPaymentMethodException.ErrorMessage); } else { ReaderNotifyHandler("Authorizing Payment"); StripeTerminal.Instance.ProcessPayment(authorizedIntent, new PaymentIntentCallback((pendingCaptureIntent, processPaymentException) => { if (processPaymentException != null) { _cancelable = null; onFailure(processPaymentException.ErrorMessage); } else { if (pendingCaptureIntent != null && string.IsNullOrEmpty(pendingCaptureIntent.PaymentMethodId) == false && pendingCaptureIntent.Status == PaymentIntentStatus.RequiresCapture) { _cancelable = null; onSuccess(pendingCaptureIntent.PaymentMethodId); } else { var errorMessage = string.Empty; if (pendingCaptureIntent == null) { errorMessage = "No payment intent was found"; } else { errorMessage = "You payment is in an invalid state try the checkout process again: " + pendingCaptureIntent.Status.ToString(); } _cancelable = null; onFailure(errorMessage); } } })); } })); } })); }
public PerformanceCounterActor(string seriesName, Func <PerformanceCounter> performanceCounterGenerator) { this._seriesName = seriesName; this._performanceCounterGenerator = performanceCounterGenerator; this._cancelPublishing = new Cancelable(Context.System.Scheduler); this.Receive <GatherMetrics>(this.HandleGatherMetrics); this.Receive <SubscribeCounter>(this.HandleSubscribeCounter); this.Receive <UnsubscribeCounter>(this.HandleUnSubscribeCounter); }
public void When_ScheduleOnce_using_canceled_Cancelable_Then_their_actions_should_not_be_invoked() { // Prepare, set up actions to be fired IActionScheduler scheduler = new DedicatedThreadScheduler(Sys); var canceled = Cancelable.CreateCanceled(); scheduler.ScheduleOnce(0, () => TestActor.Tell("Test"), canceled); //Validate that no messages were sent ExpectNoMsg(100); }
public void Should_be_possible_to_call_CancelAfterTimespan() { var c = new Cancelable(Sys.Scheduler); var latch = CreateTestLatch(); c.Token.Register(() => latch.CountDown()); c.CancelAfter(TimeSpan.FromMilliseconds(50)); c.IsCancellationRequested.ShouldBeFalse(); latch.Ready(); c.IsCancellationRequested.ShouldBeTrue(); c.Token.IsCancellationRequested.ShouldBeTrue(); }
public void When_ScheduleRepeatedly_using_canceled_Cancelable_Then_their_actions_should_not_be_invoked() { // Prepare, set up actions to be fired IActionScheduler scheduler = new TaskBasedScheduler(); var canceled = Cancelable.CreateCanceled(); scheduler.ScheduleRepeatedly(0, 100, () => TestActor.Tell("Test1"), canceled); scheduler.ScheduleRepeatedly(50, 100, () => TestActor.Tell("Test2"), canceled); //Validate that no messages were sent ExpectNoMsg(150); }
public void When_ScheduleRepeatedly_and_then_canceling_before_they_occur_Then_their_actions_should_not_be_invoked() { // Prepare, set up actions to be fired IActionScheduler scheduler = new DedicatedThreadScheduler(Sys); var cancelable = new Cancelable(scheduler); scheduler.ScheduleRepeatedly(100, 2, () => TestActor.Tell("Test"), cancelable); cancelable.Cancel(); //Validate that no messages were sent ExpectNoMsg(150); }
public void When_ScheduleTellRepeatedly_and_then_canceling_before_they_occur_Then_their_actions_should_not_be_invoked() { // Prepare, set up actions to be fired IScheduler scheduler = new TaskBasedScheduler(); var cancelable = new Cancelable(scheduler); scheduler.ScheduleTellRepeatedly(100, 2, TestActor, "Test", ActorRefs.NoSender, cancelable); cancelable.Cancel(); //Validate that no messages were sent ExpectNoMsg(150); }
public void DiscoverReaders(StripeDiscoveryConfiguration config, Action <IList <StripeTerminalReader> > readers, Action scanTimeoutCallback) { _onReadersDiscoveredAction = readers; _discoveryCancelable?.Cancel(new GenericCallback((ex) => { // Do Nothing... })); _discoveryCancelable = StripeTerminal.Instance.DiscoverReaders(new DiscoveryConfiguration(config.TimeOut, DeviceType.Chipper2x, isSimulated: config.IsSimulated), this, new GenericCallback((ex) => { // Do Nothing... scanTimeoutCallback(); })); }
protected override void OnReceive(object message) { if (message is DoConnectCommand) { var cancelReconnect = new Cancelable(Context.System.Scheduler, TimeSpan.FromDays(1)); Context.System.Scheduler.ScheduleTellRepeatedly(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5), Context.System.Tcp(), new Tcp.Connect(_endpoint), Self, cancelReconnect); Become(Connecting(cancelReconnect)); } else { Unhandled(message); } }
public void When_ScheduleTellRepeatedly_using_canceled_Cancelable_Then_their_actions_should_not_be_invoked() { // Prepare, set up actions to be fired ITellScheduler scheduler = new TaskBasedScheduler(); var canceled = Cancelable.CreateCanceled(); scheduler.ScheduleTellRepeatedly(0, 2, TestActor, "Test", ActorRefs.NoSender, canceled); scheduler.ScheduleTellRepeatedly(1, 2, TestActor, "Test", ActorRefs.NoSender, canceled); //Validate that no messages were sent ExpectNoMsg(100); }
public void Given_a_canceled_Cancelable_with_callback_Then_Cancel_should_be_possible_to_call_again_but_callbacks_should_not_be_called_again() { var c = new Cancelable(Sys.Scheduler); var callbacks = new AtomicCounter(0); c.Token.Register(() => callbacks.IncrementAndGet()); c.Cancel(); c.Cancel(); //HACK: Using the fact that when Cancel is called, callbacks are executed synchronously callbacks.Current.ShouldBe(1); }
public void When_canceling_existing_running_repeaters_Then_their_future_actions_should_not_be_invoked() { // Prepare, set up actions to be fired IActionScheduler scheduler = new DedicatedThreadScheduler(Sys); var cancelable = new Cancelable(scheduler); scheduler.ScheduleRepeatedly(0, 150, () => TestActor.Tell("Test"), cancelable); ExpectMsg("Test"); cancelable.Cancel(); //Validate that no more messages were sent ExpectNoMsg(200); }
public void ScheduleTellRepeatedly_in_milliseconds_Tests(int initialDelay, int interval) { // Prepare, set up actions to be fired IScheduler scheduler = new HashedWheelTimerScheduler(Sys.Settings.Config, Log); try { var cancelable = new Cancelable(scheduler); var receiver = ActorOf(dsl => { //Receive three messages, and store the time when these were received //after three messages stop the actor and send the times to TestActor var messages = new List <DateTimeOffset>(); dsl.Receive <string>((s, context) => { messages.Add(context.System.Scheduler.Now); if (messages.Count == 3) { TestActor.Tell(messages); cancelable.Cancel(); context.Stop(context.Self); } }); }); scheduler.ScheduleTellRepeatedly(initialDelay, interval, receiver, "Test", ActorRefs.NoSender, cancelable); //Expect to get a list from receiver after it has received three messages var dateTimeOffsets = ExpectMsg <List <DateTimeOffset> >(); dateTimeOffsets.ShouldHaveCount(3); Action <int, int> validate = (a, b) => { var valA = dateTimeOffsets[a]; var valB = dateTimeOffsets[b]; var diffBetweenMessages = Math.Abs((valB - valA).TotalMilliseconds); var diffInMs = Math.Abs(diffBetweenMessages - interval); var deviate = (diffInMs / interval); deviate.Should(val => val < 0.1, string.Format( "Expected the interval between message {1} and {2} to deviate maximum 10% from {0}. It was {3} ms between the messages. It deviated {4}%", interval, a + 1, b + 1, diffBetweenMessages, deviate * 100)); }; validate(0, 1); validate(1, 2); } finally { scheduler.AsInstanceOf <IDisposable>().Dispose(); } }
public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target, Cancelable cancelable) { foreach (var dir in source.GetDirectories()) { CancelHelper.CheckThrowCancel(cancelable); CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name), cancelable); } foreach (var file in source.GetFiles()) { CancelHelper.CheckThrowCancel(cancelable); file.CopyTo(Path.Combine(target.FullName, file.Name)); } }
public static void Install( Cancelable cancelable) { if (IsInstalled) return; Directory.CreateDirectory(InstallationFolderPath); File.Copy( Assembly.GetEntryAssembly().Location, InstallationExeFilePath, true); ExplorerContextMenuAdder.Register(); }
public void When_canceling_existing_running_repeaters_Then_their_future_actions_should_not_be_invoked() { // Prepare, set up actions to be fired IScheduler scheduler = new TaskBasedScheduler(); var cancelable = new Cancelable(scheduler); scheduler.ScheduleTellRepeatedly(0, 150, TestActor, "Test", ActorRefs.NoSender, cancelable); ExpectMsg("Test"); cancelable.Cancel(); //Validate that no more messages were sent ExpectNoMsg(200); }
public static void Restore(string destinationFolderPath, Cancelable cancelable) { if (destinationFolderPath.StartsWith(Backuper.BackupStorageBaseFolderPath, StringComparison.InvariantCultureIgnoreCase)) { throw new Exception("Path must be outside of Simple Backup folder."); } var dst = new DirectoryInfo(destinationFolderPath); var src = new DirectoryInfo(Path.Combine(Backuper.BackupStorageBaseFolderPath, Backuper.MakeUnique(dst))); if (!src.Exists) throw new MessageBoxException("No backup available for this folder."); deleteDirectoryContents(dst, cancelable); Backuper.CopyFilesRecursively(src, dst, cancelable); }
public static void Backup(string sourceFolderPath, Cancelable cancelable) { if (sourceFolderPath.StartsWith(BackupStorageBaseFolderPath, StringComparison.InvariantCultureIgnoreCase)) { throw new Exception("Path must be outside of Simple Backup folder."); } var src = new DirectoryInfo(sourceFolderPath); var dst = new DirectoryInfo(Path.Combine(BackupStorageBaseFolderPath, MakeUnique(src))); if (dst.Exists) dst.Delete(true); dst.Create(); CopyFilesRecursively(src, dst, cancelable); }
public static void Uninstall(Cancelable cancelable) { ExplorerContextMenuAdder.Unregister(); // -- var baseFolderPath = Installer.InstallationFolderPath; if (!Directory.Exists(baseFolderPath)) { return; } foreach (var directory in Directory.GetDirectories(baseFolderPath)) { CancelHelper.CheckThrowCancel(cancelable); Directory.Delete(directory, true); } foreach (var file in Directory.GetFiles(baseFolderPath)) { if (!string.Equals(Installer.InstallationExeFilePath, file, StringComparison.InvariantCultureIgnoreCase)) { CancelHelper.CheckThrowCancel(cancelable); File.Delete(file); } } // -- try { File.Delete(Installer.InstallationExeFilePath); } catch (Exception) { postPoneDeleteFile(Installer.InstallationExeFilePath); } try { Directory.Delete(Installer.InstallationFolderPath); } catch (Exception) { postPoneDeleteFile(Installer.InstallationFolderPath); } }
public void Given_linked_Cancelable_When_canceling_underlying_Then_linked_should_be_canceled() { var underlying = new Cancelable(Sys.Scheduler); var linked = Cancelable.CreateLinkedCancelable(Sys.Scheduler, underlying); var latch = CreateTestLatch(); linked.Token.Register(() => latch.CountDown()); underlying.Cancel(); underlying.IsCancellationRequested.ShouldBeTrue(); underlying.Token.IsCancellationRequested.ShouldBeTrue(); latch.Ready(); linked.IsCancellationRequested.ShouldBeTrue(); linked.Token.IsCancellationRequested.ShouldBeTrue(); }
public void When_canceling_existing_running_repeaters_by_scheduling_the_cancellation_ahead_of_time_Then_their_future_actions_should_not_be_invoked() { // Prepare, set up actions to be fired IScheduler scheduler = new TaskBasedScheduler(); var cancelableOdd = new Cancelable(scheduler); scheduler.ScheduleTellRepeatedly(1, 150, TestActor, "Test", ActorRefs.NoSender, cancelableOdd); cancelableOdd.CancelAfter(50); //Expect one message ExpectMsg("Test"); //Validate that no messages were sent ExpectNoMsg(200); }
private static void deleteDirectoryContents(DirectoryInfo dir, Cancelable cancelable) { if (!dir.Exists) return; foreach (var directory in dir.GetDirectories()) { CancelHelper.CheckThrowCancel(cancelable); directory.Delete(true); } foreach (var file in dir.GetFiles()) { CancelHelper.CheckThrowCancel(cancelable); file.Delete(); } }
public void When_canceling_existing_running_repeaters_by_scheduling_the_cancellation_ahead_of_time_Then_their_future_actions_should_not_be_invoked() { // Prepare, set up actions to be fired IActionScheduler scheduler = new DedicatedThreadScheduler(Sys); var cancelableOdd = new Cancelable(scheduler); scheduler.ScheduleRepeatedly(1, 150, () => TestActor.Tell("Test"), cancelableOdd); cancelableOdd.CancelAfter(50); //Expect one message ExpectMsg("Test"); //Validate that no messages were sent ExpectNoMsg(200); }
/// <summary> /// Sends a message to the collection of routees. /// </summary> /// <param name="message">The message that is being sent.</param> /// <param name="sender">The actor sending the message.</param> public override void Send(object message, IActorRef sender) { _routees.Shuffle(); var routeeIndex = new AtomicCounter(0); var completion = new TaskCompletionSource <object>(); var cancelable = new Cancelable(_scheduler); completion.Task .ContinueWith(task => cancelable.Cancel(false)); if (_routees.Length == 0) { completion.TrySetResult(NoRoutee); } else { _scheduler.Advanced.ScheduleRepeatedly(TimeSpan.Zero, _interval, async() => { var currentIndex = routeeIndex.GetAndIncrement(); if (currentIndex >= _routees.Length) { return; } try { completion.TrySetResult( await(_routees[currentIndex].Ask(message, _within)).ConfigureAwait(false)); } catch (AskTimeoutException) { completion.TrySetResult( new Status.Failure( new AskTimeoutException($"Ask timed out on {sender} after {_within}"))); } catch (TaskCanceledException) { completion.TrySetResult( new Status.Failure( new AskTimeoutException($"Ask timed out on {sender} after {_within}"))); } }, cancelable); } completion.Task.PipeTo(sender); }
public static void Install( Cancelable cancelable) { if (IsInstalled) { return; } Directory.CreateDirectory(InstallationFolderPath); File.Copy( Assembly.GetEntryAssembly().Location, InstallationExeFilePath, true); ExplorerContextMenuAdder.Register(); }
public PendingSpellCastData Create([NotNull] PendingSpellCastCreationContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } ICancelable pendingSpellCastCancelable = new Cancelable(ActorScheduler); SpellDefinitionDataModel definition = SpellDataCollection.GetSpellDefinition(context.SpellId); //We need to compute a timespan for the pending cast from the definition casting time. TimeSpan castTimeSpan = definition.CastTime == 0 ? TimeSpan.Zero : TimeSpan.FromMilliseconds(definition.CastTime); long startCastTime = TimeService.CurrentLocalTime; long expectedFinishTime = startCastTime + castTimeSpan.Ticks; return(new PendingSpellCastData(startCastTime, expectedFinishTime, context.SpellId, pendingSpellCastCancelable, castTimeSpan, context.CurrentTarget)); }
public static void Uninstall(Cancelable cancelable) { ExplorerContextMenuAdder.Unregister(); // -- var baseFolderPath = Installer.InstallationFolderPath; if (!Directory.Exists(baseFolderPath)) return; foreach (var directory in Directory.GetDirectories(baseFolderPath)) { CancelHelper.CheckThrowCancel(cancelable); Directory.Delete(directory, true); } foreach (var file in Directory.GetFiles(baseFolderPath)) { if (!string.Equals(Installer.InstallationExeFilePath, file, StringComparison.InvariantCultureIgnoreCase)) { CancelHelper.CheckThrowCancel(cancelable); File.Delete(file); } } // -- try { File.Delete(Installer.InstallationExeFilePath); } catch (Exception) { postPoneDeleteFile(Installer.InstallationExeFilePath); } try { Directory.Delete(Installer.InstallationFolderPath); } catch (Exception) { postPoneDeleteFile(Installer.InstallationFolderPath); } }
/// <summary> /// Compress multiple items with the ZIP algorithm. /// </summary> /// <param name="infos">The items to compress.</param> /// <returns>Returns the compressed items.</returns> private static byte[] CompressHeterogenous( CompressHeterogenousInfos infos, ICancelableProgress progress1, Cancelable progress2 ) { if ( infos == null || infos.InternalItems == null || infos.InternalItems.Count <= 0 ) { return null; } else { using ( MemoryStream buf = new MemoryStream() ) using ( ZipOutputStream zip = new ZipOutputStream( buf ) ) { Crc32 crc = new Crc32(); zip.SetLevel( 9 ); // 0..9. int index = 1; foreach ( CompressHeterogenousInfo info in infos.InternalItems ) { // Cancel, if requested. if ( progress1 != null ) { if ( progress1.OnProgress( null, EventArgs.Empty ) == CancelMode.Cancel ) { return null; } } // Cancel, if requested. if ( progress2 != null ) { if ( progress2() == CancelMode.Cancel ) { return null; } } byte[] buffer = null; string fileName = null; bool putEntry; switch ( info.Type ) { case CompressHeterogenousInfo.InfoType.String: fileName = info.FilePath; if ( fileName == null || fileName.Length <= 0 ) { fileName = string.Format( @"file{0}.bin", index ); } buffer = Encoding.UTF8.GetBytes( info.Content ); putEntry = true; break; case CompressHeterogenousInfo.InfoType.File: using ( FileStream fs = new FileStream( info.FilePath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) using ( BinaryReader r = new BinaryReader( fs ) ) { buffer = new byte[fs.Length]; fs.Read( buffer, 0, buffer.Length ); fileName = Path.GetFileName( info.FilePath ); } putEntry = false; break; case CompressHeterogenousInfo.InfoType.Bytes: fileName = info.FilePath; if ( fileName == null || fileName.Length <= 0 ) { fileName = string.Format( @"file{0}.bin", index ); } buffer = info.Bytes; putEntry = true; break; default: Debug.Assert( false, string.Format( @"Unknown compression info type '{0}'.", info.Type ) ); putEntry = false; break; } // -- if ( putEntry ) { ZipEntry entry = new ZipEntry( fileName ); entry.DateTime = DateTime.Now; entry.Size = buffer.Length; crc.Reset(); crc.Update( buffer ); entry.Crc = crc.Value; zip.PutNextEntry( entry ); zip.Write( buffer, 0, buffer.Length ); } index++; } zip.Finish(); // -- byte[] c = new byte[buf.Length]; buf.Seek( 0, SeekOrigin.Begin ); buf.Read( c, 0, c.Length ); // -- zip.Close(); return c; } } }
/// <summary> /// Compress multiple items with the ZIP algorithm. /// </summary> /// <param name="infos">The items to compress.</param> /// <param name="progress">The progress.</param> /// <returns>Returns the compressed items.</returns> public static byte[] CompressHeterogenous( CompressHeterogenousInfos infos, Cancelable progress ) { return CompressHeterogenous( infos, null, progress ); }
/// <summary> /// Compress multiple items with the ZIP algorithm. /// </summary> /// <param name="infos">The items to compress.</param> /// <param name="progress1">The progress1.</param> /// <param name="progress2">The progress2.</param> /// <returns>Returns the compressed items.</returns> private static byte[] CompressHeterogenous( CompressHeterogenousInfos infos, ICancelableProgress progress1, Cancelable progress2 ) { using ( MemoryStream destinationStream = new MemoryStream() ) { Stream realStream = CompressHeterogenousToStream( infos, progress1, progress2, destinationStream ); if ( realStream == null ) { return null; } else { using ( realStream ) { byte[] c = new byte[destinationStream.Length]; destinationStream.Seek( 0, SeekOrigin.Begin ); destinationStream.Read( c, 0, c.Length ); return c; } } } }
/// <summary> /// Compress multiple items with the ZIP algorithm. /// </summary> /// <param name="infos">The items to compress.</param> /// <param name="progress">The progress.</param> /// <param name="destinationFilePath">The destination file path.</param> public static void CompressHeterogenousToFile( CompressHeterogenousInfos infos, Cancelable progress, FileInfo destinationFilePath ) { CompressHeterogenousToFile( infos, null, progress, destinationFilePath ); }
/// <summary> /// Compress multiple items with the ZIP algorithm. /// </summary> /// <param name="infos">The items to compress.</param> /// <param name="progress1">The progress1.</param> /// <param name="progress2">The progress2.</param> /// <param name="destinationFilePath">The destination file path.</param> private static void CompressHeterogenousToFile( CompressHeterogenousInfos infos, ICancelableProgress progress1, Cancelable progress2, FileInfo destinationFilePath ) { if ( destinationFilePath.Exists ) { destinationFilePath.Delete(); } using ( FileStream destinationStream = new FileStream( destinationFilePath.FullName, FileMode.OpenOrCreate, FileAccess.ReadWrite ) ) { Stream realStream = CompressHeterogenousToStream( infos, progress1, progress2, destinationStream ); if ( realStream != null ) { realStream.Dispose(); } } }
/// <summary> /// Compress multiple items with the ZIP algorithm. /// </summary> /// <param name="infos">The items to compress.</param> /// <param name="progress1">The progress1.</param> /// <param name="progress2">The progress2.</param> /// <param name="destinationStream">The destination stream.</param> /// <returns></returns> private static Stream CompressHeterogenousToStream( CompressHeterogenousInfos infos, ICancelableProgress progress1, Cancelable progress2, Stream destinationStream ) { if ( infos == null || infos.InternalItems == null || infos.InternalItems.Count <= 0 ) { return null; } else { // No "using" block. ZipOutputStream zip = new ZipOutputStream( destinationStream ); Crc32 crc = new Crc32(); zip.SetLevel( 9 ); // 0..9. int index = 1; foreach ( CompressHeterogenousInfo info in infos.InternalItems ) { // Cancel, if requested. if ( progress1 != null ) { if ( progress1.OnProgress( null, EventArgs.Empty ) == CancelMode.Cancel ) { return null; } } // Cancel, if requested. if ( progress2 != null ) { if ( progress2( info ) == CancelMode.Cancel ) { return null; } } // -- byte[] buffer = null; string fileName = null; bool putEntry; switch ( info.Type ) { case CompressHeterogenousInfo.InfoType.String: fileName = info.FilePath; if ( fileName == null || fileName.Length <= 0 ) { fileName = string.Format( @"file{0}.bin", index ); } buffer = Encoding.UTF8.GetBytes( info.Content ); putEntry = true; break; case CompressHeterogenousInfo.InfoType.File: fileName = Path.GetFileName( info.FilePath ); ZipEntry entry = new ZipEntry( fileName ); zip.PutNextEntry( entry ); using ( FileStream fs = new FileStream( info.FilePath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) using ( BinaryReader r = new BinaryReader( fs ) ) { byte[] smallBuffer = new byte[16384]; int bytesRead; do { bytesRead = r.Read( smallBuffer, 0, smallBuffer.Length ); zip.Write( smallBuffer, 0, bytesRead ); // -- // Cancel, if requested. if ( progress1 != null ) { if ( progress1.OnProgress( null, EventArgs.Empty ) == CancelMode.Cancel ) { return null; } } // Cancel, if requested. if ( progress2 != null ) { if ( progress2( info ) == CancelMode.Cancel ) { return null; } } } while ( bytesRead > 0 ); } putEntry = false; break; case CompressHeterogenousInfo.InfoType.Bytes: fileName = info.FilePath; if ( fileName == null || fileName.Length <= 0 ) { fileName = string.Format( @"file{0}.bin", index ); } buffer = info.Bytes; putEntry = true; break; default: Debug.Assert( false, string.Format( @"Unknown compression info type '{0}'.", info.Type ) ); putEntry = false; break; } // -- if ( putEntry ) { ZipEntry entry = new ZipEntry( fileName ); entry.DateTime = DateTime.Now; entry.Size = buffer.Length; crc.Reset(); crc.Update( buffer ); entry.Crc = crc.Value; zip.PutNextEntry( entry ); zip.Write( buffer, 0, buffer.Length ); } index++; } zip.Finish(); return zip; } }