public override bool ValidParams() { var flag = true; ValidetionMessages = new ObservableDictionary <string, string>(); if (string.IsNullOrEmpty(Item.Name)) { ValidetionMessages.Add("Specializations-name", "Specialization name is empty!!"); flag = false; } if (Item.MaxHourSalary < 26 || Item.MinHourSalary < 26) { ValidetionMessages.Add("Specializations-slary", "max or min can't smmaller from 26!!"); flag = false; } if (Item.MaxHourSalary < Item.MinHourSalary) { ValidetionMessages.Add("Specializations-slary", "min salary can't be bigger or same to the max salary!!"); flag = false; } // valid if employee id exsisted if (Bl.IsExiste(CollectionNames.Specializations, Item.ID) && Mode == ViewMode.Add) { ValidetionMessages.Add("Spcializations-exsist", "Specialization already existed in DB!!"); flag = false; } return(flag); }
public void SourceManipulation() { var numbers = new ObservableDictionary <int, int>(Enumerable.Range(1, 3).ToDictionary(i => i)); using var expr = numbers.ActiveSingle((key, value) => value % 3 == 0); Assert.IsNull(expr.OperationFault); Assert.AreEqual(3, expr.Value.Value); numbers.Remove(3); Assert.IsNotNull(expr.OperationFault); Assert.AreEqual(0, expr.Value.Value); numbers.Add(3, 3); Assert.IsNull(expr.OperationFault); Assert.AreEqual(3, expr.Value.Value); numbers.Add(5, 5); Assert.IsNull(expr.OperationFault); Assert.AreEqual(3, expr.Value.Value); numbers.Add(6, 6); Assert.IsNotNull(expr.OperationFault); Assert.AreEqual(0, expr.Value.Value); numbers.Clear(); Assert.IsNotNull(expr.OperationFault); Assert.AreEqual(0, expr.Value.Value); numbers.Add(3, 3); numbers.Add(6, 6); Assert.IsNotNull(expr.OperationFault); Assert.AreEqual(0, expr.Value.Value); numbers.Remove(3); Assert.IsNull(expr.OperationFault); Assert.AreEqual(6, expr.Value.Value); }
public void Collection() { Observable.Add(Fixture.Create <string>(), Fixture.Create <TestItem>()); Observable.Add(Fixture.Create <string>(), Fixture.Create <TestItem>()); Observable.Add(Fixture.Create <string>(), Fixture.Create <TestItem>()); _testCases.CollectionTest(Observable); }
public void ObserveCheck() { const int valueCheck = 5; _observableDictionary.Observe(_key, ObservableUpdateType.Added, _caller.AddCall); _observableDictionary.Observe(_key, ObservableUpdateType.Updated, _caller.UpdateCall); _observableDictionary.Observe(_key, ObservableUpdateType.Removed, _caller.RemoveCall); _observableDictionary.Observe(ObservableUpdateType.Added, _caller.AddCall); _observableDictionary.Observe(ObservableUpdateType.Updated, _caller.UpdateCall); _observableDictionary.Observe(ObservableUpdateType.Removed, _caller.RemoveCall); _observableResolverDictionary.Observe(_key, ObservableUpdateType.Added, _caller.AddCall); _observableResolverDictionary.Observe(_key, ObservableUpdateType.Updated, _caller.UpdateCall); _observableResolverDictionary.Observe(_key, ObservableUpdateType.Removed, _caller.RemoveCall); _observableResolverDictionary.Observe(ObservableUpdateType.Added, _caller.AddCall); _observableResolverDictionary.Observe(ObservableUpdateType.Updated, _caller.UpdateCall); _observableResolverDictionary.Observe(ObservableUpdateType.Removed, _caller.RemoveCall); _caller.DidNotReceive().AddCall(Arg.Any <int>(), Arg.Any <int>()); _caller.DidNotReceive().UpdateCall(Arg.Any <int>(), Arg.Any <int>()); _caller.DidNotReceive().RemoveCall(Arg.Any <int>(), Arg.Any <int>()); _observableDictionary.Add(_key, valueCheck); _observableResolverDictionary.Add(_key, valueCheck); _observableDictionary[_key] = valueCheck; _observableResolverDictionary[_key] = valueCheck; _observableDictionary.Remove(_key); _observableResolverDictionary.Remove(_key); _caller.Received(4).AddCall(_key, valueCheck); _caller.Received(4).UpdateCall(_key, valueCheck); _caller.Received(4).RemoveCall(_key, 0); }
/// <summary> /// Uses the current category selection and creates a dictionary of recipients accordingly /// </summary> /// <param name="recipientsType">The category of recipients to use</param> /// <returns>An ObservableDictionary with all the relevent recipients (organized as <RecipientID, RecipientName>)</returns> private ObservableDictionary <int, string> CreateRecipientsList(EventRecipientsTypes recipientsType) { // Create a recipients dictioanry ObservableDictionary <int, string> recipients = new ObservableDictionary <int, string>(); // Create the list of students switch (recipientsType) { case EventRecipientsTypes.Students: // Add every active student in the school _schoolData.Persons.Where(person => !person.User.isDisabled && person.isStudent).ToList() .ForEach(person => recipients.Add(person.personID, person.firstName + " " + person.lastName)); break; case EventRecipientsTypes.Classes: // Add every class in the school _schoolData.Classes.ToList().ForEach(schoolClass => recipients.Add(schoolClass.classID, schoolClass.className)); break; case EventRecipientsTypes.Everyone: recipients.Add(EVERYONE_OPTION, "כל בית הספר"); break; default: throw new ArgumentException("Invalid recipient type!"); } return(recipients); }
public void DictionaryChanges() { var perfectNumbers = new ObservableDictionary <int, int>(Enumerable.Range(1, 10).ToDictionary(i => i, i => i * i)); var values = new BlockingCollection <int>(); using (var expr = ActiveExpression.Create(p1 => p1[5], perfectNumbers)) { var disconnect = expr.OnPropertyChanged(ae => ae.Value, value => { values.Add(value); }); values.Add(expr.Value); perfectNumbers.Add(11, 11 * 11); perfectNumbers.AddRange(Enumerable.Range(12, 3).ToDictionary(i => i, i => i * i)); perfectNumbers.Remove(11); perfectNumbers.RemoveRange(Enumerable.Range(12, 3)); perfectNumbers.Remove(5); perfectNumbers.Add(5, 30); perfectNumbers[5] = 25; perfectNumbers.RemoveRange(Enumerable.Range(4, 3)); perfectNumbers.AddRange(Enumerable.Range(4, 3).ToDictionary(i => i, i => i * i)); perfectNumbers.Clear(); disconnect(); } Assert.IsTrue(new int[] { 25, 0, 30, 25, 0, 25, 0 }.SequenceEqual(values)); }
public LessonManagementViewModel(Person connectedPerson, ICommand refreshDataCommand, IMessageBoxService messageBoxService) : base(messageBoxService) { HasRequiredPermissions = connectedPerson.isSecretary || connectedPerson.isPrincipal; _refreshDataCommand = refreshDataCommand; if (HasRequiredPermissions) { _schoolData = new SchoolEntities(); AvailableSearchChoices = new ObservableDictionary <int, string>(); LessonsTableData = new ObservableCollection <LessonData>(); AvailableClasses = new ObservableDictionary <int, string>(); AvailableCourses = new ObservableDictionary <int, string>(); AvailableTeachers = new ObservableDictionary <int, string>(); AvailableRooms = new ObservableDictionary <int, string>(); TeacherAvailableCourses = new ObservableDictionary <int, string>(); // Fill up days and hour lists (allow 'no meeting' choice with the NOT_ASSIGNED value) AvailableDays = new ObservableDictionary <int, string>(); AvailableDays.Add(NOT_ASSIGNED, "ללא"); for (int i = 0; i < Globals.DAY_NAMES.Length; i++) { // Count days as 1 to N rather than 0 to N-1 AvailableDays.Add(i + 1, Globals.DAY_NAMES[i]); } AvailableHours = new ObservableDictionary <int, string>(); AvailableHours.Add(NOT_ASSIGNED, "ללא"); for (int i = 0; i < Globals.HOUR_NAMES.Length; i++) { // Count hours as 1 to N rather than 0 to N-1 AvailableHours.Add(i + 1, Globals.HOUR_NAMES[i]); } } }
public override bool ValidParams() { var flag = true; ValidetionMessages = new ObservableDictionary <string, string>(); if (!Bl.ValidID(Item.ID)) { ValidetionMessages.Add("id-incorrect", "id nust to be a number and contain at 8 digds"); flag = false; } if (!Bl.ValidAgeToEmployr(Item.EstablishmentDate)) { ValidetionMessages.Add("EstablishmentDate", "EstablishmentDate must to be one tear later"); flag = false; } if (!Bl.ValidPhon(Item.Phon)) { ValidetionMessages.Add("Phon", "Phon is not valid!! (xxx-xxxxxxx)!!"); flag = false; } // valid if employee id exsisted if (Bl.IsExiste(CollectionNames.Employees, Item.ID) && Mode == ViewMode.Add) { ValidetionMessages.Add("employee-exsist", "employee already existed in DB!!"); flag = false; } return(flag); }
public static void AddWatch(Action <String, EventState> callback, String eventName, Guid eventID) { EventMonitor e = new EventMonitor(callback, eventName, eventID); _monitor.Add(eventID, e); //ActivateTimer(e); }
public void ObservableDictionary() { var list = new ObservableDictionary() { "hello" }; list.Add("world"); list["yo"] = "heyy"; list.Add("saturn"); list.Add("pluto"); Assert.IsTrue(list.ContainsKey(0)); Assert.IsTrue(list.ContainsKey(1)); Assert.IsTrue(list.ContainsKey("yo")); Assert.IsTrue(list.ContainsKey(3)); Assert.IsTrue(list.ContainsKey(4)); list.Remove(3); list.Remove(4); list.Add("hello there"); Assert.AreEqual(4, list.Count); Assert.IsTrue(list.ContainsKey(0)); Assert.IsTrue(list.ContainsKey(1)); Assert.IsTrue(list.ContainsKey("yo")); Assert.IsTrue(list.ContainsKey(3)); }
public void ObservableDictionaryAddItemTest() { var sourceDictionary = new ObservableDictionary <int, string>(); sourceDictionary.Add(1, "1"); sourceDictionary.Add(2, "2"); // Full write var syncSourceRoot = new SyncSourceRoot(sourceDictionary, _sourceSettings); var syncTargetRoot = new SyncTargetRoot <ObservableDictionary <int, string> >(syncSourceRoot.WriteFullAndDispose(), _targetSettings); ObservableDictionary <int, string> targetDictionary = syncTargetRoot.Root; foreach (KeyValuePair <int, string> keyValuePair in sourceDictionary) { Assert.Equal(keyValuePair.Value, targetDictionary[keyValuePair.Key]); } // Changes sourceDictionary.Add(3, "3"); byte[] changesSynchronization = syncSourceRoot.WriteChangesAndDispose().SetTick(0); syncTargetRoot.Read(changesSynchronization); foreach (KeyValuePair <int, string> keyValuePair in sourceDictionary) { Assert.Equal(keyValuePair.Value, targetDictionary[keyValuePair.Key]); } }
public void BeginEndBulkOperationTest() { DictionaryChangedEventArgs <int, string> args = null; var dictionary = new ObservableDictionary <int, string>(); dictionary.DictionaryChanged += (sender, e) => args = e; dictionary.BeginBatch(); dictionary.Add(1, "1"); Assert.IsNull(args); dictionary.Add(2, "2"); Assert.IsNull(args); dictionary.EndBatch(); Assert.IsNotNull(args); args = null; dictionary.BeginBatch(); dictionary.AddRange(MakeTestPairs(4, 5, 6)); Assert.IsNull(args); dictionary.Add(10, "10"); Assert.IsNull(args); dictionary.Remove(4); Assert.IsNull(args); dictionary[4] = "44"; Assert.IsNull(args); dictionary[44] = "44"; Assert.IsNull(args); dictionary.Clear(); Assert.IsNull(args); dictionary.EndBatch(); Assert.IsNotNull(args); }
/// <summary> /// Add a property to the grid, And set a custom event callback. /// </summary> /// <param name="PropName">Name of the property to add</param> /// <param name="ctype">The type of control that will be added to the grid</param> /// <param name="data">The data that will be inserted/set to the control</param> /// <param name="handler">the custom event handler</param> public void AddProperty(String PropName, TextBox ctype, String data, KeyEventHandler handler) { if (PropDictionary.ContainsKey(PropName)) { return; //avoid dict crash } //add a row. int num = 0; //add label AddLabelProp(PropName, ref num); PropDictionary.Add(PropName, data); if (data is String) { ctype.HorizontalAlignment = HorizontalAlignment.Stretch; ctype.Margin = new Thickness(10, 2, 10, 2); ((TextBox)ctype).Text = (String)data; ctype.Height = 30; Grid.SetRow(ctype, num); Grid.SetColumn(ctype, 1); ctype.BringIntoView(); ctype.Tag = PropName; //used for EZ dictionary access later ctype.KeyDown += handler; InnerPropGrid.Children.Add(ctype); //add the desired control type. } }
public void ShouldBindBetweenIndexedObjects() { var binder = new Binder<ObservableDictionary<UniversalStub>>(); var dict= new ObservableDictionary<UniversalStub>(); binder.BindIf(x => x.ContainsKey("first") && x.ContainsKey("second"), x => x["first"].String).To(x => x["second"].String); using (binder.Attach(dict)) { var first = new UniversalStub(); var second = new UniversalStub { String = "a" }; dict.Add("second", second); second.String.ShouldBe("a"); using (second.VerifyChangedOnce("String")) { dict.Add("first", first); } second.String.ShouldBe(null); using (second.VerifyChangedOnce("String")) { first.String = "b"; } second.String.ShouldBe("b"); } }
public void ContainsTest() { var dic = new ObservableDictionary <int, string>(); dic.Contains(new KeyValuePair <int, string>(1, null)).Should().BeFalse(); dic.Add(1, "1"); dic.Add(2, "2"); dic.Contains(new KeyValuePair <int, string>(1, "1")).Should().BeTrue(); }
public PaletteEditorTreeViewItem(string entryId, string name, Dictionary <string, T> values) { EntryId = entryId; _name = new ObservableProperty <string>(name); foreach (var value in values) { _values.Add(value.Key, new ObservableProperty <T>(value.Value)); } }
private void RefreshGui() { ObservableDictionary <string, string> displayStrings = new ObservableDictionary <string, string>(); //Initialize a observable dictionary to allow the xaml file to grab information from the current database and display it try { if (Scan.IsInfected) { displayStrings.Add("IsInfected", "The sample is infected"); displayStrings.Add("InfectedColor", "Red"); } else { displayStrings.Add("IsInfected", "The sample is not infected"); displayStrings.Add("InfectedColor", "Green"); } displayStrings.Add("Name", "Name: " + Scan.Name); displayStrings.Add("ID", "ID: " + i); displayStrings.Add("Date", "Date: " + Scan.Date); displayStrings.Add("PeakCurrent", "The peak current was " + Scan.PeakVoltage + "µA"); displayStrings.Add("Reference", "A normal amount of bacteria is around # cfu/mL"); } catch (Exception ex) { Crashes.TrackError(ex); } BindingContext = displayStrings; //Set the binding context to the observable dictionary }
public void ObservableDictionaryReferenceTrackOnPreAddTest() { var sourceDictionary = new ObservableDictionary <int, string>(); sourceDictionary.Add(1, "1"); sourceDictionary.Add(2, "2"); var syncSourceRoot = new SyncSourceRoot(sourceDictionary, SyncSourceSettings.Default); Assert.Equal(3, syncSourceRoot.TrackedReferences.Count()); }
public void AddingItems_ThatAreReferences_ShouldTrackAddedItems() { var sourceDictionary = new ObservableDictionary <int, string>(); var SourceSynchronizerRoot = new SourceSynchronizerRoot(sourceDictionary); sourceDictionary.Add(1, "1"); sourceDictionary.Add(2, "2"); Assert.Equal(3, SourceSynchronizerRoot.TrackedObjects.Count()); }
public void TryGetValueTest() { var dic = new ObservableDictionary <int, string>(); string value; dic.TryGetValue(1, out value).Should().BeFalse(); dic.Add(1, "1"); dic.Add(2, "2"); dic.TryGetValue(1, out value).Should().BeTrue(); value.Should().Be("1"); }
public ViewModel() { Items = new ObservableDictionary <string, object>(); Items.Add("Chennai", "MAS"); Items.Add("Trichy", "TPJ"); Items.Add("Bangalore", "SBC"); Items.Add("Coimbatore", "CBE"); SelectedItems = new ObservableDictionary <string, object>(); SelectedItems.Add("Chennai", "MAS"); SelectedItems.Add("Trichy", "TPJ"); }
public void ToDictionary_Unset_Set() { var source = new ObservableDictionary<int, string>(); var get2 = Nothing<string>(); source.ToLiveLinq()[2].Subscribe(val => get2 = val); get2.Should().Be(Nothing<string>()); source.Add(2, "Hi there"); get2.Should().Be(Something("Hi there")); source.Remove(2); get2.Should().Be(Nothing<string>()); source.Add(2, "Hello"); get2.Should().Be(Something("Hello")); }
public Bag() { Properties = new ObservableCollection <Tuple <string, object, Control> >(); observableDictionary.Add("combo box", new List <String>() { "one", "two", "three" }); //combo box observableDictionary.Add("Text", "Default Text"); //textblock and or label observableDictionary.Add("Check Box", true); //check box observableDictionary.Add("Text Box", "Writable Text"); //observableDictionary.Add("Custom Controls", new DropDownCustomColorPicker.ColorPicker()); Name = ""; //DictionaryValues = new ObservableCollection<object>(observableDictionary.Values); //sync }
public void OperationCollapseTest() { var argsList = new List <DictionaryChangedEventArgs <int, string> >(); var dictionary = new ObservableDictionary <int, string>(); dictionary.DictionaryChanged += (sender, e) => argsList.Add(e); dictionary.BeginBatch(); dictionary.Add(1, "1"); // \ dictionary.Add(2, "2"); // > collapse into [0] add dictionary.Add(3, "3"); // / dictionary.Remove(1); // \ dictionary.Remove(2); // > collapse into [1] remove dictionary.Remove(3); // / dictionary.AddRange(MakeTestPairs(1, 2, 3)); // \ dictionary.Add(4, "4"); // > collapse into [2] add dictionary.AddRange(MakeTestPairs(5, 6, 7)); // / dictionary.Remove(7); // \ dictionary.Remove(6); // > collapse into [3] reset dictionary.Clear(); // / dictionary[1] = "1"; // \ dictionary[2] = "2"; // > collapse into [4] add dictionary[3] = "3"; // / dictionary[1] = "1234"; // no collapse - [5] replace dictionary.Remove(1); // \ dictionary.Clear(); // / collapse into [6] reset Assert.AreEqual(0, argsList.Count); dictionary.EndBatch(); Assert.AreEqual(7, argsList.Count); Assert.AreEqual(NotifyCollectionChangedAction.Add, argsList[0].Action); Assert.IsTrue(Enumerable.SequenceEqual(MakeTestPairs(1, 2, 3), argsList[0].NewItems)); Assert.AreEqual(NotifyCollectionChangedAction.Remove, argsList[1].Action); Assert.IsTrue(Enumerable.SequenceEqual(MakeTestPairs(1, 2, 3), argsList[1].OldItems)); Assert.AreEqual(NotifyCollectionChangedAction.Add, argsList[2].Action); Assert.IsTrue(Enumerable.SequenceEqual(MakeTestPairs(1, 2, 3, 4, 5, 6, 7), argsList[2].NewItems)); Assert.AreEqual(NotifyCollectionChangedAction.Reset, argsList[3].Action); Assert.AreEqual(NotifyCollectionChangedAction.Add, argsList[4].Action); Assert.IsTrue(Enumerable.SequenceEqual(MakeTestPairs(1, 2, 3), argsList[4].NewItems)); Assert.AreEqual(NotifyCollectionChangedAction.Replace, argsList[5].Action); Assert.AreEqual(NotifyCollectionChangedAction.Reset, argsList[6].Action); }
/// <summary> /// Converti un Jtoken en une ObservableDictionary /// </summary> /// <param name="jTokenOeuvre">Le JToken à convertir</param> /// <returns>L'ObservableDictionary convertie</returns> private static ObservableDictionary <StringVérifié, StringVérifié> JTokenVersObservableDictionnaryString(JToken jTokenCollectionOeuvres) { var dictionnaryRetour = new ObservableDictionary <StringVérifié, StringVérifié>(); foreach (JObject j in jTokenCollectionOeuvres["infos"]) { //On vérifie qu'il n'y ait pas plusieurs informations avec le même nom if (dictionnaryRetour.ContainsKey(new StringVérifié((string)j["nomInfo"]))) { int i = 0; //Si le nom de l'information est trop grand if (new StringVérifié($"{(string)j["nomInfo"]} {i}").LeString.Length > 16) { while (dictionnaryRetour.ContainsKey(new StringVérifié($"Inconnu {i}"))) { i++; } dictionnaryRetour.Add(new StringVérifié($"Inconnu {i}"), new StringVérifié((string)j["lInfo"])); continue; } while (dictionnaryRetour.ContainsKey(new StringVérifié($"{(string)j["nomInfo"]} {i}"))) { i++; } //Si le nom de l'information est trop grand if (new StringVérifié($"{(string)j["nomInfo"]} {i}").LeString.Length > 16) { i = 0; while (dictionnaryRetour.ContainsKey(new StringVérifié($"Inconnu {i}"))) { i++; } dictionnaryRetour.Add(new StringVérifié($"Inconnu {i}"), new StringVérifié((string)j["lInfo"])); continue; } dictionnaryRetour.Add(new StringVérifié($"{(string)j["nomInfo"]} {i}"), new StringVérifié((string)j["lInfo"])); } else { dictionnaryRetour.Add(new StringVérifié((string)j["nomInfo"]), new StringVérifié((string)j["lInfo"])); } } return(dictionnaryRetour); }
public void ExpressionlessSourceManipulation() { var numbers = new ObservableDictionary <int, int>(System.Linq.Enumerable.Range(0, 10).ToDictionary(i => i)); using (var query = numbers.ActiveFirst()) { Assert.IsNull(query.OperationFault); Assert.AreEqual(0, query.Value.Value); numbers.Remove(0); Assert.AreEqual(1, query.Value.Value); numbers.Clear(); Assert.IsNotNull(query.OperationFault); Assert.AreEqual(0, query.Value.Value); numbers.Add(30, 30); Assert.IsNull(query.OperationFault); Assert.AreEqual(30, query.Value.Value); numbers.Reset(new Dictionary <int, int> { { 15, 15 } }); Assert.IsNull(query.OperationFault); Assert.AreEqual(15, query.Value.Value); numbers.Remove(15); Assert.IsNotNull(query.OperationFault); Assert.AreEqual(0, query.Value.Value); } }
public void ExpressionlessSourceManipulation() { var numbers = new ObservableDictionary <string, decimal>(); using (var aggregate = numbers.ActiveAverage()) { Assert.IsNotNull(aggregate.OperationFault); Assert.AreEqual(0, aggregate.Value); numbers.Add("1", 1m); Assert.IsNull(aggregate.OperationFault); Assert.AreEqual(1m, aggregate.Value); numbers.AddRange(System.Linq.Enumerable.Range(2, 3).ToDictionary(i => i.ToString(), i => Convert.ToDecimal(i))); Assert.AreEqual(2.5m, aggregate.Value); numbers.RemoveRange(new string[] { "1", "2" }); Assert.AreEqual(3.5m, aggregate.Value); numbers.Remove("3"); Assert.AreEqual(4m, aggregate.Value); numbers.Remove("4"); Assert.IsNotNull(aggregate.OperationFault); Assert.AreEqual(0m, aggregate.Value); numbers.Reset(System.Linq.Enumerable.Range(2, 3).ToDictionary(i => i.ToString(), i => Convert.ToDecimal(i))); Assert.IsNull(aggregate.OperationFault); Assert.AreEqual(3m, aggregate.Value); } }
public override bool ValidParams() { var flag = true; ValidetionMessages = new ObservableDictionary <string, string>(); if (!Bl.ValidBankBranch(Item.BankNumber, Item.BranchNumber)) { ValidetionMessages.Add("Bank-Branch", "Bank branch is not exist!!"); flag = false; } ////// valid if id exsisted ////if ( Mode == ViewMode.Add && !Bl.IsExiste(collectionName, Item.ID) && Item.ID =) ////{ //// ValidetionMessages.Add("id-exsist", "id alrady exsited!!"); //// flag = false; ////} //// valid if employee id exsisted //if (Bl.IsExiste(CollectionNames.Employees, Item.ID) && Mode == ViewMode.Add) //{ // ValidetionMessages.Add("employee-exsist", "employee already existed in DB!!"); // flag = false; //} return(flag); }
private void Initialize(IAlgorithm algorithm) { parameters = new ObservableDictionary <string, IItem>(); results = new ObservableDictionary <string, IItem>(); if (algorithm.StoreAlgorithmInEachRun) { var clone = (IAlgorithm)algorithm.Clone(); clone.CollectParameterValues(parameters); clone.CollectResultValues(results); clone.Runs.Clear(); this.algorithm = clone; } else { var par = new Dictionary <string, IItem>(); var res = new Dictionary <string, IItem>(); algorithm.CollectParameterValues(par); algorithm.CollectResultValues(res); var cloner = new Cloner(); foreach (var k in par) { parameters.Add(k.Key, cloner.Clone(k.Value)); } foreach (var k in res) { results.Add(k.Key, cloner.Clone(k.Value)); } } }
/// <summary> /// Called when node error changed /// </summary> /// <param name="sender">The sender.</param> /// <param name="errorArgs">The <see cref="TraceLab.Core.Experiments.ExperimentNodeErrorEventArgs"/> instance containing the event data.</param> private void OnNodeErrorChanged(object sender, ExperimentNodeErrorEventArgs errorArgs) { ExperimentNode node = sender as ExperimentNode; if (node != null) { if (errorArgs.NodeError == null) { lock (lockErrors) { m_errors.Remove(node); } } else { ExperimentNodeError nodeError; if (m_errors.TryGetValue(node, out nodeError)) { lock (lockErrors) { nodeError = errorArgs.NodeError; } } else { lock (lockErrors) { m_errors.Add(node, errorArgs.NodeError); } } } } }
public void TestAddingItems() { var items = new[] { 79, 88, 8, 61, 40, 87, 27, 18, 59, 12 }; var dict = new ObservableDictionary <int, double>(); var keys = dict.Keys; var values = keys.ListSelect(i => 1d / i); Assert.AreEqual(0, dict.Count); Assert.AreEqual(0, keys.Count); Assert.AreEqual(0, values.Count); foreach (var value in items) { dict.Add(value, 1d / value); } Assert.AreEqual(items.Length, dict.Count); Assert.AreEqual(items.Length, keys.Count); Assert.AreEqual(items.Length, values.Count); var keySet = new HashSet <int>(items); var valueSet = new HashSet <double>(items.Select(i => 1d / i)); var pairSet = new HashSet <KeyValuePair <int, double> >(items.Select(i => new KeyValuePair <int, double>(i, 1d / i)), new PairComparer <int, double>()); Assert.IsTrue(pairSet.SetEquals(dict)); Assert.IsTrue(keySet.SetEquals(keys)); Assert.IsTrue(valueSet.SetEquals(dict.Values)); Assert.IsTrue(valueSet.SetEquals(values)); }
public void AddTest() { var dictionary = new ObservableDictionary <int, string>(); DictionaryChangedEventArgs <int, string> args = null; dictionary.DictionaryChanged += (sender, e) => args = e; for (int i = 0; i < 50; i++) { args = null; dictionary.Add(i, i.ToString()); Assert.IsNotNull(args); Assert.AreEqual(NotifyCollectionChangedAction.Add, args.Action); Assert.AreEqual(1, args.NewItems.Count); Assert.AreEqual(i, args.NewItems[0].Key); Assert.AreEqual(i.ToString(), args.NewItems[0].Value); Assert.AreEqual(0, args.OldItems.Count); Assert.AreEqual(i + 1, dictionary.Count); } for (int i = 50; i < 100; i++) { args = null; dictionary[i] = i.ToString(); Assert.IsNotNull(args); Assert.AreEqual(NotifyCollectionChangedAction.Add, args.Action); Assert.AreEqual(1, args.NewItems.Count); Assert.AreEqual(i, args.NewItems[0].Key); Assert.AreEqual(i.ToString(), args.NewItems[0].Value); Assert.AreEqual(0, args.OldItems.Count); Assert.AreEqual(i + 1, dictionary.Count); } }
public void AddItem() { _handle = new EventWaitHandle(false, EventResetMode.ManualReset); var test = new ObservableDictionary<int, string>(); test.ItemAdded += Dictionary_ItemEvent; test.Add(0, "myValue"); Assert.IsTrue(_handle.WaitOne(10)); }
public MainView() { channels = new ObservableDictionary<string, ChannelViewModel>(); channels.Add("#speedrunslive", new ChannelViewModel { Title = "#speedrunslive" }); channels.Add("#bingo", new ChannelViewModel { Title = "#bingo" }); pinnedChannels = new ObservableDictionary<string, ChannelViewModel>(); pinnedChannels.Add("#speedrunslive", new ChannelViewModel { Title = "#speedrunslive" }); pinnedChannels.Add("#bingo", new ChannelViewModel { Title = "#bingo" }); messages = new ObservableCollection<Message>(); var msg = Message.ParseString(":BOB!asdf PART #speedrunslive :how's it going"); var msg1 = Message.ParseString(":BOB!asdf JOIN #speedrunslive :how's it going"); var msg2 = Message.ParseString(":BOB!asdf NOTICE #speedrunslive :how's it going"); var msg3 = Message.ParseString(":BOB!asdf PRIVMSG #bingo :how's it goingkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj"); MessageAdded(msg); MessageAdded(msg1); MessageAdded(msg2); MessageAdded(msg3); }
public void ObservableDictionaryAddItemTest() { ObservableDictionary<GenericParameterHelper, GenericParameterHelper> target = new ObservableDictionary<GenericParameterHelper, GenericParameterHelper>(); target.CollectionChanged += delegate(object sender, NotifyCollectionChangedEventArgs e) { Assert.AreEqual(NotifyCollectionChangedAction.Add, e.Action); Assert.IsNotNull(e.NewItems); }; KeyValuePair<GenericParameterHelper, GenericParameterHelper> item = new KeyValuePair<GenericParameterHelper, GenericParameterHelper>(new GenericParameterHelper(1), new GenericParameterHelper(1)); target.Add(item); Assert.AreEqual(1, target.Count); }
private Run(Run original, Cloner cloner) : base(original, cloner) { color = original.color; algorithm = cloner.Clone(original.algorithm); parameters = new ObservableDictionary<string, IItem>(); foreach (string key in original.parameters.Keys) parameters.Add(key, cloner.Clone(original.parameters[key])); results = new ObservableDictionary<string, IItem>(); foreach (string key in original.results.Keys) results.Add(key, cloner.Clone(original.results[key])); }
public void ChangeCollection() { _handle = new EventWaitHandle(false, EventResetMode.ManualReset); var test = new ObservableDictionary<int, string>(); test.Changed += Dictionary_Changed; test.Add(0, "myValue"); Assert.IsTrue(_handle.WaitOne(10), "Add() is not recognized as a change"); _handle.Reset(); test[0] = "newValue"; Assert.IsTrue(_handle.WaitOne(10), "this[] is not recognized as a change"); _handle.Reset(); test.Remove(0); Assert.IsTrue(_handle.WaitOne(10), "Remove() is not recognized as a change"); }
/// <summary> /// <para>Creates a <see cref="ObservableDictionary<string, bool>"/> that contains all available <see cref="TaskPlugin"/>s and loads their values from the settings</para> /// </summary> /// <param name="Main"></param> /// <returns></returns> public static ObservableDictionary<string, bool> GetPluginsAll(Main Main) { ObservableDictionary<string, bool> setting = GetPluginsSetting(); ObservableDictionary<string, bool> plugins = new ObservableDictionary<string, bool>(); foreach (Type task in Main.TaskMgr.TaskPluginsAvailable) { string name = task.Name; bool enabled = true; if (setting.ContainsKey(name)) enabled = setting[name]; plugins.Add(name, enabled); } return plugins; }
public void AddAddsItem() { // given var key = 1; var value = "One"; using (var observableDictionary = new ObservableDictionary<int, string>()) { // when observableDictionary.Add(key, value); // then check whether all items have been accounted for observableDictionary.Count.Should().Be(1); observableDictionary.Should().Contain(key, value); observableDictionary.Keys.Should().Contain(key); observableDictionary.Values.Should().Contain(value); } }
public void DictionaryChangesObserverExceptionsShouldBeThrownIfUnhandled() { // given using (var observableDictionary = new ObservableDictionary<int, string>()) { observableDictionary.DictionaryChanges.Subscribe(_ => { throw new InvalidOperationException("My Marker Message"); }); // when Action action = () => observableDictionary.Add(1, "One"); // then action .ShouldThrow<InvalidOperationException>() .WithMessage("My Marker Message"); } }
public void CountChangesObserverExceptionsShouldNotBeThrownIfHandledViaUnhandledObserverExceptionsObservable() { // given using (var observableDictionary = new ObservableDictionary<int, string>()) { observableDictionary.ObserverExceptions.Subscribe(observerException => { observerException.Handled = true; }); observableDictionary.CountChanges.Subscribe(_ => { throw new InvalidOperationException("My Marker Message"); }); // when Action action = () => observableDictionary.Add(1, "One"); // then action.ShouldNotThrow<InvalidOperationException>(); } }
private void Initialize(IAlgorithm algorithm) { parameters = new ObservableDictionary<string, IItem>(); results = new ObservableDictionary<string, IItem>(); if (algorithm.StoreAlgorithmInEachRun) { var clone = (IAlgorithm)algorithm.Clone(); clone.CollectParameterValues(parameters); clone.CollectResultValues(results); clone.Runs.Clear(); this.algorithm = clone; } else { var par = new Dictionary<string, IItem>(); var res = new Dictionary<string, IItem>(); algorithm.CollectParameterValues(par); algorithm.CollectResultValues(res); var cloner = new Cloner(); foreach (var k in par) parameters.Add(k.Key, cloner.Clone(k.Value)); foreach (var k in res) results.Add(k.Key, cloner.Clone(k.Value)); } }
public void NestedObservables() { _handle = new EventWaitHandle(false, EventResetMode.ManualReset); var test = new ObservableDictionary<ObservableItem, ObservableItem>(); test.ItemChanged += ObservableItemChanged; var key = new ObservableItem(); var value = new ObservableItem(); test.Add(key, value); key.ReportChange(); Assert.IsTrue(_handle.WaitOne(10), "The key is not detected as an observable"); _handle.Reset(); value.ReportChange(); Assert.IsTrue(_handle.WaitOne(10), "The value is not detected as an observable"); }
public void RemoveRaisesPropertyChangedEventForItemIndexerAndCount() { // given using (var observableDictionary = new ObservableDictionary<int, string>()) { observableDictionary.Add(1, "One"); observableDictionary.MonitorEvents(); // when observableDictionary.Remove(1); // then observableDictionary .ShouldRaise(nameof(observableDictionary.PropertyChanged)) .WithSender(observableDictionary) .WithArgs<PropertyChangedEventArgs>(args => args.PropertyName == "Item[]"); observableDictionary .ShouldRaise(nameof(observableDictionary.PropertyChanged)) .WithSender(observableDictionary) .WithArgs<PropertyChangedEventArgs>(args => args.PropertyName == nameof(observableDictionary.Count)); } }
public void AddNotifiesItemAddition(int amountOfItemsToAdd) { // given var scheduler = new TestScheduler(); var observer = scheduler.CreateObserver<IObservableDictionaryChange<int, string>>(); using (var observableDictionary = new ObservableDictionary<int, string>(scheduler: scheduler)) { // when observableDictionary.ThresholdAmountWhenChangesAreNotifiedAsReset = int.MaxValue; using (observableDictionary.DictionaryChanges.Subscribe(observer)) { var addedKeyValuePairs = new List<KeyValuePair<int, string>>(); for (int i = 0; i < amountOfItemsToAdd; i++) { var keyValuePair = new KeyValuePair<int, string>(i, $"#{i}"); observableDictionary.Add(keyValuePair.Key, keyValuePair.Value); addedKeyValuePairs.Add(keyValuePair); scheduler.AdvanceBy(1); } // then observableDictionary.Count.Should().Be(amountOfItemsToAdd); observer.Messages.Count.Should().Be(amountOfItemsToAdd); if (amountOfItemsToAdd > 0) { observer.Messages.Select(message => message.Value.Value.ChangeType).Should().OnlyContain(changeType => changeType == ObservableDictionaryChangeType.ItemAdded); observer.Messages.Select(message => message.Value.Value.Key).Should().Contain(addedKeyValuePairs.Select(kvp => kvp.Key)); observer.Messages.Select(message => message.Value.Value.Value).Should().Contain(addedKeyValuePairs.Select(kvp => kvp.Value)); } } } }
/// <summary> /// The class constructor. /// </summary> /// <param name="bench"> Reference to dynBench object for logging </param> public SearchViewModel() { SelectedIndex = 0; RevitApiSearchElements = new List<SearchElementBase>(); NodeCategories = new Dictionary<string, CategorySearchElement>(); SearchDictionary = new SearchDictionary<SearchElementBase>(); SearchResults = new ObservableCollection<SearchElementBase>(); MaxNumSearchResults = 20; Visible = Visibility.Collapsed; _SearchText = ""; IncludeRevitAPIElements = false; // revit api Regions = new ObservableDictionary<string, RegionBase>(); //Regions.Add("Include Nodes from Package Manager", DynamoCommands.PackageManagerRegionCommand ); Regions.Add("Include Experimental Revit API Nodes", new RevitAPIRegion()); _topResult = this.AddRootCategory("Top Result"); this.AddRootCategory(BuiltinNodeCategories.CORE); this.AddRootCategory(BuiltinNodeCategories.LOGIC); this.AddRootCategory(BuiltinNodeCategories.CREATEGEOMETRY); this.AddRootCategory(BuiltinNodeCategories.MODIFYGEOMETRY); this.AddRootCategory(BuiltinNodeCategories.REVIT); this.AddRootCategory(BuiltinNodeCategories.IO); this.AddRootCategory(BuiltinNodeCategories.SCRIPTING); this.AddRootCategory(BuiltinNodeCategories.ANALYZE); }
public void SynchronizeRegistryWith(ObservableDictionary<uint, VirtualRegistryKey> keyList) { if (keyList == null) throw new ArgumentNullException("keyList"); keyList.Clear(); var keys = _regDatabase.ReadAll(); foreach (var key in keys) keyList.Add(key.Handle, key); keyList.ItemAdded += Registry_ItemAdded; keyList.ItemChanged += Registry_ItemChanged; keyList.ItemRemoved += Registry_ItemRemoved; }
public void SuppressCountChangedNotificationsSuppressesCountChangedNotifications() { // given var scheduler = new TestScheduler(); var countChangesObserver = scheduler.CreateObserver<int>(); using (var observableDictionary = new ObservableDictionary<int, string>(scheduler: scheduler)) { // when observableDictionary.ThresholdAmountWhenChangesAreNotifiedAsReset = int.MaxValue; IDisposable countChangesSubscription = null; try { countChangesSubscription = observableDictionary.CountChanges.Subscribe(countChangesObserver); using (observableDictionary.SuppressCountChangeNotifications(false)) { observableDictionary.Add(1, "One"); observableDictionary.Add(2, "Two"); observableDictionary.Remove(1); observableDictionary.Remove(2); scheduler.AdvanceBy(4); } scheduler.AdvanceBy(1); // then countChangesObserver.Messages.Should().BeEmpty(); } finally { countChangesSubscription?.Dispose(); } } }
public void ShouldNotifySubscribersAboutValueChangesWhileItemsAreInDictionary() { // given var scheduler = new TestScheduler(); int key = 1; var testInpcImplementationInstance = new MyNotifyPropertyChanged<int, string>(key); var observer = scheduler.CreateObserver<IObservableDictionaryChange<int, MyNotifyPropertyChanged<int, string>>>(); var itemChangesObserver = scheduler.CreateObserver<IObservableDictionaryChange<int, MyNotifyPropertyChanged<int, string>>>(); var collectionItemChangesObserver = scheduler.CreateObserver<IObservableCollectionChange<KeyValuePair<int, MyNotifyPropertyChanged<int, string>>>>(); using (var observableDictionary = new ObservableDictionary<int, MyNotifyPropertyChanged<int, string>>(scheduler: scheduler)) { observableDictionary.ThresholdAmountWhenChangesAreNotifiedAsReset = int.MaxValue; IDisposable dictionaryChangesSubscription = null; IDisposable dictionaryItemChangesSubscription = null; IDisposable observableCollectionItemChangesSubscription = null; try { dictionaryChangesSubscription = observableDictionary.DictionaryChanges.Subscribe(observer); dictionaryItemChangesSubscription = observableDictionary.ValueChanges.Subscribe(itemChangesObserver); observableCollectionItemChangesSubscription = ((INotifyObservableCollectionItemChanges<KeyValuePair<int, MyNotifyPropertyChanged<int, string>>>)observableDictionary) .CollectionItemChanges .Subscribe(collectionItemChangesObserver); // when observableDictionary.Add(key, testInpcImplementationInstance); testInpcImplementationInstance.FirstProperty = Guid.NewGuid().ToString(); scheduler.AdvanceBy(100); // then observer.Messages.Count.Should().Be(2); itemChangesObserver.Messages.Count.Should().Be(1); collectionItemChangesObserver.Messages.Count.Should().Be(1); observer.Messages.First().Value.Value.ChangeType.Should().Be(ObservableDictionaryChangeType.ItemAdded); observer.Messages.First().Value.Value.Key.Should().Be(key); observer.Messages.First().Value.Value.Value.Should().Be(testInpcImplementationInstance); observer.Messages.Last().Value.Value.ChangeType.Should().Be(ObservableDictionaryChangeType.ItemValueChanged); observer.Messages.Last().Value.Value.Key.Should().Be(default(int)); observer.Messages.Last().Value.Value.Value.Should().Be(testInpcImplementationInstance); observer.Messages.Last().Value.Value.OldValue.Should().BeNull(); observer.Messages.Last().Value.Value.ChangedPropertyName.Should().Be(nameof(MyNotifyPropertyChanged<int, string>.FirstProperty)); itemChangesObserver.Messages.First().Value.Value.ChangeType.Should().Be(ObservableDictionaryChangeType.ItemValueChanged); itemChangesObserver.Messages.First().Value.Value.Key.Should().Be(default(int)); itemChangesObserver.Messages.First().Value.Value.Value.Should().Be(testInpcImplementationInstance); itemChangesObserver.Messages.First().Value.Value.OldValue.Should().BeNull(); itemChangesObserver.Messages.Last().Value.Value.ChangedPropertyName.Should().Be(nameof(MyNotifyPropertyChanged<int, string>.FirstProperty)); collectionItemChangesObserver.Messages.First().Value.Value.ChangeType.Should().Be(ObservableCollectionChangeType.ItemChanged); collectionItemChangesObserver.Messages.First().Value.Value.Item.Key.Should().Be(key); collectionItemChangesObserver.Messages.First().Value.Value.Item.Value.Should().Be(testInpcImplementationInstance); } finally { dictionaryChangesSubscription?.Dispose(); dictionaryItemChangesSubscription?.Dispose(); observableCollectionItemChangesSubscription?.Dispose(); } } }
/// <summary> /// Constructs a new GeomagicTouch View Model /// </summary> public GeomagicTouchViewModel() { DeviceNames = new ObservableCollection<string>(); SignalSources = new ObservableDictionary<string, SignalSourceViewModel>(); SignalSources.Add("X", new SignalSourceViewModel("X Position")); SignalSources.Add("Y", new SignalSourceViewModel("Y Position")); SignalSources.Add("Z", new SignalSourceViewModel("Z Position")); SignalSources.Add("Theta1", new SignalSourceViewModel("Gimbal Theta 1")); SignalSources.Add("Theta2", new SignalSourceViewModel("Gimbal Theta 2")); SignalSources.Add("Theta3", new SignalSourceViewModel("Gimbal Theta 3")); SignalSources.Add("Inkwell", new SignalSourceViewModel("Inkwell Switch")); SignalSources.Add("Button1", new SignalSourceViewModel("Button 1")); SignalSources.Add("Button2", new SignalSourceViewModel("Button 2")); SignalSources.Add("Button3", new SignalSourceViewModel("Button 1")); SignalSources.Add("Button4", new SignalSourceViewModel("Button 2")); TypeName = "Geomagic Touch"; // Get a list of all GeomagicTouch device names foreach(string device in GetGeomagicDevices()) { DeviceNames.Add(device); } UpdateTimer = new System.Timers.Timer(); UpdateTimer.Elapsed += UpdateTimer_Elapsed; UpdateTimer.Interval = 50; }
public void AddNotifiesCountIncrease(int lowerLimit, int upperLimit) { // given var initialList = new List<KeyValuePair<int, string>>() { new KeyValuePair<int, string>(1, "Some Value"), new KeyValuePair<int, string>(2, "Some Other Value"), new KeyValuePair<int, string>(3, "Some Totally Different Value"), }; int observableReportedCount = initialList.Count; int countChangesCalled = 0; using (var observableDictionary = new ObservableDictionary<int, string>(initialList)) { // when observableDictionary.ThresholdAmountWhenChangesAreNotifiedAsReset = int.MaxValue; observableDictionary.CountChanges.Subscribe(i => { observableReportedCount = i; countChangesCalled++; }); for (int i = lowerLimit; i <= upperLimit; i++) { observableDictionary.Add(i, $"#{i}"); } // then check whether all items have been accounted for var expectedCountChangesCalls = ((upperLimit == lowerLimit) ? 1 : (upperLimit - lowerLimit + 1)); var expectedCount = expectedCountChangesCalls + initialList.Count; observableReportedCount.Should().Be(expectedCount); // +1 because the upper for loop goes up to & inclusive the upperLimit observableReportedCount.Should().Be(observableDictionary.Count); countChangesCalled.Should().Be(expectedCountChangesCalls); } }
public void AddShouldThrowOnNullKey() { // given using (var observableDictionary = new ObservableDictionary<string, string>()) { // when Action action = () => observableDictionary.Add(null, null); // then action .ShouldThrow<ArgumentNullException>() .WithMessage("Value cannot be null.\r\nParameter name: key"); observableDictionary.Count.Should().Be(0); } }
public void CollectionChangedSubscriberExceptionsShouldBeThrownIfUnhandled() { // given using (var observableDictionary = new ObservableDictionary<int, string>()) { ((INotifyCollectionChanged)observableDictionary).CollectionChanged += (sender, args) => { throw new InvalidOperationException("My Marker Message"); }; // when Action action = () => observableDictionary.Add(1, "One"); // then action .ShouldThrow<InvalidOperationException>() .WithMessage("My Marker Message"); } }
public void ShouldNotifySubscribersAboutKeyChangesAsResetIfRequestedWhileItemsAreInDictionary() { // given var scheduler = new TestScheduler(); int value = 1; var key = new MyNotifyPropertyChanged<int, string>(value); var observer = scheduler.CreateObserver<IObservableDictionaryChange<MyNotifyPropertyChanged<int, string>, int>>(); var itemChangesObserver = scheduler.CreateObserver<IObservableDictionaryChange<MyNotifyPropertyChanged<int, string>, int>>(); var resetsObserver = scheduler.CreateObserver<Unit>(); using (var observableDictionary = new ObservableDictionary<MyNotifyPropertyChanged<int, string>, int>(scheduler: scheduler)) { observableDictionary.ThresholdAmountWhenChangesAreNotifiedAsReset = Int32.MaxValue; IDisposable dictionaryChangesSubscription = null; IDisposable dictionaryItemChangesSubscription = null; IDisposable dictionaryResetsSubscription = null; try { dictionaryChangesSubscription = observableDictionary.DictionaryChanges.Subscribe(observer); dictionaryItemChangesSubscription = observableDictionary.KeyChanges.Subscribe(itemChangesObserver); dictionaryResetsSubscription = observableDictionary.Resets.Subscribe(resetsObserver); // when observableDictionary.Add(key, value); observableDictionary.ThresholdAmountWhenChangesAreNotifiedAsReset = 0; key.FirstProperty = Guid.NewGuid().ToString(); scheduler.AdvanceBy(100); // then observer.Messages.Count.Should().Be(2); itemChangesObserver.Messages.Count.Should().Be(0); resetsObserver.Messages.Count.Should().Be(1); observer.Messages.First().Value.Value.ChangeType.Should().Be(ObservableDictionaryChangeType.ItemAdded); observer.Messages.First().Value.Value.Key.Should().Be(key); observer.Messages.First().Value.Value.Value.Should().Be(value); observer.Messages.Last().Value.Value.ChangeType.Should().Be(ObservableDictionaryChangeType.Reset); observer.Messages.Last().Value.Value.Key.Should().Be(default(MyNotifyPropertyChanged<int, string>)); observer.Messages.Last().Value.Value.Value.Should().Be(default(int)); observer.Messages.Last().Value.Value.OldValue.Should().Be(default(int)); observer.Messages.Last().Value.Value.ChangedPropertyName.Should().BeEmpty(); } finally { dictionaryChangesSubscription?.Dispose(); dictionaryItemChangesSubscription?.Dispose(); dictionaryResetsSubscription?.Dispose(); } } }
public GraphicalView() { this.DataContext = this; InitializeComponent(); Sinks = new ObservableDictionary<string, InputSignalViewModel>(); Sinks.Add("RightUpperBevel", new InputSignalViewModel("RightUpperBevel", "GraphicalView")); Sinks.Add("RightLowerBevel", new InputSignalViewModel("RightLowerBevel", "GraphicalView")); Sinks.Add("RightElbow", new InputSignalViewModel("RightElbow", "GraphicalView")); Sinks.Add("LeftUpperBevel", new InputSignalViewModel("LeftUpperBevel", "GraphicalView")); Sinks.Add("LeftLowerBevel", new InputSignalViewModel("LeftLowerBevel", "GraphicalView")); Sinks.Add("LeftElbow", new InputSignalViewModel("LeftElbow", "GraphicalView")); Sinks.Add("GrasperOpen", new InputSignalViewModel("GrasperOpen", "GraphicalView")); Sinks.Add("GrasperTwist", new InputSignalViewModel("GrasperTwist", "GraphicalView")); Sinks.Add("CauteryTwist", new InputSignalViewModel("CauteryTwist", "GraphicalView")); Sinks.Add("LeftGrasperForce", new InputSignalViewModel("LeftGrasperForce", "GraphicalView")); SetupMessenger(); Random R = new Random(); for (int i = 0; i < line_colour_array.Length; i++) { line_colour_array[i] = new Bgr(R.Next(0, 255), R.Next(0, 255), R.Next(0, 255)); } //Run(); Write_BTN.IsEnabled = false; Main_Picturebox.Size = new System.Drawing.Size(820, 820); DeviceNames = new ObservableCollection<string>(); SettingNames = new ObservableCollection<string>(); _deviceList = new FilterInfoCollection(FilterCategory.VideoInputDevice); // Get a list of all video capture source names for (int i = 0; i < _deviceList.Count; i++) { DeviceNames.Add(_deviceList[i].Name); } // paths to *.stl files string startupPath = System.IO.Directory.GetCurrentDirectory(); startupPath = startupPath + "\\3D Models\\"; this.dispatcher = Dispatcher.CurrentDispatcher; string shoulderPath = startupPath + "Shoulder.stl"; string upperRightPath = startupPath + "upperRight.stl"; string upperLeftPath = startupPath + "upperLeft.stl"; string foreRightPath = startupPath + "cauteryFore.stl"; string rightTipPath = startupPath + "cauteryHook.stl"; string foreLeftPath = startupPath + "grasperFore.stl"; string yolkPath = startupPath + "grasperYolk.stl"; string jaw1Path = startupPath + "grasperJaw1.stl"; string jaw2Path = startupPath + "grasperJaw2.stl"; string rightSpacePath = startupPath + "RightWorkspace.stl"; string leftSpacePath = startupPath + "LeftWorkspace.stl"; // Import *.stl files var up = new ModelImporter(); var shoulder = up.Load(shoulderPath, this.dispatcher); var upperRightArm = up.Load(upperRightPath, this.dispatcher); var upperLeftArm = up.Load(upperLeftPath, this.dispatcher); var foreRightArm = up.Load(foreRightPath, this.dispatcher); var tipRightArm = up.Load(rightTipPath, this.dispatcher); var foreLeftArm = up.Load(foreLeftPath, this.dispatcher); var grasperYolk = up.Load(yolkPath, this.dispatcher); var grasperJaw1 = up.Load(jaw1Path, this.dispatcher); var grasperJaw2 = up.Load(jaw2Path, this.dispatcher); var rightSpace = up.Load(rightSpacePath, this.dispatcher); var leftSpace = up.Load(leftSpacePath, this.dispatcher); // Convert to GeometryModel3d so we can rotate models GeometryModel3D SHmodel = shoulder.Children[0] as GeometryModel3D; GeometryModel3D URmodel = upperRightArm.Children[0] as GeometryModel3D; GeometryModel3D ULmodel = upperLeftArm.Children[0] as GeometryModel3D; GeometryModel3D FRmodel = foreRightArm.Children[0] as GeometryModel3D; GeometryModel3D FLmodel = foreLeftArm.Children[0] as GeometryModel3D; GeometryModel3D TRmodel = tipRightArm.Children[0] as GeometryModel3D; GeometryModel3D GYmodel = grasperYolk.Children[0] as GeometryModel3D; GeometryModel3D GJ1model = grasperJaw1.Children[0] as GeometryModel3D; GeometryModel3D GJ2model = grasperJaw2.Children[0] as GeometryModel3D; GeometryModel3D RWSmodel = rightSpace.Children[0] as GeometryModel3D; GeometryModel3D LWSmodel = leftSpace.Children[0] as GeometryModel3D; // GHOST WHITE // Set model color DiffuseMaterial material = new DiffuseMaterial(new SolidColorBrush(Colors.GhostWhite)); SHmodel.Material = material; SHmodel.BackMaterial = material; // RED // Set model color material = new DiffuseMaterial(new SolidColorBrush(Colors.Red)); FRmodel.Material = material; FRmodel.BackMaterial = material; TRmodel.Material = material; TRmodel.BackMaterial = material; // DARK RED // Set model color material = new DiffuseMaterial(new SolidColorBrush(Colors.DarkRed)); URmodel.Material = material; URmodel.BackMaterial = material; // GREEN // Set model color material = new DiffuseMaterial(new SolidColorBrush(Colors.Green)); // BLUE // Set model color material = new DiffuseMaterial(new SolidColorBrush(Colors.Blue)); GYmodel.Material = material; GYmodel.BackMaterial = material; GJ1model.Material = material; GJ1model.BackMaterial = material; GJ2model.Material = material; GJ2model.BackMaterial = material; FLmodel.Material = material; FLmodel.BackMaterial = material; // DARK BLUE // Set model color material = new DiffuseMaterial(new SolidColorBrush(Colors.DarkBlue)); ULmodel.Material = material; ULmodel.BackMaterial = material; // BLACK // Set model color material = new DiffuseMaterial(new SolidColorBrush(Colors.Black)); // TRANSPARENT RED // Set model color SolidColorBrush brushOne = new SolidColorBrush(); brushOne.Opacity = 0.50; brushOne.Color = Colors.Red; material = new DiffuseMaterial(brushOne); RWSmodel.Material = material; RWSmodel.BackMaterial = material; // TRANSPARENT BLUE // Set model color SolidColorBrush brushTwo = new SolidColorBrush(); brushTwo.Opacity = 0.50; brushTwo.Color = Colors.Blue; material = new DiffuseMaterial(brushTwo); LWSmodel.Material = material; LWSmodel.BackMaterial = material; // right shoulder rotations rsyTransform.CenterX = 0; rsyTransform.CenterY = 0; rsyTransform.CenterZ = 0; rightShoulderRotY.Axis = new Vector3D(0, 1, 0); rsxTransform.CenterX = 0; rsxTransform.CenterY = 0; rsxTransform.CenterZ = 0; rightShoulderRotX.Axis = new Vector3D(1, 0, 0); // right elbow rotations relTransform.CenterX = -13.386; relTransform.CenterY = 5; relTransform.CenterZ = 74.684; rightElbow.Axis = new Vector3D(0, 1, 0); // right tip rotations rTipTransform.CenterX = -15.111; rTipTransform.CenterY = 9.515; rTipTransform.CenterZ = 0; rightTip.Axis = new Vector3D(0, 0, 1); //left shoulder rotations lsyTransform.CenterX = 14.478; lsyTransform.CenterY = 0; lsyTransform.CenterZ = 0; leftShoulderRotY.Axis = new Vector3D(0, 1, 0); lsxTransform.CenterX = 0; lsxTransform.CenterY = 0; lsxTransform.CenterZ = 0; leftShoulderRotX.Axis = new Vector3D(1, 0, 0); // left elbow rotations lelTransform.CenterX = 27.864; lelTransform.CenterY = 0; lelTransform.CenterZ = 74.684; leftElbow.Axis = new Vector3D(0, 1, 0); // grasper rotations graspTransform.CenterX = 27.864; graspTransform.CenterY = 13.624; graspTransform.CenterZ = 0; graspOrient1.Axis = new Vector3D(0, 0, 1); jaw1Transform.CenterX = 27.864; jaw1Transform.CenterZ = 160.284; jawAngle1.Axis = new Vector3D(0, 1, 0); jaw2Transform.CenterX = 27.864; jaw2Transform.CenterZ = 160.284; jawAngle2.Axis = new Vector3D(0, 1, 0); // Define cautery tip rightTipVisual.Content = TRmodel; // Define right forearm group rightForeBodyVisual.Content = FRmodel; rightForeVisual.Children.Clear(); rightForeVisual.Children.Add(rightForeBodyVisual); rightForeVisual.Children.Add(rightTipVisual); // Define right arm group rightUpperVisual.Content = URmodel; rightVisual.Children.Clear(); rightVisual.Children.Add(rightUpperVisual); rightVisual.Children.Add(rightForeVisual); // Left grasper open/close jawOneVisual.Content = GJ1model; jawTwoVisual.Content = GJ2model; // Define grasper group yolkVisual.Content = GYmodel; grasperVisual.Children.Clear(); grasperVisual.Children.Add(yolkVisual); grasperVisual.Children.Add(jawOneVisual); grasperVisual.Children.Add(jawTwoVisual); // Define left forearm group leftForeBodyVisual.Content = FLmodel; leftForeVisual.Children.Clear(); leftForeVisual.Children.Add(leftForeBodyVisual); leftForeVisual.Children.Add(grasperVisual); // Define left arm group leftUpperVisual.Content = ULmodel; leftVisual.Children.Clear(); leftVisual.Children.Add(leftUpperVisual); leftVisual.Children.Add(leftForeVisual); // workspace rightSpaceVisual.Content = RWSmodel; leftSpaceVisual.Content = LWSmodel; staticVisual.Children.Clear(); staticVisual.Children.Add(rightSpaceVisual); staticVisual.Children.Add(leftSpaceVisual); // Add left and right arms to full model wholeModel.Content = SHmodel; wholeModel.Children.Clear(); wholeModel.Children.Add(rightVisual); wholeModel.Children.Add(leftVisual); // wholeModel.Children.Add(staticVisual); DisplayModel(); }
private void cmdOnlineView_Click(object sender, RoutedEventArgs e) { try { var btn = sender as ToggleButton; if (btn.IsChecked.Value) { _connectionDictionary = new ObservableDictionary<string, PLCConnection>(); var conns = from rw in varTabRows group rw by rw.ConnectionName; foreach (var conn in conns) { if (!string.IsNullOrEmpty(conn.Key)) _connectionDictionary.Add(conn.Key, new PLCConnection(conn.Key)); } if (!string.IsNullOrEmpty(DefaultConnection) && !_connectionDictionary.ContainsKey(DefaultConnection)) _connectionDictionary.Add(DefaultConnection, new PLCConnection(DefaultConnection)); lblStatus.Content = ""; foreach (var varTabRowWithConnection in varTabRows) { //Register Notify Changed Handler vor <connected Property var conn = varTabRowWithConnection.Connection; if (conn != null) conn.Configuration.ConnectionName = conn.Configuration.ConnectionName; } Parallel.ForEach(_connectionDictionary, plcConnection => { try { plcConnection.Value.AutoConnect = false; plcConnection.Value.Connect(); } catch (Exception ex) { } }); var st = new ThreadStart(BackgroundReadingProc); BackgroundReadingThread = new Thread(st); BackgroundReadingThread.Name = "Background Reading Thread"; BackgroundReadingThread.Start(); ProgressBarOnlineStatus.IsIndeterminate = true; IsOnline = true; } else { this.StopOnlineView(); } } catch(Exception ex) { lblStatus.Content = ex.Message; } }
/// <summary> /// The class constructor. /// </summary> /// <param name="bench"> Reference to dynBench object for logging </param> public SearchViewModel() { SelectedIndex = 0; RevitApiSearchElements = new List<SearchElementBase>(); NodeCategories = new Dictionary<string, CategorySearchElement>(); SearchDictionary = new SearchDictionary<SearchElementBase>(); SearchResults = new ObservableCollection<SearchElementBase>(); MaxNumSearchResults = 100; Visible = Visibility.Collapsed; _SearchText = ""; IncludeOptionalElements = false; // revit api Regions = new ObservableDictionary<string, RegionBase>(); //Regions.Add("Include Nodes from Package Manager", DynamoCommands.PackageManagerRegionCommand ); Regions.Add("Include Experimental Revit API Nodes", new RevitAPIRegion()); AddHomeToSearch(); AddCommandElements(); }
public void ShouldNotNotifySubscribersAboutValueChangesAfterItemsAreRemovedFromDictionary() { // given var scheduler = new TestScheduler(); int key = 1; var testInpcImplementationInstance = new MyNotifyPropertyChanged<int, string>(key); var observer = scheduler.CreateObserver<IObservableDictionaryChange<int, MyNotifyPropertyChanged<int, string>>>(); var itemChangesObserver = scheduler.CreateObserver<IObservableDictionaryChange<int, MyNotifyPropertyChanged<int, string>>>(); using (var observableDictionary = new ObservableDictionary<int, MyNotifyPropertyChanged<int, string>>(scheduler: scheduler)) { observableDictionary.ThresholdAmountWhenChangesAreNotifiedAsReset = int.MaxValue; IDisposable dictionaryChangesSubscription = null; IDisposable dictionaryItemChangesSubscription = null; try { dictionaryChangesSubscription = observableDictionary.DictionaryChanges.Subscribe(observer); dictionaryItemChangesSubscription = observableDictionary.ValueChanges.Subscribe(itemChangesObserver); // when observableDictionary.Add(key, testInpcImplementationInstance); // first general message - ItemAdd testInpcImplementationInstance.FirstProperty = Guid.NewGuid().ToString(); // second general / first item change message - ItemChanged observableDictionary.Remove(key); // third general message - ItemRemoved testInpcImplementationInstance.SecondProperty = Guid.NewGuid().ToString(); // should no longer be observable on/via dictionary scheduler.AdvanceBy(100); // then observer.Messages.Count.Should().Be(3); observer.Messages[0].Value.Value.ChangeType.Should().Be(ObservableDictionaryChangeType.ItemAdded); observer.Messages[0].Value.Value.Key.Should().Be(key); observer.Messages[0].Value.Value.Value.Should().Be(testInpcImplementationInstance); observer.Messages[1].Value.Value.ChangeType.Should().Be(ObservableDictionaryChangeType.ItemValueChanged); observer.Messages[1].Value.Value.Key.Should().Be(default(int)); observer.Messages[1].Value.Value.Value.Should().Be(testInpcImplementationInstance); observer.Messages[1].Value.Value.OldValue.Should().BeNull(); observer.Messages[1].Value.Value.ChangedPropertyName.Should().Be(nameof(MyNotifyPropertyChanged<int, string>.FirstProperty)); observer.Messages[2].Value.Value.ChangeType.Should().Be(ObservableDictionaryChangeType.ItemRemoved); observer.Messages[2].Value.Value.Key.Should().Be(key); observer.Messages[2].Value.Value.Value.Should().Be(testInpcImplementationInstance); itemChangesObserver.Messages.Count.Should().Be(1); itemChangesObserver.Messages.First().Value.Value.ChangeType.Should().Be(ObservableDictionaryChangeType.ItemValueChanged); itemChangesObserver.Messages.First().Value.Value.Key.Should().Be(default(int)); itemChangesObserver.Messages.First().Value.Value.Value.Should().Be(testInpcImplementationInstance); itemChangesObserver.Messages.First().Value.Value.OldValue.Should().BeNull(); itemChangesObserver.Messages.First().Value.Value.ChangedPropertyName.Should().Be(nameof(MyNotifyPropertyChanged<int, string>.FirstProperty)); } finally { dictionaryChangesSubscription?.Dispose(); dictionaryItemChangesSubscription?.Dispose(); } } }
public void AddShouldNotThrowOnDefaultValue() { // given using (var observableDictionary = new ObservableDictionary<string, string>()) { // when Action action = () => observableDictionary.Add("1", default(string)); // then action.ShouldNotThrow<ArgumentNullException>(); observableDictionary.Count.Should().Be(1); } }
public void AddNotifiesAdditionAsResetIfRequested(int amountOfItemsToAdd) { // given var scheduler = new TestScheduler(); var dictionaryChangesObserver = scheduler.CreateObserver<IObservableDictionaryChange<int, string>>(); var resetsObserver = scheduler.CreateObserver<Unit>(); using (var observableDictionary = new ObservableDictionary<int, string>(scheduler: scheduler)) { // when observableDictionary.ThresholdAmountWhenChangesAreNotifiedAsReset = 0; using (observableDictionary.DictionaryChanges.Subscribe(dictionaryChangesObserver)) { using (observableDictionary.Resets.Subscribe(resetsObserver)) { var addedKeyValuePairs = new List<KeyValuePair<int, string>>(); for (int i = 0; i < amountOfItemsToAdd; i++) { var keyValuePair = new KeyValuePair<int, string>(i, $"#{i}"); observableDictionary.Add(keyValuePair.Key, keyValuePair.Value); addedKeyValuePairs.Add(keyValuePair); scheduler.AdvanceBy(2); } // then observableDictionary.Count.Should().Be(amountOfItemsToAdd); dictionaryChangesObserver.Messages.Count.Should().Be(amountOfItemsToAdd); resetsObserver.Messages.Count.Should().Be(amountOfItemsToAdd); if (amountOfItemsToAdd > 0) { dictionaryChangesObserver.Messages.Select(message => message.Value.Value.ChangeType).Should().OnlyContain(changeType => changeType == ObservableDictionaryChangeType.Reset); dictionaryChangesObserver.Messages.Select(message => message.Value.Value.Key).Should().Match(ints => ints.All(@int => Equals(default(int), @int))); dictionaryChangesObserver.Messages.Select(message => message.Value.Value.Value).Should().Match(strings => strings.All(@string => Equals(default(string), @string))); } } } } }