public void Test_DisposeContainedResources() { var disposable = new Disposable(); var pool = new Pool<Disposable>(() => disposable, AccessStrategy.LIFO, LoadingStrategy.Eager, 1); pool.Dispose(); Assert.True(disposable.Disposed); }
bool UsingTest () { dynamic d = new Disposable (); try { using (d) { d.VV (); } } catch { } if (Disposable.Counter != 1) return false; try { using (dynamic u = new Disposable ()) { u.VV (); } } catch { } if (Disposable.Counter != 2) return false; using (dynamic u = new Disposable ()) { u.Test (); } return true; }
/// <summary> /// Internal contructor /// </summary> /// <param name="saveOnCompletion"></param> internal UnitOfWork(bool saveOnCompletion = false) { StartingPoint = new StackTrace(2); SaveOnCompletion = saveOnCompletion; Disposable = new Disposable<UnitOfWork>(this); //All the logic is within the generic Disposable }
public static void FunWithDisposable() { var d = new Disposable(); using (d) { #pragma warning disable 0728 d = null; #pragma warning restore 0728 } }
public Node(Context WorldInputContext, Disposable<Content> Content, Block Block, Point Position, Point Velocity) { this._Content = Content; this._Block = Block; this._Position = Position; this._Velocity = Velocity; this._Layout = this._Block.Object.CreateLayout(null, SizeRange, out this._Size); this._InputContext = new _NodeInputContext(this, WorldInputContext); this._Layout.Link(this._InputContext); }
public Node(Context WorldInputContext, Disposable<Content> Content, Block Block, Layout Layout, Point Size, Point Position, Point Velocity) { this._Content = Content; this._Block = Block; this._Position = Position; this._Velocity = Velocity; this._Layout = Layout; this._Size = Size; this._InputContext = new _NodeInputContext(this, WorldInputContext); this._Layout.Link(this._InputContext); }
public void DisposesAllDisposableInstances() { var isDisposed = false; var disposable = new Disposable(); disposable.Disposed += (sender, e) => isDisposed = true; var serviceLocator = new ServiceLocator(); serviceLocator.RegisterInstance(typeof(Disposable), disposable); serviceLocator.Dispose(); Assert.IsTrue(isDisposed); }
/// <summary> /// Publishes an ASP.NET 4.x project to the given GCE <seealso cref="Instance"/>. /// </summary> /// <param name="projectPath">The full path to the project file.</param> /// <param name="targetInstance">The instance to deploy.</param> /// <param name="credentials">The Windows credentials to use to deploy to the <paramref name="targetInstance"/>.</param> /// <param name="progress">The progress indicator.</param> /// <param name="outputAction">The action to call with lines of output.</param> /// <returns></returns> public static async Task<bool> PublishProjectAsync( string projectPath, Instance targetInstance, WindowsInstanceCredentials credentials, IProgress<double> progress, Action<string> outputAction) { var stagingDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(stagingDirectory); progress.Report(0.1); var publishSettingsPath = Path.GetTempFileName(); var publishSettingsContent = targetInstance.GeneratePublishSettings(credentials.User, credentials.Password); File.WriteAllText(publishSettingsPath, publishSettingsContent); using (var cleanup = new Disposable(() => Cleanup(publishSettingsPath, stagingDirectory))) { // Wait for the bundle operation to finish and update the progress in the mean time to show progress. if (!await ProgressHelper.UpdateProgress( CreateAppBundleAsync(projectPath, stagingDirectory, outputAction), progress, from: 0.1, to: 0.5)) { return false; } progress.Report(0.6); // Update for the deploy operation to finish and update the progress as it goes. if (!await ProgressHelper.UpdateProgress( DeployAppAsync(stagingDirectory, publishSettingsPath, outputAction), progress, from: 0.6, to: 0.9)) { return false; } progress.Report(1); } return true; }
ISymbolReader GetSymbolReader(ModuleDefinition module, Disposable <Stream> symbolStream, string fileName) { return(new PortablePdbReader(ImageReader.ReadPortablePdb(symbolStream, fileName), module)); }
partial void RegisterEvents() { _clickSubscription.Disposable = null; if (Window == null) { // Will be invoked again when this control will be attached loaded. return; } if (!(GetContentElement() is UIControl uiControl)) { // Button is using Windows template, no native events to register to return; } if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)) { this.Log().Debug("ControlTemplateRoot is a UIControl, hooking on to AllTouchEvents and TouchUpInside"); } void pressHandler(object e, EventArgs s) { if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)) { this.Log().Debug("AllTouchEvents, trigger OnPointerPressed"); } OnPointerPressed(new PointerRoutedEventArgs(this)); } void clickHandler(object e, EventArgs s) { if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)) { this.Log().Debug("TouchUpInside, executing command"); } OnClick(); RaiseEvent(TappedEvent, new TappedRoutedEventArgs { OriginalSource = this }); } // // Bind the enabled handler // void enabledHandler(object e, DependencyPropertyChangedEventArgs s) { uiControl.Enabled = IsEnabled; } uiControl.AllTouchEvents += pressHandler; uiControl.TouchUpInside += clickHandler; IsEnabledChanged += enabledHandler; void unregister() { uiControl.AllTouchEvents -= pressHandler; uiControl.TouchUpInside -= clickHandler; IsEnabledChanged -= enabledHandler; } _clickSubscription.Disposable = Disposable.Create(unregister); }
public static IDisposable RegisterCallbackForPinValueChangedEventAsDisposable(this IGpioController controller, int pinNumber, PinEventTypes eventTypes, PinChangeEventHandler callback) { controller.RegisterCallbackForPinValueChangedEvent(pinNumber, eventTypes, callback); return(Disposable.Create(() => controller.UnregisterCallbackForPinValueChangedEvent(pinNumber, callback))); }
public static void Scenario() { var disposable0 = default(Disposable); "Given a disposable" .Given(() => disposable0 = new Disposable().Using()); "When using the disposable" .When(() => disposable0.Use()); "Then something" .Then(() => { }) .InIsolation(); "And something" .Then(() => { }); }
public RequestContext(Disposable<RemoteConnection> disposable) { _disposable = disposable; }
private void SettingWindow_OnLoaded(object sender, RoutedEventArgs e) { _settingViewModel = new SettingViewModel(); Disposable.Add(_settingViewModel); DataContext = _settingViewModel; }
public static void Scenario( Disposable disposable0, Disposable disposable1, Disposable disposable2) { "Given some disposables" .f(async c => { await Task.Yield(); disposable0 = new Disposable(1).Using(c); disposable1 = new Disposable(2).Using(c); disposable2 = new Disposable(3).Using(c); }); "When using the disposables" .f(() => { disposable0.Use(); disposable1.Use(); disposable2.Use(); }); }
public RequestContext GetContext() { var tcpClient = _pool.AquireResource(); var disposable = new Disposable<RemoteConnection>(tcpClient, () => _pool.Release(tcpClient)); return new RequestContext(disposable); }
private static void Main(string[] args) { if (args.Length == 0) { PrintUsage(); return; } var projects = new List <string>(); var properties = new Dictionary <string, string>(); foreach (var arg in args) { if (arg.StartsWith("/out:")) { Paths.SolutionDestinationFolder = Path.GetFullPath(arg.Substring("/out:".Length).StripQuotes()); continue; } if (arg.StartsWith("/in:")) { string inputPath = arg.Substring("/in:".Length).StripQuotes(); try { if (!File.Exists(inputPath)) { continue; } string[] paths = File.ReadAllLines(inputPath); foreach (string path in paths) { AddProject(projects, path); } } catch { Log.Write("Invalid argument: " + arg, ConsoleColor.Red); } continue; } if (arg.StartsWith("/p:")) { var match = Regex.Match(arg, "/p:(?<name>[^=]+)=(?<value>.+)"); if (match.Success) { var propertyName = match.Groups["name"].Value; var propertyValue = match.Groups["value"].Value; properties.Add(propertyName, propertyValue); continue; } } try { AddProject(projects, arg); } catch (Exception ex) { Log.Write("Exception: " + ex.ToString(), ConsoleColor.Red); } } if (projects.Count == 0) { PrintUsage(); return; } AssertTraceListener.Register(); AppDomain.CurrentDomain.FirstChanceException += FirstChanceExceptionHandler.HandleFirstChanceException; if (Paths.SolutionDestinationFolder == null) { Paths.SolutionDestinationFolder = Path.Combine(Microsoft.SourceBrowser.Common.Paths.BaseAppFolder, "Index"); } Log.ErrorLogFilePath = Path.Combine(Paths.SolutionDestinationFolder, Log.ErrorLogFile); Log.MessageLogFilePath = Path.Combine(Paths.SolutionDestinationFolder, Log.MessageLogFile); // Warning, this will delete and recreate your destination folder Paths.PrepareDestinationFolder(); using (Disposable.Timing("Generating website")) { IndexSolutions(projects, properties); FinalizeProjects(); } }
public void UsingArray() { var a = new Disposable[] {}; }
public Disposable ReturnLocalDisposable() { var instance = new Disposable(); instance.DoSomething(); return instance; }
public static void MethodWithDisposableVariable() { var disposable = new Disposable(); disposable.Method(); }
protected override void OnDragLeave(EventArgs e) { if (!this._DragContent.IsNull) { this._DragContent.Dispose(); this._DragContent = null; } }
protected override void OnDragEnter(DragEventArgs e) { this._DragContent = Content.Import(Transfer.Item.FromDataObject(e.Data)); if (this._DragContent.IsNull) { e.Effect = DragDropEffects.None; } else { e.Effect = DragDropEffects.Copy; } }
/// <summary> /// When this method is called, an object will not fire change /// notifications (neither traditional nor Observable notifications) /// until the return value is disposed. /// </summary> /// <returns>An object that, when disposed, reenables change /// notifications.</returns> public IDisposable SuppressChangeNotifications() { Interlocked.Increment(ref changeNotificationsSuppressed); return(Disposable.Create(() => Interlocked.Decrement(ref changeNotificationsSuppressed))); }
public void OnCompleted() { Disposable.TryDispose(ref _parent._secondDisposable); }
public static void Add(this CompositeDisposable c, Action action) { c.Add(Disposable.Create(action)); }
public MenuItems(ILogger logger, IObjectProvider objectProvider) { _logger = logger; _objectProvider = objectProvider; _menu = new List <MenuItem> { new MenuItem("Live Trades", "A basic example, illustrating how to connect to a stream, inject a user filter and bind.", () => Open <LiveTradesViewer>("Live Trades"), new [] { new Link("Service", "TradeService.cs", "https://github.com/RolandPheasant/TradingDemo/blob/master/Trader.Domain/Services/TradeService.cs"), new Link("View Model", "LiveTradesViewer.cs", "https://github.com/RolandPheasant/TradingDemo/blob/master/Trader.App/Views/LiveTradesViewer.cs "), new Link("Blog", "Ui Integration", "https://dynamicdataproject.wordpress.com/2014/11/24/trading-example-part-3-integrate-with-ui/"), }), new MenuItem("Live Trades (RxUI)", "A basic example, illustrating where reactive-ui and dynamic data can work together", () => Open <RxUiViewer>("Reactive UI Example"), new [] { new Link("View Model", "RxUiViewer.cs", "https://github.com/RolandPheasant/TradingDemo/blob/master/Trader.App/Views/RxUiViewer.cs "), new Link("Blog", "Integration with reactive ui", "https://dynamicdataproject.wordpress.com/2015/01/18/integration-with-reactiveui/"), }), new MenuItem("Near to Market", "Dynamic filtering of calculated values.", () => Open <NearToMarketViewer>("Near to Market"), new [] { new Link("Service", "NearToMarketService.cs", "https://github.com/RolandPheasant/TradingDemo/blob/master/Trader.Domain/Services/NearToMarketService.cs"), new Link("Rates Updater", "TradePriceUpdateJob.cs", "https://github.com/RolandPheasant/TradingDemo/blob/master/Trader.Domain/Services/TradePriceUpdateJob.cs"), new Link("View Model", "NearToMarketViewer.cs", "https://github.com/RolandPheasant/TradingDemo/blob/master/Trader.App/Views/NearToMarketViewer.cs"), new Link("Blog i", "Manage Market Data", "https://dynamicdataproject.wordpress.com/2014/11/22/trading-example-part-2-manage-market-data/"), new Link("Blog ii", "Filter on calculated values", "https://dynamicdataproject.wordpress.com/2014/12/21/trading-example-part-4-filter-on-calculated-values/"), }), new MenuItem("Trades By %", "Group trades by a constantly changing calculated value. With automatic regrouping.", () => Open <TradesByPercentViewer>("Trades By % Diff"), new [] { new Link("View Model", "TradesByPercentViewer.cs", "https://github.com/RolandPheasant/TradingDemo/blob/master/Trader.App/Views/TradesByPercentViewer.cs"), new Link("Group Model", "TradesByPercentDiff.cs", "https://github.com/RolandPheasant/TradingDemo/blob/master/Trader.Domain/Model/TradesByPercentDiff.cs"), }), new MenuItem("Trades By hh:mm", "Group items by time with automatic regrouping as time passes", () => Open <TradesByTimeViewer>("Trades By hh:mm"), new [] { new Link("View Model", "TradesByTimeViewer.cs", "https://github.com/RolandPheasant/TradingDemo/blob/master/Trader.App/Views/TradesByTimeViewer.cs"), new Link("Group Model", "TradesByTime.cs", "https://github.com/RolandPheasant/TradingDemo/blob/master/Trader.Domain/Model/TradesByTime.cs"), }), new MenuItem("Recent Trades", "Operator which only includes trades which have changed in the last minute.", () => Open <RecentTradesViewer>("Recent Trades"), new [] { new Link("View Model", "RecentTradesViewer.cs", "https://github.com/RolandPheasant/TradingDemo/blob/master/Trader.App/Views/RecentTradesViewer.cs"), }), }; _cleanUp = Disposable.Create(() => _viewCreatedSubject.OnCompleted()); }
void TryDispose( Disposable sut ) { Assert.False( sut.Disposed ); sut.TryDispose(); Assert.True( sut.Disposed ); }
public void Dispose() { Disposable.Dispose(ref _disposable); }
public void Run() { var disposable = new Disposable(); disposable.Dispose(); Assert.IsTrue(DisposeTracker.HasDisposedBeenCalled); }
public void OnNext(IDisposable value) { Disposable.SetSingle(ref _disposable, value); }
public static void Scenario( Disposable disposable0, Disposable disposable1, Disposable disposable2) { "Given a disposable" .f(c => disposable0 = new Disposable(1).Using(c)); "And another disposable" .f(c => disposable1 = new Disposable(2).Using(c)); "And another disposable" .f(c => disposable2 = new Disposable(3).Using(c)); "When using the disposables" .f(() => { disposable0.Use(); disposable1.Use(); disposable2.Use(); }); "Then something happens" .f(() => 1.Should().Be(0)); }
protected override IDisposable SubscribeCore(IObserver <TSource> observer) { var a = _subscribe(observer); return(a != null?Disposable.Create(a) : Disposable.Empty); }
protected override void OnDragDrop(DragEventArgs e) { if (!this._DragContent.IsNull) { this.TopLevelControl.Focus(); this._World.Spawn(this._DragContent, this._Project(this.PointToClient(new SPoint(e.X, e.Y)))); this._DragContent = null; } }
protected NeuronViewModelBase(IAvatarViewer host, Node <Neuron, int> node, SourceCache <Neuron, int> cache, NeuronViewModelBase parent = null, INeuronApplicationService neuronApplicationService = null, INeuronQueryService neuronQueryService = null, ITerminalApplicationService terminalApplicationService = null, IExtendedSelectionService selectionService = null, IExtendedSelectionService highlightService = null, IStatusService statusService = null, IDialogService dialogService = null) { this.host = host; this.Id = node.Key; this.Parent = parent; this.SetNeuron(node.Item); this.ReloadCommand = ReactiveCommand.Create(async() => await this.OnReload(cache)); this.ReloadExpandCommand = ReactiveCommand.Create(async() => { await this.OnReload(cache); this.IsExpanded = true; }); this.AddPostsynapticCommand = ReactiveCommand.Create <object>(async(parameter) => await this.OnAddPostsynaptic(cache, parameter)); this.AddPresynapticCommand = ReactiveCommand.Create <object>(async(parameter) => await this.OnAddPresynaptic(cache, parameter)); this.DeleteCommand = ReactiveCommand.Create <object>(async(parameter) => await this.OnDeleteClicked(cache, parameter)); this.neuronApplicationService = neuronApplicationService ?? Locator.Current.GetService <INeuronApplicationService>(); this.neuronQueryService = neuronQueryService ?? Locator.Current.GetService <INeuronQueryService>(); this.terminalApplicationService = terminalApplicationService ?? Locator.Current.GetService <ITerminalApplicationService>(); this.selectionService = selectionService ?? Locator.Current.GetService <IExtendedSelectionService>(SelectionContract.Select.ToString()); this.highlightService = highlightService ?? Locator.Current.GetService <IExtendedSelectionService>(SelectionContract.Highlight.ToString()); this.statusService = statusService ?? Locator.Current.GetService <IStatusService>(); this.dialogService = dialogService ?? Locator.Current.GetService <IDialogService>(); var childrenLoader = new Lazy <IDisposable>(() => node.Children.Connect() .Transform(e => e.Item.Type == RelativeType.Postsynaptic ? (NeuronViewModelBase)(new PostsynapticViewModel(this.host, e.Item.Tag, e, cache, this)) : (NeuronViewModelBase)(new PresynapticViewModel(this.host, e.Item.Tag, e, cache, this))) .Bind(out this.children) .DisposeMany() .Subscribe() ); var shouldExpand = node.IsRoot ? Observable.Return(true) : Parent.Value.WhenValueChanged(t => t.IsExpanded); var expander = shouldExpand .Where(isExpanded => isExpanded) .Take(1) .Subscribe(_ => { var x = childrenLoader.Value; }); var childrenCount = node.Children.CountChanged .Select(count => { if (count == 0) { return("0 Synapses"); } else { return($"{node.Children.Items.Count(n => n.Item.Type == RelativeType.Postsynaptic)} Postsynaptic; " + $"{node.Children.Items.Count(n => n.Item.Type == RelativeType.Presynaptic)} Presynaptic"); } }) .Subscribe(text => this.ChildrenCountText = text); var changeTag = this.WhenPropertyChanged(p => p.Tag, false) .Subscribe(async(x) => await this.OnNeuronTagChanged(cache, x)); var selector = this.WhenPropertyChanged(p => p.IsSelected) .Where(p => p.Value) .Subscribe(x => { this.selectionService.SetSelectedComponents(new object[] { x.Sender }); this.host.Target = NeuronViewModelBase.ConvertNeuronViewModelToEditorNeuron((NeuronViewModelBase)x.Sender); }); var highlighter = this.highlightService.WhenPropertyChanged(a => a.SelectedComponents) .Subscribe(p => { if (p.Sender.SelectedComponents != null) { var selection = p.Sender.SelectedComponents.OfType <object>().ToArray(); if (selection.Count() > 0 && selection[0] is string) { if (selection.Count() < 2) { this.IsHighlighted = this.NeuronId == p.Sender.PrimarySelection.ToString(); } else { this.IsHighlighted = this.NeuronId == p.Sender.PrimarySelection.ToString() && this.TerminalId == selection[1].ToString(); } } } } ); this.cleanUp = Disposable.Create(() => { expander.Dispose(); childrenCount.Dispose(); if (childrenLoader.IsValueCreated) { childrenLoader.Value.Dispose(); } changeTag.Dispose(); selector.Dispose(); highlighter.Dispose(); }); }
private IEnumerable <IDisposable> Binding() { yield return (ViewModel.PlanCertificateFilterViewModel.WhenAny(x => x.IsBusy, x => x.Value) .Subscribe(isBusy => Root.IsEnabled = !isBusy)); yield return (this.OneWayBind( ViewModel, vm => vm.PlanCertificateFilterViewModel.IsBusy, v => v.BusyIndicator.IsActive)); yield return (this.Bind( this.ViewModel, vm => vm.SelectedPlanCertificate, v => v.DtGridPlanCertificate.SelectedValue)); yield return (this.OneWayBind( this.ViewModel, vm => vm.PlanCertificateFilterViewModel.Result, v => v.DtGridPlanCertificate.ItemsSource)); yield return (this.BindCommand( this.ViewModel, vm => vm.PreparingEditablePlanCertificateCommand, v => v._editRowMenuItem)); yield return (this.BindCommand(this.ViewModel, vm => vm.PreparingCopyPlanCertificateCommand, v => v._copyRowMenuItem)); yield return (this.BindCommand( this.ViewModel, vm => vm.PreparingAddingPlanCertificateCommand, v => v._insertRowMenuItem)); yield return (this.BindCommand(this.ViewModel, vm => vm.PreparingAddingPlanCertificateCommand, v => v._insertMenuItem)); yield return (this.BindCommand( this.ViewModel, vm => vm.PreparingEditablePersonalAccountCommand, v => v._personalAccountEditRowMenuItem)); yield return (this.BindCommand( this.ViewModel, vm => vm.PreparingAddingPersonalAccountCommand, v => v._personalAccountInsertRowMenuItem)); yield return (this.BindCommand( this.ViewModel, vm => vm.PreparingAddingPersonalAccountCommand, v => v._personalAccountInsertMenuItem)); yield return (this.BindCommand( this.ViewModel, vm => vm.PreparingRemovingPlanCertificateCommand, v => v._removeRowMenuItem)); yield return (this.BindCommand( this.ViewModel, vm => vm.PreparingRemovingPersonalAccountCommand, v => v._personalAccountRemoveRowMenuItem)); yield return (ViewModel.WhenAny(vm => vm.PlanCertificateFilterViewModel.Result, x => x.Value) .Where(x => x != null) .Subscribe(x => TxbRowsCount.Text = x.Count.ToString(CultureInfo.InvariantCulture))); yield return (Observable.FromEventPattern <SelectionChangedEventHandler, SelectionChangedEventArgs>( h => this.DtGridPlanCertificate.SelectionChanged += h, h => this.DtGridPlanCertificate.SelectionChanged -= h).Subscribe( _ => { TxbSelectedRowsCount.Text = this.DtGridPlanCertificate.SelectedItems.Count.ToString( CultureInfo.InvariantCulture); TxbSumCountByDocumentSelectedRows.Text = (from PlanCertificateLiteDto elem in this.DtGridPlanCertificate.SelectedItems select elem.CountByDocument into countByDocument where countByDocument != null select countByDocument).Sum().ToString(); TxbSumCountFactSelectedRows.Text = (from PlanCertificateLiteDto elem in this.DtGridPlanCertificate.SelectedItems select elem.CountFact into countFact select countFact).Sum() .ToString(CultureInfo.InvariantCulture); TxbSumSelectedPriseCount.Text = (from PlanCertificateLiteDto elem in this.DtGridPlanCertificate.SelectedItems where elem.SumWithTaxDocumenta != null select elem.SumWithTaxDocumenta).Sum().ToString(); })); yield return (this.BindCommand( this.ViewModel, vm => vm.PreparingEditablePlanCertificateCommand, v => v.DtGridPlanCertificate, "MouseDoubleClick")); _personalAccountStatusRowMenuItem.SetBinding( MenuItem.CommandProperty, new Binding(ViewModel.GetName(x => x.PreparingForStatusPersonalAccountCommand)) { Source = ViewModel }); _changeStatusCertificate.SetBinding( MenuItem.CommandProperty, new Binding(ViewModel.GetName(x => x.PreparingForStatusPlanCertificateCommand)) { Source = ViewModel }); _changeStatusCertificate.SetBinding( MenuItem.CommandParameterProperty, new Binding(DtGridPlanCertificate.GetName(x => x.SelectedItems)) { Source = DtGridPlanCertificate, Converter = new SelectedItemsConverter <PlanCertificateLiteDto>() }); yield return(Disposable.Create(() => BindingOperations.ClearAllBindings(_changeStatusCertificate))); }
public void Run(Absolute parent) { SetUpstream(parent._scheduler.ScheduleAction(this, parent._dueTime, @this => @this.Timeout())); Disposable.TrySetSingle(ref _serialDisposable, parent._source.SubscribeSafe(this)); }
public static IDisposable OpenPinAsDisposable(this IGpioController controller, int pinNumber) { controller.OpenPin(pinNumber); return(Disposable.Create(() => controller.ClosePin(pinNumber))); }
public void Run(Timeout <TSource, TTimeout> parent) { SetTimer(parent._firstTimeout, 0L); Disposable.TrySetSingle(ref _sourceDisposable, parent._source.SubscribeSafe(this)); }
/// <summary> /// Begins an auto-resize operation. /// </summary> /// <returns>A disposable used to finish the operation.</returns> /// <remarks> /// When an auto-resize operation is in progress any resize events received will not be /// cause the new size to be written to the <see cref="Layoutable.Width"/> and /// <see cref="Layoutable.Height"/> properties. /// </remarks> protected IDisposable BeginAutoSizing() { AutoSizing = true; return(Disposable.Create(() => AutoSizing = false)); }
public override void Run(IObservable <TSource> source) { CreateTimer(0L); Disposable.SetSingle(ref _mainDisposable, source.SubscribeSafe(this)); }
int executeCommandLine(string[] args) { var animatedGifWindowToken = new CancellationTokenSource(); #if !MONO // Uncomment to test Gifs /* * var ps = new ProgressSource(); * int i = 0; var t = new Timer(_ => ps.Raise(i += 10), null, 0, 1000); * AnimatedGifWindow.ShowWindow(TimeSpan.FromMilliseconds(0), animatedGifWindowToken.Token, ps); * Thread.Sleep(10 * 60 * 1000); */ #endif using (Disposable.Create(() => animatedGifWindowToken.Cancel())) { this.Log().Info("Starting Squirrel Updater: " + String.Join(" ", args)); if (args.Any(x => x.StartsWith("/squirrel", StringComparison.OrdinalIgnoreCase))) { // NB: We're marked as Squirrel-aware, but we don't want to do // anything in response to these events return(0); } if (opt.updateAction == UpdateAction.Unset) { ShowHelp(); return(-1); } switch (opt.updateAction) { #if !MONO case UpdateAction.Install: var progressSource = new ProgressSource(); if (!opt.silentInstall) { AnimatedGifWindow.ShowWindow(TimeSpan.FromSeconds(4), animatedGifWindowToken.Token, progressSource); } Install(opt.silentInstall, progressSource, Path.GetFullPath(opt.target)).Wait(); animatedGifWindowToken.Cancel(); break; case UpdateAction.Uninstall: Uninstall().Wait(); break; case UpdateAction.Download: Console.WriteLine(Download(opt.target).Result); break; case UpdateAction.Update: Update(opt.target).Wait(); break; case UpdateAction.CheckForUpdate: Console.WriteLine(CheckForUpdate(opt.target).Result); break; case UpdateAction.UpdateSelf: UpdateSelf().Wait(); break; case UpdateAction.Shortcut: Shortcut(opt.target, opt.shortcutArgs, opt.processStartArgs, opt.setupIcon); break; case UpdateAction.Deshortcut: Deshortcut(opt.target, opt.shortcutArgs); break; case UpdateAction.ProcessStart: ProcessStart(opt.processStart, opt.processStartArgs, opt.shouldWait); break; #endif case UpdateAction.Releasify: Releasify(opt.target, opt.releaseDir, opt.packagesDir, opt.bootstrapperExe, opt.backgroundGif, opt.signingParameters, opt.baseUrl, opt.setupIcon, !opt.noMsi, opt.packageAs64Bit, opt.frameworkVersion, !opt.noDelta); break; } } this.Log().Info("Finished Squirrel Updater"); return(0); }
public static IDisposable SuspendHandler(this INotifyCollectionChanged source, NotifyCollectionChangedEventHandler handler) { source.CollectionChanged -= handler; return(Disposable.Create(() => source.CollectionChanged += handler)); }
public static Slinq <T, HashSetContext <T, C> > Intersect(Slinq <T, C> slinq, Disposable <HashSet <T> > hashSet, bool release) { return(new Slinq <T, HashSetContext <T, C> >( intersectSkip, intersectRemove, dispose, new HashSetContext <T, C>(slinq, hashSet, release))); }
private static (int Imported, int Skipped) ImportedArtboards(XdImportSettings xdSettings, AkyuiLogger logger, string xdFilePath, IAkyuiProgress progress, List <IAkyuiLoader> loaders) { var stopWatch = Stopwatch.StartNew(); var file = new XdFile(xdFilePath); XdFile = file; using (Disposable.Create(() => XdFile = null)) { var imported = 0; var skipped = 0; var targets = new List <XdArtboard>(); foreach (var artwork in file.Artworks) { if (artwork.Artboard.Children.Length == 0) { continue; } var markForExport = artwork.Artboard.Children[0].Meta?.Ux?.MarkedForExport ?? false; if (!markForExport) { continue; } targets.Add(artwork); } progress.SetTotal(targets.Count); var akyuiXdObjectParsers = xdSettings.ObjectParsers ?? new AkyuiXdObjectParser[] { }; var akyuiXdGroupParsers = xdSettings.GroupParsers ?? new AkyuiXdGroupParser[] { }; var triggers = xdSettings.XdTriggers ?? new AkyuiXdImportTrigger[] { }; var expandTargets = new List <XdArtboard>(); foreach (var artwork in targets) { if (!artwork.HasParameter("expand")) { expandTargets.Add(artwork); continue; } foreach (var child in artwork.Artboard.Children.SelectMany(x => x.Artboard.Children)) { var childArtboardJson = new XdArtboardJson { Version = artwork.Artboard.Version, Artboards = artwork.Artboard.Artboards, Resources = artwork.Artboard.Resources, Children = new[] { new XdArtboardChildJson { Artboard = new XdArtboardChildArtboardJson { Children = new[] { child } } } } }; var childArtboard = new XdArtboard($"{artwork.GetSimpleName()}{child.GetSimpleName()}", artwork.Manifest, childArtboardJson, artwork.Resources, artwork.Hash); expandTargets.Add(childArtboard); } } foreach (var artwork in expandTargets) { using (progress.TaskStart(artwork.Name)) using (var _ = logger.SetCategory(artwork.Name)) { var name = artwork.Name.ToSafeString(); var xdHash = artwork.Hash; var userData = new Dictionary <string, string> { { "xd_hash", xdHash.ToString() } }; var pathGetter = new PathGetter(xdSettings, name); var prevMetaGameObject = AssetDatabase.LoadAssetAtPath <GameObject>(pathGetter.MetaSavePath); var prevMeta = prevMetaGameObject != null?prevMetaGameObject.GetComponent <AkyuiMeta>() : null; var prevMetaUserData = prevMeta != null?prevMeta.FindUserData("xd_hash") : null; if (!xdSettings.ReimportLayout && !xdSettings.ReimportAsset && prevMetaUserData != null && prevMetaUserData.value == xdHash.ToString()) { logger.Log("Skip", ("Name", artwork.Name), ("Hash", xdHash)); skipped++; continue; } loaders.Add(new XdAkyuiLoader(file, artwork, name, userData, akyuiXdObjectParsers, akyuiXdGroupParsers, triggers)); imported++; } } stopWatch.Stop(); logger.Log($"Xd Parse Finish", ("ImportArtboard", imported), ("SkipArtboard", skipped), ("Time", $"{stopWatch.Elapsed.TotalSeconds:0.00}s")); return(imported, skipped); } }
public void SetResource(IDisposable resource) { Disposable.SetSingle(ref _disposable, resource); }
public IDisposable OnRetrievingForView(Lite <Entity> lite) { return(Disposable.Combine(RetrievingForView, f => f(lite))); }
/// <summary> /// Processes the receipt of a chunk. Returns true and sets the message stream if a full message has been received. /// </summary> /// <param name="SequenceNumber">The sequence number for the received chunk.</param> /// <param name="Acknowledged">Indicates wether the receipt of this chunk has changed the acknowledgement number.</param> public bool Process(int SequenceNumber, byte[] Data, bool Initial, bool Final, out bool Acknowledged, ref Disposable<InStream> Message) { _Chunk chunk; // Make sure we need this chunk if (this._Chunks.ContainsKey(SequenceNumber) || this._AcknowledgementNumber - SequenceNumber > 0) { Acknowledged = false; return false; } // Update acknowledgement number if (Acknowledged = this._AcknowledgementNumber == SequenceNumber) { while (this._Chunks.TryGetValue(++this._AcknowledgementNumber, out chunk)) { // If the chunk has already been read in a message, remove it if (chunk.Data == null) { this._Chunks.Remove(this._AcknowledgementNumber); } } } // Add chunk chunk = new _Chunk { Data = Data, Initial = Initial, Final = Final }; // Find "First" chunk _Chunk first; int firstsq = SequenceNumber - 1; if (!Initial && this._Chunks.TryGetValue(firstsq, out first)) { firstsq = first.First; first = this._Chunks[firstsq]; chunk.First = firstsq; } else { chunk.First = firstsq = SequenceNumber; first = chunk; } // Find "Last" chunk _Chunk last; int lastsq = SequenceNumber + 1; if (!Final && this._Chunks.TryGetValue(lastsq, out last)) { lastsq = last.Last; last = this._Chunks[lastsq]; chunk.Last = lastsq; } else { chunk.Last = lastsq = SequenceNumber; last = chunk; } // Check if a full message can be formed this._Chunks[SequenceNumber] = chunk; if (first.Initial && last.Final) { Message = new _ReceiveStream(firstsq, Acknowledged, this); return true; } else { first.Last = lastsq; last.First = firstsq; return false; } }
public void DisposeEachItemInSet() { var disposable = new Disposable(); var disposables = new[] {disposable}; disposables.DisposeAll(); Assert.True(disposable.Disposed); }
/// <summary> /// Publishes the ASP.NET Core project to App Engine Flex. /// </summary> /// <param name="projectPath">The full path to the project.json for the ASP.NET Core project.</param> /// <param name="options">The <seealso cref="DeploymentOptions"/> to use.</param> /// <param name="progress">The progress indicator.</param> /// <param name="outputAction">The action to call with lines from the command output.</param> /// <returns></returns> public static async Task<NetCorePublishResult> PublishProjectAsync( string projectPath, DeploymentOptions options, IProgress<double> progress, Action<string> outputAction) { if (!File.Exists(projectPath)) { Debug.WriteLine($"Cannot find {projectPath}, not a valid project."); return null; } var stageDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(stageDirectory); progress.Report(0.1); using (var cleanup = new Disposable(() => Cleanup(stageDirectory))) { // Wait for the bundle creation operation to finish, updating progress as it goes. if (!await ProgressHelper.UpdateProgress( CreateAppBundleAsync(projectPath, stageDirectory, outputAction), progress, from: 0.1, to: 0.3)) { Debug.WriteLine("Failed to create app bundle."); return null; } CopyOrCreateDockerfile(projectPath, stageDirectory); CopyOrCreateAppYaml(projectPath, stageDirectory); progress.Report(0.4); // Deploy to app engine, this is where most of the time is going to be spent. Wait for // the operation to finish, update the progress as it goes. var effectiveVersion = options.Version ?? GetDefaultVersion(); var deployTask = DeployAppBundleAsync( stageDirectory: stageDirectory, version: effectiveVersion, promote: options.Promote, context: options.Context, outputAction: outputAction); if (!await ProgressHelper.UpdateProgress(deployTask, progress, 0.6, 0.9)) { Debug.WriteLine("Failed to deploy bundle."); return null; } progress.Report(1.0); var service = GetAppEngineService(projectPath); return new NetCorePublishResult( projectId: options.Context.ProjectId, service: service, version: effectiveVersion, promoted: options.Promote); } }
public static void Scenario(Disposable disposable) { "Given a disposable" .f(c => { context++; var @event = string.Concat("step", context.ToString(CultureInfo.InvariantCulture)); typeof(ObjectDisposalFeature).SaveTestEvent(@event); disposable = new Disposable(context).Using(c); }); "When using the disposable" .f(() => disposable.Use()); "Then something" .f(() => { }) .InIsolation(); "And something" .f(() => { }); }
public static void Scenario() { var disposable0 = default(Disposable); var disposable1 = default(Disposable); var disposable2 = default(Disposable); "Given a disposable" .Given(() => disposable0 = new Disposable().Using()); "And another disposable" .Given(() => disposable1 = new Disposable().Using()); "And another disposable" .Given(() => disposable2 = new Disposable().Using()); "When using the disposables" .When(() => { disposable0.Use(); disposable1.Use(); disposable2.Use(); }); }
public Given_an_instance_of_an_Owned_disposable() { _ownedDisposable = Disposable.AsOwned(); }
public static void Scenario() { var disposable0 = default(Disposable); var disposable1 = default(Disposable); var disposable2 = default(Disposable); "Given a disposable" .Given(() => disposable0 = new Disposable().Using()); "And another disposable" .Given(() => disposable1 = new Disposable().Using()); "And another disposable" .Given(() => disposable2 = new Disposable().Using()); "When using the disposables" .When(() => { disposable0.Use(); disposable1.Use(); disposable2.Use(); }); "Then something happens" .Then(() => 1.Should().Be(0)); }
public Given_an_instance_of_a_BorrowedDisposable() { _borrowedDisposable = Disposable.AsBorrowed(); }
bool FindFuelSourcesStackPriorityRecursive(int type, Disposable<HashSet<FuelNode>> sources, int fuelLookupID, int level, bool checkSurface) { // The fuel flow rules for STACK_PRIORITY_SEARCH are nicely explained in detail by Kashua at // http://forum.kerbalspaceprogram.com/threads/64362-Fuel-Flow-Rules-%280-23-5%29 // recursive search cannot visit same node twice (Kashua rule #1) if (fuelLookupID == lastSeenFuelLookupID) { return false; } lastSeenFuelLookupID = fuelLookupID; // First try to draw fuel through incoming fuel lines (Kashua rule #2) bool success = false; for (int i = 0; i < fuelLineSources.Count; i++) { success |= fuelLineSources[i].FindFuelSourcesStackPriorityRecursive(type, sources, fuelLookupID, level + 1, checkSurface); } if (success) { return true; } // Then try to draw fuel through stack nodes (Kashua rule #4 (there is no rule #3)) for (int i = 0; i < stackNodeSources.Count; i++) { success |= stackNodeSources[i].FindFuelSourcesStackPriorityRecursive(type, sources, fuelLookupID, level + 1, checkSurface); } if (success) { return true; } // Then try to draw fuel through stack mounted children nodes (That one did not exist in Kashua time so it is the rule #3 that goes after #4) if (checkSurface) { for (int i = 0; i < surfaceMountSources.Count; i++) { success |= surfaceMountSources[i].FindFuelSourcesStackPriorityRecursive(type, sources, fuelLookupID, level + 1, checkSurface); } if (success) { return true; } } // If we are a container for this resource (and it hasn't been disabled by the right-click menu)... if (resources.ContainsKey(type)) { // If we have some of the resource, return ourselves (Kashua rule #5) // Otherwise return failure (Kashua rule #6) if (resources[type] > DRAINED) { sources.value.Add(this); return true; } else { return false; } } // If we are fuel crossfeed capable and surface-mounted to our parent, // try to draw fuel from our parent (Kashua rule #7) if (surfaceMountParent != null) { return surfaceMountParent.FindFuelSourcesStackPriorityRecursive(type, sources, fuelLookupID, level + 1, checkSurface); } // If all that fails, give up (Kashua rule #8) return false; }
public Given_an_instance_of_a_BorrowedDisposable_with_strict_mode_set() { _borrowedDisposable = Disposable.AsBorrowed(isStrict: true); }
private static IDisposable InnerCreateLayer(UIElement owner, LayoutState state) { var parent = owner.Visual; var compositor = parent.Compositor; var area = owner.LayoutRound(state.Area); var background = state.Background; var borderThickness = owner.LayoutRound(state.BorderThickness); var borderBrush = state.BorderBrush; var cornerRadius = state.CornerRadius; var disposables = new CompositeDisposable(); var sublayers = new List <Visual>(); var heightOffset = ((float)borderThickness.Top / 2) + ((float)borderThickness.Bottom / 2); var widthOffset = ((float)borderThickness.Left / 2) + ((float)borderThickness.Right / 2); var halfWidth = (float)area.Width / 2; var halfHeight = (float)area.Height / 2; var adjustedArea = area; adjustedArea = adjustedArea.DeflateBy(borderThickness); if (cornerRadius != CornerRadius.None) { var maxOuterRadius = Math.Max(0, Math.Min(halfWidth - widthOffset, halfHeight - heightOffset)); var maxInnerRadius = Math.Max(0, Math.Min(halfWidth, halfHeight)); cornerRadius = new CornerRadius( Math.Min(cornerRadius.TopLeft, maxOuterRadius), Math.Min(cornerRadius.TopRight, maxOuterRadius), Math.Min(cornerRadius.BottomRight, maxOuterRadius), Math.Min(cornerRadius.BottomLeft, maxOuterRadius)); var innerCornerRadius = new CornerRadius( Math.Min(cornerRadius.TopLeft, maxInnerRadius), Math.Min(cornerRadius.TopRight, maxInnerRadius), Math.Min(cornerRadius.BottomRight, maxInnerRadius), Math.Min(cornerRadius.BottomLeft, maxInnerRadius)); var borderShape = compositor.CreateSpriteShape(); var backgroundShape = compositor.CreateSpriteShape(); var outerShape = compositor.CreateSpriteShape(); // Border brush Brush.AssignAndObserveBrush(borderBrush, compositor, brush => borderShape.FillBrush = brush) .DisposeWith(disposables); // Background brush if (background is ImageBrush imgBackground) { adjustedArea = CreateImageLayer(compositor, disposables, borderThickness, adjustedArea, backgroundShape, adjustedArea, imgBackground); } else { Brush.AssignAndObserveBrush(background, compositor, brush => backgroundShape.FillBrush = brush) .DisposeWith(disposables); } var borderPath = GetRoundedRect(cornerRadius, innerCornerRadius, area, adjustedArea); var backgroundPath = GetRoundedPath(cornerRadius, adjustedArea); var outerPath = GetRoundedPath(cornerRadius, area); backgroundShape.Geometry = compositor.CreatePathGeometry(backgroundPath); borderShape.Geometry = compositor.CreatePathGeometry(borderPath); outerShape.Geometry = compositor.CreatePathGeometry(outerPath); var borderVisual = compositor.CreateShapeVisual(); var backgroundVisual = compositor.CreateShapeVisual(); backgroundVisual.Shapes.Add(backgroundShape); borderVisual.Shapes.Add(borderShape); sublayers.Add(backgroundVisual); sublayers.Add(borderVisual); parent.Children.InsertAtBottom(backgroundVisual); parent.Children.InsertAtTop(borderVisual); owner.ClippingIsSetByCornerRadius = cornerRadius != CornerRadius.None; if (owner.ClippingIsSetByCornerRadius) { parent.Clip = compositor.CreateGeometricClip(outerShape.Geometry); } } else { var shapeVisual = compositor.CreateShapeVisual(); var backgroundShape = compositor.CreateSpriteShape(); var backgroundArea = area; // Background brush if (background is ImageBrush imgBackground) { backgroundArea = CreateImageLayer(compositor, disposables, borderThickness, adjustedArea, backgroundShape, backgroundArea, imgBackground); } else { Brush.AssignAndObserveBrush(background, compositor, brush => backgroundShape.FillBrush = brush) .DisposeWith(disposables); // This is required because changing the CornerRadius changes the background drawing // implementation and we don't want a rectangular background behind a rounded background. Disposable.Create(() => backgroundShape.FillBrush = null) .DisposeWith(disposables); } var geometrySource = new SkiaGeometrySource2D(); var geometry = geometrySource.Geometry; geometry.AddRect(backgroundArea.ToSKRect()); backgroundShape.Geometry = compositor.CreatePathGeometry(new CompositionPath(geometrySource)); shapeVisual.Shapes.Add(backgroundShape); if (borderThickness != Thickness.Empty) { Action <Action <CompositionSpriteShape, SKPath> > createLayer = builder => { var spriteShape = compositor.CreateSpriteShape(); var geometry = new SkiaGeometrySource2D(); // Border brush Brush.AssignAndObserveBrush(borderBrush, compositor, brush => spriteShape.StrokeBrush = brush) .DisposeWith(disposables); builder(spriteShape, geometry.Geometry); spriteShape.Geometry = compositor.CreatePathGeometry(new CompositionPath(geometry)); shapeVisual.Shapes.Add(spriteShape); }; if (borderThickness.Top != 0) { createLayer((l, path) => { l.StrokeThickness = (float)borderThickness.Top; var StrokeThicknessAdjust = (float)(borderThickness.Top / 2); path.MoveTo((float)(area.X + borderThickness.Left), (float)(area.Y + StrokeThicknessAdjust)); path.LineTo((float)(area.X + area.Width - borderThickness.Right), (float)(area.Y + StrokeThicknessAdjust)); path.Close(); }); } if (borderThickness.Bottom != 0) { createLayer((l, path) => { l.StrokeThickness = (float)borderThickness.Bottom; var StrokeThicknessAdjust = borderThickness.Bottom / 2; path.MoveTo((float)(area.X + (float)borderThickness.Left), (float)(area.Y + area.Height - StrokeThicknessAdjust)); path.LineTo((float)(area.X + area.Width - (float)borderThickness.Right), (float)(area.Y + area.Height - StrokeThicknessAdjust)); path.Close(); }); } if (borderThickness.Left != 0) { createLayer((l, path) => { l.StrokeThickness = (float)borderThickness.Left; var StrokeThicknessAdjust = borderThickness.Left / 2; path.MoveTo((float)(area.X + StrokeThicknessAdjust), (float)area.Y); path.LineTo((float)(area.X + StrokeThicknessAdjust), (float)(area.Y + area.Height)); path.Close(); }); } if (borderThickness.Right != 0) { createLayer((l, path) => { l.StrokeThickness = (float)borderThickness.Right; var StrokeThicknessAdjust = borderThickness.Right / 2; path.MoveTo((float)(area.X + area.Width - StrokeThicknessAdjust), (float)area.Y); path.LineTo((float)(area.X + area.Width - StrokeThicknessAdjust), (float)(area.Y + area.Height)); path.Close(); }); } } sublayers.Add(shapeVisual); // Must be inserted below the other subviews, which may happen when // the current view has subviews. parent.Children.InsertAtBottom(shapeVisual); } disposables.Add(() => { owner.ClippingIsSetByCornerRadius = false; foreach (var sv in sublayers) { parent.Children.Remove(sv); sv.Dispose(); } } ); compositor.InvalidateRender(); return(disposables); }
public IDisposable Start(IFeatureCollection serverFeatures, Func<IFeatureCollection, Task> application) { var disposables = new Stack<IDisposable>(); var disposer = new Disposable(() => { foreach (var disposable in disposables) { disposable.Dispose(); } }); try { var information = (KestrelServerInformation)serverFeatures.Get<IKestrelServerInformation>(); var dateHeaderValueManager = new DateHeaderValueManager(); var engine = new KestrelEngine(_libraryManager, new ServiceContext { AppShutdown = _appShutdownService, Log = new KestrelTrace(_logger), DateHeaderValueManager = dateHeaderValueManager }); disposables.Push(engine); disposables.Push(dateHeaderValueManager); if (information.ThreadCount < 0) { throw new ArgumentOutOfRangeException(nameof(information.ThreadCount), information.ThreadCount, "ThreadCount cannot be negative"); } engine.Start(information.ThreadCount == 0 ? 1 : information.ThreadCount); bool atLeastOneListener = false; foreach (var address in information.Addresses) { var parsedAddress = ServerAddress.FromUrl(address); if (parsedAddress == null) { throw new FormatException("Unrecognized listening address: " + address); } else { atLeastOneListener = true; disposables.Push(engine.CreateServer( parsedAddress.Scheme, parsedAddress.Host, parsedAddress.Port, async frame => { var request = new ServerRequest(frame); await application.Invoke(request.Features).ConfigureAwait(false); })); } } if (!atLeastOneListener) { throw new InvalidOperationException("No recognized listening addresses were configured."); } return disposer; } catch { disposer.Dispose(); throw; } }
static IDisposable ConnectAndSubscribe(string connectionString) { var connectionFactory = new ConnectionFactory { Uri = connectionString, ClientProperties = new Dictionary<string, string> { { "Client", "EasyNetQ.Trace" }, { "Host", Environment.MachineName } }, RequestedHeartbeat = 10 }; var connection = connectionFactory.CreateConnection(); var disposable = new Disposable{ ToBeDisposed = connection }; connection.ConnectionShutdown += (connection1, reason) => { if(!tokenSource.IsCancellationRequested) { Console.Out.WriteLine("\nConnection closed.\nReason {0}\nNow reconnecting", reason.ToString()); disposable.ToBeDisposed = ConnectAndSubscribe(connectionString); } }; Subscribe(connection, traceExchange, publishRoutingKey); Subscribe(connection, traceExchange, deliverRoutingKey); return disposable; }
private static Task <Result <UserInfo> > HandleUserInfoResponse(ApiResult result) => Disposable.UsingAsync( () => result.Response, x => x.ParseAndMapResultAsync <UserInfoDto, UserInfo>(UserInfoDto.MapToModel));