private void StartNewDiagram() { SaveFileDialog dlg = new SaveFileDialog(); dlg.DefaultExt = "*.txt"; dlg.Filter = "Diagram text files (*.txt)|*.txt"; dlg.AddExtension = true; dlg.InitialDirectory = this.DiagramLocationTextBox.Text; if (dlg.ShowDialog().Value) { var diagramFileName = dlg.FileName; File.WriteAllText(diagramFileName, string.Format( "@startuml \"{0}\"" + Environment.NewLine + Environment.NewLine + Environment.NewLine + "@enduml", System.IO.Path.GetFileNameWithoutExtension(diagramFileName) + ".png")); this.DiagramLocationTextBox.Text = System.IO.Path.GetDirectoryName(diagramFileName); Weak <ListBox> listbox = this.DiagramFileListBox; this.LoadDiagramFiles(this.DiagramLocationTextBox.Text, () => { var diagramOnList = this._DiagramFiles.First( d => d.DiagramFilePath == diagramFileName); ListBox diagramListBox = listbox; diagramListBox.SelectedItem = diagramOnList; this.OpenDiagramFile(diagramOnList); }); } }
/// <summary> /// Initializes a new instance of the <see cref="BindingListToBindableCollectionAdapter<TElement>"/> class. /// </summary> /// <param name="sourceCollection">The source collection.</param> /// <param name="dispatcher">The dispatcher.</param> public BindingListToBindableCollectionAdapter(IEnumerable sourceCollection, IDispatcher dispatcher) : base(sourceCollection, dispatcher) { var observable = (IBindingList)sourceCollection; observable.ListChanged += Weak.Event <ListChangedEventArgs>((sender, e) => Dispatcher.Dispatch(() => SourceCollection_ListChanged(sender, e))).KeepAlive(InstanceLifetime).HandlerProxy.Handler; }
/// <summary> /// Initializes a new instance of the <see cref="Iterator<TSource, TResult>"/> class. /// </summary> protected Iterator(IBindableCollection <TSource> sourceCollection, IDispatcher dispatcher) : base(dispatcher) { _resultCollection = new BindableCollection <TResult>(dispatcher); _resultCollection.CollectionChanged += ((sender, e) => OnCollectionChanged(e)); _sourceCollection = sourceCollection; _sourceCollection.CollectionChanged += Weak.Event <NotifyCollectionChangedEventArgs>((sender, e) => Dispatcher.Dispatch(() => ReactToCollectionChanged(e))).KeepAlive(InstanceLifetime).HandlerProxy.Handler; }
public async Task GetWeak(CommandContext ctx) { var weak = Weak.GetWeak(); var message = $"№ {Weak.GetNumberOfWeak()} {weak}" + (weak.ToLower().Equals("чётная") ? " - нижняя" : " - верхняя"); await ctx.Channel.SendMessageAsync(message).ConfigureAwait(false); }
public ObservableCollectionToBindableCollectionAdapter(IEnumerable sourceCollection, IDispatcher dispatcher) : base(sourceCollection, dispatcher) { var observable = sourceCollection as INotifyCollectionChanged; if (observable != null) { // TODO observable.CollectionChanged += Weak.Event <NotifyCollectionChangedEventArgs>((sender, e) => Dispatcher.Dispatch(() => OnCollectionChanged(e))).KeepAlive(InstanceLifetime).HandlerProxy.Handler; } }
public void WeakTargetTest() { var target = new object(); var weak = new Weak <object>(target); Assert.True(weak.IsAlive); target = null; GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); GC.WaitForFullGCComplete(); Assert.False(weak.IsAlive); }
public async Task GetUserAgeOnServer(CommandContext ctx, [Description("Дата этого пользователя")] DiscordMember discordMember = null) { if (discordMember == null) { discordMember = ctx.Member; } var days = Weak.GetAge(discordMember.JoinedAt.DateTime); var message = $"{discordMember.DisplayName} на сервере уже: {days} дней" + $" \nПрисоединился к нам: {discordMember.JoinedAt.DateTime}"; await ctx.Channel.SendMessageAsync(message).ConfigureAwait(false); }
public int DamageFrom(Group group) { if (Immune.HasFlag(group.Element)) { return(0); } if (Weak.HasFlag(group.Element)) { return(2 * group.EffectivePower); } return(group.EffectivePower); }
public ObservableCollectionToBindableCollectionAdapter(IEnumerable sourceCollection, IDispatcher dispatcher) : base(sourceCollection, dispatcher) { if (sourceCollection is INotifyCollectionChanged notifyCollectionChanged) { notifyCollectionChanged.CollectionChanged += Weak.Event(delegate(object sender, NotifyCollectionChangedEventArgs e) { var observableCollectionToBindableCollectionAdapter = this; Dispatcher.Dispatch(delegate { observableCollectionToBindableCollectionAdapter.OnCollectionChanged(e); }); }).KeepAlive(InstanceLifetime).HandlerProxy.Handler; } }
public BindingListToBindableCollectionAdapter(IEnumerable sourceCollection, IDispatcher dispatcher) : base(sourceCollection, dispatcher) { var bindingList = (IBindingList)sourceCollection; var bindingList2 = bindingList; EventHandler <ListChangedEventArgs> eventHandler = delegate(object sender, ListChangedEventArgs e) { var bindingListToBindableCollectionAdapter = this; Dispatcher.Dispatch(delegate { bindingListToBindableCollectionAdapter.SourceCollection_ListChanged(sender, e); }); }; bindingList2.ListChanged += Weak.Event(eventHandler).KeepAlive(InstanceLifetime).HandlerProxy.Handler; }
private Token BindToken(string virtualPath) { lock (_tokens) { Weak<Token> weak; if (!_tokens.TryGetValue(virtualPath, out weak)) { weak = new Weak<Token>(new Token(virtualPath)); _tokens[virtualPath] = weak; } var token = weak.Target; if (token == null) { token = new Token(virtualPath); weak.Target = token; } return token; } }
private Token BindToken(string virtualPath) { lock (_tokens) { Weak <Token> weak; if (!_tokens.TryGetValue(virtualPath, out weak)) { weak = new Weak <Token>(new Token(virtualPath)); _tokens[virtualPath] = weak; } var token = weak.Target; if (token == null) { token = new Token(virtualPath); weak.Target = token; } return(token); } }
public void EqualsTest() { var obj1 = new object(); var obj2 = new object(); var weak1 = new Weak <object>(obj1); var weak2 = new Weak <object>(obj1); var weak3 = new Weak <object>(obj2); var sut = new WeakEqualityComparer <object>(); Assert.True(sut.Equals(weak1, weak2)); Assert.False(sut.Equals(weak2, weak3)); obj2 = null; GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); GC.WaitForFullGCComplete(); var hold = new Weak <object>(obj1); Assert.True(sut.Equals(weak1, weak2)); Assert.False(sut.Equals(weak2, weak3)); }
public void GetHashCodeTest() { var obj1 = new object(); var obj2 = new object(); var weak1 = new Weak <object>(obj1); var weak2 = new Weak <object>(obj1); var weak3 = new Weak <object>(obj2); var sut = new WeakEqualityComparer <object>(); Assert.Equal(sut.GetHashCode(weak1), sut.GetHashCode(weak2)); Assert.NotEqual(sut.GetHashCode(weak2), sut.GetHashCode(weak3)); obj2 = null; GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); GC.WaitForFullGCComplete(); var hold = new Weak <object>(obj1); Assert.Equal(sut.GetHashCode(weak1), sut.GetHashCode(weak2)); Assert.NotEqual(sut.GetHashCode(weak2), sut.GetHashCode(weak3)); }
private void UserControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { if (DesignerProperties.GetIsInDesignMode(this)) { return; } if (e.NewValue != null) { var newDiagram = (e.NewValue as DiagramFile); ContentEditor.Text = newDiagram.Content; ContentEditor.Tag = newDiagram.DiagramFilePath; // The document has been opened first time. So, any changes // made to the document will require creating a backup. _FirstSaveAfterOpen = true; } if (this._LastMenuItemClicked != default(Weak <MenuItem>)) { this._LastMenuItemClicked.Dispose(); this._LastMenuItemClicked = null; } }
internal Concrete() { this.weak = new Weak(typeof(TEnum)); }
public Thunk(DefaultVirtualPathMonitor provider) { _weak = new Weak <DefaultVirtualPathMonitor>(provider); }
/// <summary> /// Checks if there's a new version of the app and downloads and installs /// if user wants to. /// </summary> private void CheckForUpdate() { var me = new Weak <Window>(this); // Check if there's a newer version of the app Start <bool> .Work(() => { var versionFileName = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Settings.Default.VersionFileName); if (File.Exists(versionFileName)) { var localVersion = File.ReadAllText(versionFileName); return(UpdateChecker.HasUpdate(Settings.Default.VersionFileUrl, localVersion)); } else { return(true); } }) .OnComplete((hasUpdate) => { if (hasUpdate) { if (MessageBox.Show(Window.GetWindow(me), "There's a newer version available. Do you want to download and install?", "New version available", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes) { ParallelWork.StartNow(() => { var tempPath = System.IO.Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Settings.Default.SetupExeName); UpdateChecker.DownloadLatestUpdate(Settings.Default.DownloadUrl, tempPath); }, () => { }, (x) => { MessageBox.Show(Window.GetWindow(me), "Download failed. When you run next time, it will try downloading again.", "Download failed", MessageBoxButton.OK, MessageBoxImage.Warning); }); } } }) .OnException((x) => { MessageBox.Show(Window.GetWindow(me), x.Message, "Download failed", MessageBoxButton.OK, MessageBoxImage.Exclamation); }) .Run(); UpdateChecker.DownloadCompleted = new Action <AsyncCompletedEventArgs>((e) => { Dispatcher.BeginInvoke(new Action(() => { if (e.Cancelled || e.Error != default(Exception)) { MessageBox.Show(Window.GetWindow(me), "Download failed. When you run next time, it will try downloading again.", "Download failed", MessageBoxButton.OK, MessageBoxImage.Warning); } else { Process.Start(UpdateChecker.DownloadedLocation).Dispose(); this.Close(); } })); }); UpdateChecker.DownloadProgressChanged = new Action <DownloadProgressChangedEventArgs>((e) => { Dispatcher.BeginInvoke(new Action(() => { this.StartProgress("New version downloaded " + e.ProgressPercentage + "%"); })); }); }
/// <summary> /// Initializes a new instance of the <see cref="Aggregator<TSource, TResult>"/> class. /// </summary> /// <param name="sourceCollection">The source collection.</param> /// <param name="dispatcher">The dispatcher.</param> protected Aggregator(IBindableCollection <TSource> sourceCollection, IDispatcher dispatcher) : base(dispatcher) { _sourceCollection = sourceCollection; _sourceCollection.CollectionChanged += Weak.Event <NotifyCollectionChangedEventArgs>((sender, e) => Dispatcher.Dispatch(Refresh)).KeepAlive(InstanceLifetime).HandlerProxy.Handler; }
/// <summary> /// Checks if there's a new version of the app and downloads and installs /// if user wants to. /// </summary> private void CheckForUpdate() { var me = new Weak<Window>(this); // Check if there's a newer version of the app Start<bool>.Work(() => { var versionFileName = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Settings.Default.VersionFileName); if (File.Exists(versionFileName)) { var localVersion = File.ReadAllText(versionFileName); return UpdateChecker.HasUpdate(Settings.Default.VersionFileUrl, localVersion); } else { return true; } }) .OnComplete((hasUpdate) => { if (hasUpdate) { if (MessageBox.Show(Window.GetWindow(me), "There's a newer version available. Do you want to download and install?", "New version available", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes) { ParallelWork.StartNow(() => { var tempPath = System.IO.Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Settings.Default.SetupExeName); UpdateChecker.DownloadLatestUpdate(Settings.Default.DownloadUrl, tempPath); }, () => { }, (x) => { MessageBox.Show(Window.GetWindow(me), "Download failed. When you run next time, it will try downloading again.", "Download failed", MessageBoxButton.OK, MessageBoxImage.Warning); }); } } }) .OnException((x) => { MessageBox.Show(Window.GetWindow(me), x.Message, "Download failed", MessageBoxButton.OK, MessageBoxImage.Exclamation); }) .Run(); UpdateChecker.DownloadCompleted = new Action<AsyncCompletedEventArgs>((e) => { Dispatcher.BeginInvoke(new Action(() => { if (e.Cancelled || e.Error != default(Exception)) { MessageBox.Show(Window.GetWindow(me), "Download failed. When you run next time, it will try downloading again.", "Download failed", MessageBoxButton.OK, MessageBoxImage.Warning); } else { Process.Start(UpdateChecker.DownloadedLocation).Dispose(); this.Close(); } })); }); UpdateChecker.DownloadProgressChanged = new Action<DownloadProgressChangedEventArgs>((e) => { Dispatcher.BeginInvoke(new Action(() => { this.StartProgress("New version downloaded " + e.ProgressPercentage + "%"); })); }); }
public Thunk(DefaultVirtualPathMonitor provider) { _weak = new Weak<DefaultVirtualPathMonitor>(provider); }
private void LoadDiagramFiles(string path, Action loaded) { _DiagramFiles.Clear(); this.StartProgress("Loading diagrams..."); Weak <ListBox> listbox = this.DiagramFileListBox; Start <List <DiagramFile> > .Work((onprogress) => { var diagrams = new List <DiagramFile>(); var files = Directory.GetFiles(path, "*.txt"); var numberOfFiles = files.Length; var processed = 0; foreach (string file in files) { try { string content = File.ReadAllText(file); if (content != null && content.Length > 0) { //string firstLine = content.Substring(0,500); Match match = Regex.Match(content, @"@startuml\s*(?:"")*([^\r\n""]*)", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled ); if (match.Success && match.Groups.Count > 1) { string imageFileName = match.Groups[1].Value; diagrams.Add(new DiagramFile { Content = content, DiagramFilePath = file, ImageFilePath = System.IO.Path.IsPathRooted(imageFileName) ? System.IO.Path.GetFullPath(imageFileName) : System.IO.Path.GetFullPath( System.IO.Path.Combine(path, imageFileName)) }); } processed++; onprogress(string.Format("Loading {0} of {1}", processed, numberOfFiles), (int)((double)processed / (double)numberOfFiles * 100)); //Thread.Sleep(50); } } catch (Exception x) { Debug.WriteLine(x); } } return(diagrams); }) .OnProgress((msg, progress) => { this.StartProgress(msg, progress); }) .OnComplete((diagrams) => { this._DiagramFiles = new ObservableCollection <DiagramFile>(diagrams); (listbox.Target as ListBox).ItemsSource = this._DiagramFiles; this.StopProgress("Diagrams loaded."); loaded(); }) .OnException((exception) => { MessageBox.Show(this, exception.Message, "Error loading files", MessageBoxButton.OK, MessageBoxImage.Error); this.StopProgress(exception.Message); }) .Run(); }
private void UserControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { if (DesignerProperties.GetIsInDesignMode(this)) return; if (e.NewValue != null) { var newDiagram = (e.NewValue as DiagramFile); ContentEditor.Text = newDiagram.Content; ContentEditor.Tag = newDiagram.DiagramFilePath; // The document has been opened first time. So, any changes // made to the document will require creating a backup. _FirstSaveAfterOpen = true; } if (this._LastMenuItemClicked != default(Weak<MenuItem>)) { this._LastMenuItemClicked.Dispose(); this._LastMenuItemClicked = null; } }
private void MenuItem_Click(object sender, RoutedEventArgs e) { this._LastMenuItemClicked = e.Source as MenuItem; this.AddCode((e.Source as MenuItem).Tag as string); }
public Thunk(WebSiteFolder provider) { _weak = new Weak<WebSiteFolder>(provider); }
public void WeakerAttack() { Weak?.Invoke(this, EventArgs.Empty); }
/// <summary> /// Initializes a new instance of the <see cref="Operator<TSource, TResult>"/> class. /// </summary> /// <param name="dispatcher">The dispatcher.</param> /// <param name="source">The source.</param> protected Operator(IBindable <TSource> source, IDispatcher dispatcher) : base(dispatcher) { _source = source; _source.PropertyChanged += Weak.Event <PropertyChangedEventArgs>((sender, e) => Dispatcher.Dispatch(Refresh)).KeepAlive(InstanceLifetime).HandlerProxy.Handler; }