public void RecordCalculatedResults(string k1, string k2, decimal pr) { if (calculatedResults.ContainsKey(k1)) { var innerDictionary = calculatedResults[k1]; if (innerDictionary.ContainsKey(k2)) { throw new NotSupportedException("This pattern expects only one entry per k1k2 pair"); } else { //ToDo: Better understanding/handling of exceptions here try { innerDictionary.Add(k2, pr); } catch { new Exception($"adding {pr} to {k1}'s innerDictionary keyed by {k2} failed"); } } } else { var innerDictionary = new ConcurrentObservableDictionary <string, decimal>(); try { innerDictionary.Add(k2, pr); } catch { new Exception($"adding {pr} to the new innerDictionary keyed by {k2} failed"); } try { calculatedResults.Add(k1, innerDictionary); } catch { new Exception($"adding the new innerDictionary to calculatedResults keyed by {k1} failed"); } }; }
public void Test_ConcurrentObservableCollection_RemoveRange_ByItems_IEnumerable() { var initial = Enumerable.Range(0, 100).Select(x => new KeyValuePair <int, int>(x, x)); var toRemove = Enumerable.Range(1, 40).Select(x => x * 2); var collection = new ConcurrentObservableDictionary <int, int>(); collection.AddRange(initial); Assert.AreEqual(100, collection.Count); // Record all the collection changed events List <(object, NotifyCollectionChangedEventArgs)> returnedList = new List <(object, NotifyCollectionChangedEventArgs)>(); collection.CollectionChanged += (s, e) => returnedList.Add((s, e)); collection.RemoveRange(toRemove); // Check just one collection changed event was fired Assert.AreEqual(1, returnedList.Count); (var returnedObject, var returnedArgs) = returnedList[0]; Assert.IsNotNull(returnedObject); Assert.IsNotNull(returnedArgs); Assert.AreEqual(returnedObject, collection); Assert.AreEqual(NotifyCollectionChangedAction.Remove, returnedArgs.Action); Assert.AreEqual(-1, returnedArgs.OldStartingIndex); Assert.IsNull(returnedArgs.NewItems); Assert.IsNotNull(returnedArgs.OldItems); Assert.AreEqual(toRemove.Count(), returnedArgs.OldItems.Count); Assert.IsTrue(CollectionsAreEqual(toRemove, returnedArgs.OldItems)); }
public void Test_ConcurrentObservableDictionary_Clear() { var initial = Enumerable.Range(0, 100).Select(x => new KeyValuePair <int, int>(x, x)); var collection = new ConcurrentObservableDictionary <int, int>(); collection.AddRange(initial); Assert.AreEqual(100, collection.Count); // Record all the collection changed events List <(object, NotifyCollectionChangedEventArgs)> returnedList = new List <(object, NotifyCollectionChangedEventArgs)>(); collection.CollectionChanged += (s, e) => returnedList.Add((s, e)); collection.Clear(); // Check just one collection changed event was fired Assert.AreEqual(1, returnedList.Count); (var returnedObject, var returnedArgs) = returnedList[0]; Assert.AreEqual(0, collection.Count); Assert.AreEqual(returnedObject, collection); Assert.AreEqual(NotifyCollectionChangedAction.Remove, returnedArgs.Action); Assert.IsNull(returnedArgs.NewItems); Assert.IsNotNull(returnedArgs.OldItems); Assert.AreEqual(initial.Count(), returnedArgs.OldItems.Count); Assert.IsTrue(initial.Zip(returnedArgs.OldItems.OfType <KeyValuePair <int, int> >(), (a, b) => a.Key == b.Key && a.Value == b.Value).All(c => c)); }
public ComputerHardware(MainBoard mainBoard, IList <CPUMaker> cPUs, ConcurrentObservableDictionary <Id <DiskDriveInfoEx>, DiskDriveInfoEx> diskDriveInfoExCOD, TimeBlock moment) { MainBoard = mainBoard ?? throw new ArgumentNullException(nameof(mainBoard)); CPUs = cPUs ?? throw new ArgumentNullException(nameof(cPUs)); DiskDriveInfoExCOD = diskDriveInfoExCOD ?? throw new ArgumentNullException(nameof(diskDriveInfoExCOD)); Moment = moment ?? throw new ArgumentNullException(nameof(moment)); }
public void TestRemovePartialEvents() { var data = new ConcurrentObservableDictionary <string, double>(); var obs = new SimpleObserver(); data.AddPartialObserver(obs, "test", "test2", "test3"); data.AddOrUpdate("test", 1.0); Assert.AreEqual(1.0, obs.LastValue, "Error in test key"); Assert.IsTrue(data.RemovePartialObserver(obs, "test").All( pair => pair.Key == "test" && pair.Value.Count == 1 && pair.Value.Contains(obs)), "remove <obs, test>"); data.AddOrUpdate("test", 10.0); Assert.AreEqual(1.0, obs.LastValue, "Error in test key after remove <obs, test>"); Assert.IsTrue(data.RemovePartialObserver("test3").All(pair => pair.Key == "test3"), "remove test3 key"); data.AddOrUpdate("test3", 30.0); Assert.AreEqual(1.0, obs.LastValue, "Error in test3 key after remove test3 key"); data.AddOrUpdate("test2", 2.0); Assert.AreEqual(2.0, obs.LastValue, "Error in test2 key"); Assert.IsTrue(data.RemovePartialObserver(obs).All( pair => pair.Value.Count == 1 && pair.Value.Contains(obs)), "remove obs"); data.AddOrUpdate("test2", 20.0); Assert.AreEqual(2.0, obs.LastValue, "Error in test2 key after remove obs"); }
// Access the Logging extensions registered in the DI container //[Inject] //public ILogger<BaseServicesCodeBehind> Log { get; set; } //[Inject] //protected SessionStorage sessionStorage; //[Inject] //protected LocalStorage localStorage; #endregion #region Page Initialization Handler protected override async Task OnInitAsync() { //Log.LogDebug($"Starting OnInitAsync"); ////Log.LogDebug($"Initializing IServiceClient"); ////IServiceClient client = new JsonHttpClient("http://localhost:21100"); ////Log.LogDebug($"client is null: {client == null}"); /* // from teh stateless statemachine compiler project * const string on = "On"; * const string off = "Off"; * const char space = ' '; * var onOffSwitch = new StateMachine<string, char>(off); * onOffSwitch.Configure(off).Permit(space, on); * onOffSwitch.Configure(on).Permit(space, off); */ var initializationRequest = new InitializationRequest(new InitializationRequestPayload(new InitializationData("BaseVersionXX", "MachineIDXX", "userIDxx"))); //Log.LogDebug($"Calling PostJsonAsync<InitializationResponse> with InitializationRequest = {InitializationRequest}"); InitializationResponse = await HttpClient.PostJsonAsync <InitializationResponse>("/BaseServicesInitialization", initializationRequest); //Log.LogDebug($"Returned from PostJsonAsync<InitializationResponse>, InitializationResponse = {InitializationResponse}"); ConfigurationData = InitializationResponse.InitializationResponsePayload.ConfigurationData; UserData = InitializationResponse.InitializationResponsePayload.UserData; PartitionInfoExs = new PartitionInfoExs(); LongRunningTasksCOD = new ConcurrentObservableDictionary <Id <LongRunningTaskInfo>, LongRunningTaskStatus>(); //Log.LogDebug($"Leaving OnInitAsync"); }
public void AddRangeTest() { // There was an issue with ConcurrentObservableDictionary.AddMany throwing an // exception when passed an IEnumerable. IEnumerable <KeyValuePair <string, string> > GetIEnumerable() { for (int i = 0; i < 10; ++i) { yield return(new KeyValuePair <string, string>(i.ToString(), i.ToString())); } } var itemsToAdd = GetIEnumerable(); var dictionary1 = new ConcurrentObservableDictionary <string, string>(); dictionary1.AddRange(itemsToAdd); Assert.IsTrue(dictionary1.Count == itemsToAdd.Count(), "Right number of items"); var sourceDictionary = itemsToAdd.ToDictionary(a => a.Key, b => b.Value); var dictionary2 = new ConcurrentObservableDictionary <string, string>(); dictionary2.AddRange(sourceDictionary); Assert.IsTrue(dictionary2.Count == sourceDictionary.Count, "Right number of items"); }
internal void MinerGPUSerializeToJSON(string _testdatainput) { var hrpc = new ConcurrentObservableDictionary <Coin, HashRate>() { { Coin.ETH, new HashRate(20.0, new TimeSpan(0, 0, 1)) } }; VideoCardSignil vcdc = VideoCardsKnown.TuningParameters.Keys.Where(x => (x.VideoCardMaker == VideoCardMaker.ASUS && x.GPUMaker == GPUMaker.NVIDEA)) .Single(); MinerGPU minerGPU = new MinerGPU(vcdc, "10DE 17C8 - 3842", "100.00001.02320.00", false, 1140, 1753, 11.13, 0.8, hrpc); var str = JsonConvert.SerializeObject(minerGPU); str.Should() .NotBeNull(); str.Should() .Be(_testdatainput); }
public void RecordR(string k1, string k2, decimal pr) { if (ResultsCOD.ContainsKey(k1)) { var innerCOD = ResultsCOD[k1]; if (innerCOD.ContainsKey(k2)) { throw new NotSupportedException("This pattern expects only one entry per k1k2 pair"); } else { //ToDo: Better understanding/handling of exceptions here try { innerCOD.Add(k2, pr); } catch { new Exception($"adding {pr} to {k1}'s innerDictionary keyed by {k2} failed"); } } } else { var innerCOD = new ConcurrentObservableDictionary <string, decimal>(); if (this.onResultsNestedCODCollectionChanged != null) { innerCOD.CollectionChanged += this.onResultsNestedCODCollectionChanged; } if (this.onResultsNestedCODPropertyChanged != null) { innerCOD.PropertyChanged += this.onResultsNestedCODPropertyChanged; } try { innerCOD.Add(k2, pr); } catch { new Exception($"adding {pr} to the new innerDictionary keyed by {k2} failed"); } try { ResultsCOD.Add(k1, innerCOD); } catch { new Exception($"adding the new innerDictionary to cODR keyed by {k1} failed"); } }; }
public WithObservableConcurrentDictionaryAndEventHandlers(NotifyCollectionChangedEventHandler OnCollectionChanged, NotifyCollectionChangedEventHandler OnNestedCollectionChanged) { calculatedResults = new ConcurrentObservableDictionary <string, ConcurrentObservableDictionary <string, decimal> >(); this.onCollectionChanged = OnCollectionChanged; this.onNestedCollectionChanged = OnNestedCollectionChanged; calculatedResults.CollectionChanged += onCollectionChanged; }
// constructor with event handlers public RealEstateServicesData(IAppHost appHost, ConcurrentObservableDictionary <string, decimal> pluginRootCOD, NotifyCollectionChangedEventHandler onPluginRootCODCollectionChanged, PropertyChangedEventHandler onPluginRootCODPropertyChanged) { cacheClient = appHost.GetContainer().Resolve <ICacheClient>(); PluginRootCOD = pluginRootCOD; this.onPluginRootCODCollectionChanged = onPluginRootCODCollectionChanged; this.onPluginRootCODPropertyChanged = onPluginRootCODPropertyChanged; pluginRootCOD.CollectionChanged += this.onPluginRootCODCollectionChanged; pluginRootCOD.PropertyChanged += this.onPluginRootCODPropertyChanged; }
//public ConcurrentObservableDictionary<Id<LongRunningTaskInfo>, FileInfoExs> FileInfoExCOD { get; set; } //public ConcurrentObservableDictionary<Id<LongRunningTaskInfo>, (Id<DirectoryInfoEx>, Id<FileInfoEx>)> EdgeFileInfoExDirectoryInfoExCOD { get; set; } //public ConcurrentObservableDictionary<Id<LongRunningTaskInfo>, (Id<DirectoryInfoEx>, Id<DirectoryInfoEx>)> EdgeDirectoryInfoExDirectoryInfoExCOD { get; set; } void ConstructFileSystemAnalysisData() { LookupFileSystemAnalysisResultsCOD = new ConcurrentObservableDictionary <Id <LongRunningTaskInfo>, LongRunningTaskInfo>(); AnalyzeFileSystemResultsCOD = new ConcurrentObservableDictionary <Id <LongRunningTaskInfo>, IAnalyzeFileSystemResult>(); AnalyzeFileSystemProgressCOD = new ConcurrentObservableDictionary <Id <LongRunningTaskInfo>, IAnalyzeFileSystemProgress>(); //DirectoryInfoExCOD =new ConcurrentObservableDictionary<Id<LongRunningTaskInfo>, DirectoryInfoExs>(); //FileInfoExCOD=new ConcurrentObservableDictionary<Id<LongRunningTaskInfo>, FileInfoExs>(); //EdgeFileInfoExDirectoryInfoExCOD=new ConcurrentObservableDictionary<Id<LongRunningTaskInfo>, (Id<DirectoryInfoEx>, Id<FileInfoEx>)>(); //EdgeDirectoryInfoExDirectoryInfoExCOD=new ConcurrentObservableDictionary<Id<LongRunningTaskInfo>, (Id<DirectoryInfoEx>, Id<DirectoryInfoEx>)>(); }
public void TestEvents() { var data = new ConcurrentObservableDictionary <string, double>(); var updated = false; data.CollectionChanged += (s, e) => { updated = true; }; data.AddOrUpdate("test", 1.0); Assert.IsTrue(updated); }
/// <summary> /// Constructeur initialisant les listes de noeuds et clients et générant les TaskExecutor infrastructure /// </summary> /// <param name="name">Nom Orchestrateur</param> /// <param name="address">Adresse IP de l'orchestrateur</param> /// <param name="port">Port d'écoute</param> protected Orchestrator(string name, string address, int port) : base(name, address, port) { Logger = new Logger(true); unidentifiedNodes = new List <Tuple <int, Node> >(); Nodes = new ConcurrentObservableDictionary <string, Node>(); Clients = new ConcurrentDictionary <string, Node>(); TaskDistrib = new ConcurrentDictionary <int, Tuple <ConcurrentBag <int>, bool> >(); WorkerFactory.AddWorker(IdentMethod, new TaskExecutor(this, IdentNode, null, null)); WorkerFactory.AddWorker(GetCpuMethod, new TaskExecutor(this, ProcessCpuStateOrder, null, null)); WorkerFactory.AddWorker(TaskStatusMethod, new TaskExecutor(this, RefreshTaskState, null, null)); }
public void TestAddPartialEvents() { var data = new ConcurrentObservableDictionary <string, double>(); var obs = new SimpleObserver(); data.AddPartialObserver(obs, "test", "test2"); data.AddOrUpdate("test", 1.0); Assert.AreEqual(1.0, obs.LastValue, "Error in test key"); data.AddOrUpdate("test2", 10.0); Assert.AreEqual(10.0, obs.LastValue, "Error in test2 key"); }
public void TestAddPartialEventsByAction() { var data = new ConcurrentObservableDictionary <string, double>(); var ret = 0.0; data.AddPartialObserver(args => ret = args.NewValue, "test", "test2"); data.AddOrUpdate("test", 1.0); Assert.AreEqual(1.0, ret, "Error in test key"); data.AddOrUpdate("test2", 10.0); Assert.AreEqual(10.0, ret, "Error in test2 key"); }
public MinerStatusDetailsAbstract(ConcurrentObservableDictionary <int, Ratio> perGPUFanPct, ConcurrentObservableDictionary <int, ConcurrentObservableDictionary <Coin, double> > perGPUPerCoinHashRate, ConcurrentObservableDictionary <int, Power> perGPUPowerConsumption, ConcurrentObservableDictionary <int, Temperature> perGPUTemperature, string runningTime, ConcurrentObservableDictionary <Coin, double> totalPerCoinHashRate, ConcurrentObservableDictionary <Coin, int> totalPerCoinInvalidShares, ConcurrentObservableDictionary <Coin, int> totalPerCoinPoolSwitches, ConcurrentObservableDictionary <Coin, int> totalPerCoinRejectedShares, ConcurrentObservableDictionary <Coin, int> totalPerCoinShares, string version) { PerGPUFanPct = perGPUFanPct ?? throw new ArgumentNullException(nameof(perGPUFanPct)); PerGPUPerCoinHashRate = perGPUPerCoinHashRate ?? throw new ArgumentNullException(nameof(perGPUPerCoinHashRate)); PerGPUPowerConsumption = perGPUPowerConsumption ?? throw new ArgumentNullException(nameof(perGPUPowerConsumption)); PerGPUTemperature = perGPUTemperature ?? throw new ArgumentNullException(nameof(perGPUTemperature)); RunningTime = runningTime ?? throw new ArgumentNullException(nameof(runningTime)); TotalPerCoinHashRate = totalPerCoinHashRate ?? throw new ArgumentNullException(nameof(totalPerCoinHashRate)); TotalPerCoinInvalidShares = totalPerCoinInvalidShares ?? throw new ArgumentNullException(nameof(totalPerCoinInvalidShares)); TotalPerCoinPoolSwitches = totalPerCoinPoolSwitches ?? throw new ArgumentNullException(nameof(totalPerCoinPoolSwitches)); TotalPerCoinRejectedShares = totalPerCoinRejectedShares ?? throw new ArgumentNullException(nameof(totalPerCoinRejectedShares)); TotalPerCoinShares = totalPerCoinShares ?? throw new ArgumentNullException(nameof(totalPerCoinShares)); Version = version ?? throw new ArgumentNullException(nameof(version)); }
// constructor with event handlers public DiskAnalysisServicesData(IAppHost appHost, ConcurrentObservableDictionary <string, decimal> pluginRootCOD, NotifyCollectionChangedEventHandler onPluginRootCODCollectionChanged, PropertyChangedEventHandler onPluginRootCODPropertyChanged) { cacheClient = appHost.GetContainer().Resolve <ICacheClient>(); BaseServicesData = appHost.GetContainer().Resolve <BaseServicesData>(); PluginRootCOD = pluginRootCOD; this.onPluginRootCODCollectionChanged = onPluginRootCODCollectionChanged; this.onPluginRootCODPropertyChanged = onPluginRootCODPropertyChanged; pluginRootCOD.CollectionChanged += this.onPluginRootCODCollectionChanged; pluginRootCOD.PropertyChanged += this.onPluginRootCODPropertyChanged; // ToDo: Get the Configuration data into the COD, and populate it from "plugin configuration data load" ConstructConfigurationData(); ConstructUserData(); ConstructDiskDriveAnalysisData(); ConstructFileSystemAnalysisData(); }
private void Button_Click(object sender, RoutedEventArgs e) { Messages.Add("Testing BinaryFormatter..."); var list = new ConcurrentObservableCollection <string>(); var dictionary = new ConcurrentObservableDictionary <string, string>(); var sortedDictionary = new ConcurrentObservableSortedDictionary <string, string>(); InitializeList(list, 20); TestSerializingObject(list); InitializeDictionary(dictionary, 20); TestSerializingObject(dictionary); InitializeDictionary(sortedDictionary, 20); TestSerializingObject(sortedDictionary); Messages.Add("Done"); }
public void TestClearCache() { var data = new ConcurrentObservableDictionary <string, double>(); var obs = new SimpleObserver(); data.AddPartialObserver(obs, "test", "test2", "test3"); data.AddOrUpdate("test", 2.0); data.AddOrUpdate("test2", 12.0); data.AddOrUpdate("test3", 32.0); Assert.IsFalse(data.IsEmpty, "data is empty"); data.Clear(); Assert.IsTrue(data.IsEmpty, "data is not empty"); }
public void ConcurrentObservableDictionarySerializationTest() { var serializer = new BinaryFormatter(); var stream = new MemoryStream(); var collection = new ConcurrentObservableDictionary <string, int>(); for (int i = 0; i < 10; i++) { collection.Add("TestItem" + (i + 1).ToString(), i); } serializer.Serialize(stream, collection); stream.Position = 0; collection = serializer.Deserialize(stream) as ConcurrentObservableDictionary <string, int>; for (int i = 0; i < 10; i++) { Assert.AreEqual(i, collection["TestItem" + (i + 1).ToString()]); } }
public TransientBuffer(KeySignature <string> sig, DynamicBuffers parent) : base(parent._parent._calculateAndStoreFromInputAndAsyncTermsOptions) { Log.Trace("Constructor Starting"); this._parent = parent; Log.Trace($"ElementSet: {sig.Longest().ToString()}"); Log.Trace("Creating _buffer"); _buffer = new BufferBlock <IInternalMessage <string> >(); Log.Trace("Registering _buffer"); RegisterChild(_buffer); // critical section // iterate each individual element of the sig, and get those that are not already present in the COD FetchingIndividualElementsOfTerm1 foreach (var element in sig.IndividualElements) { if (!parent._parent._calculateAndStoreFromInputAndAsyncTermsObservableData.FetchingIndividualElementsOfTerm1.ContainsKey(element)) { // For each element that is not already being fetched, start the async task to fetch it Log.Trace($"Fetching AsyncWebGet for {element} and storing the task in FetchingIndividualElementsOfTerm1 indexed by {element}"); // call the async function that fetches the information for each individual element in the elementSet // record the individual element and it's corresponding task in the FetchingIndividualElementsOfTerm1 parent._parent._calculateAndStoreFromInputAndAsyncTermsObservableData.FetchingIndividualElementsOfTerm1[element] = parent._parent._webGet.AsyncWebGet <double>(element); } } // Record into FetchingElementSetsOfTerm1 the sig.Longest as key, and for the data, // create a COD whose keys are the keys of sig.IndividualElements in the FetchingElementSetsOfTerm1 Log.Trace("Creating new concurrent dictionary"); var x = new ConcurrentObservableDictionary <string, byte>(); foreach (var element in sig.IndividualElements) { Log.Trace($"Creating an entry for {element}"); x[element] = default; } Log.Trace($"Creating an entry for FetchingElementSetsOfTerm1. Key is {sig.Longest()} data is x"); parent._parent._calculateAndStoreFromInputAndAsyncTermsObservableData.FetchingElementSetsOfTerm1[sig.Longest()] = x; // If the asyncFetchCheckTimer is not enabled, enable it now. if (!parent._parent.asyncFetchCheckTimer.Enabled) { parent._parent.asyncFetchCheckTimer.Enabled = true; } Log.Trace("Constructor Finished"); }
public ClaymoreMinerStatusDetails(string str) { string version; TimeBlock runningTime; ConcurrentObservableDictionary <Coin, double> totalPerCoinHashRate = new ConcurrentObservableDictionary <Coin, double>(); ConcurrentObservableDictionary <Coin, int> totalPerCoinShares = new ConcurrentObservableDictionary <Coin, int>(); ConcurrentObservableDictionary <Coin, int> totalPerCoinRejectedShares = new ConcurrentObservableDictionary <Coin, int>(); ConcurrentObservableDictionary <Coin, int> totalPerCoinInvalidShares = new ConcurrentObservableDictionary <Coin, int>(); ConcurrentObservableDictionary <Coin, int> totalPerCoinPoolSwitches = new ConcurrentObservableDictionary <Coin, int>(); ConcurrentObservableDictionary <int, ConcurrentObservableDictionary <Coin, double> > perGPUPerCoinHashRate = new ConcurrentObservableDictionary <int, ConcurrentObservableDictionary <Coin, double> >(); ConcurrentObservableDictionary <int, Temperature> perGPUTemperature = new ConcurrentObservableDictionary <int, Temperature>(); ConcurrentObservableDictionary <int, Ratio> perGPUFanPct = new ConcurrentObservableDictionary <int, Ratio>(); ConcurrentObservableDictionary <int, Power> perGPUPowerConsumption = new ConcurrentObservableDictionary <int, Power>(); string rEClaymoreMinerStatusResultDetails = "^\"(?<Version>.*?),\\s+\"(?<RunningTime>.*?)\",\\s+\"(?<TotalETHHashRate>.*?);(?<TotalETHShares>.*?);(?<TotalETHRejectedShares>.*?)\",\\s+\"(?<PerGPUETHHashRate>.*?)\",\\s+\"(?<TotalSecondaryHashRate>.*?);(?<TotalSecondaryShares>.*?);(?<TotalSecondaryRejectedShares>.*?)\",\\s+\"(?<PerGPUSecondaryHashRate>.*?)\",\\s+\"(?<PerGPUTempFanPair>.*?)\",\\s+\"(?<CurrentMiningPools>.*?)\",\\s+\"(?<TotalETHInvalidShares>.*?);(?<TotalETHPoolSwitches>.*?);(?<TotalSecondaryInvalidShares>.*?);(?<TotalSecondaryPoolSwitches>.*?)\""; Regex RE1 = new Regex(rEClaymoreMinerStatusResultDetails, RegexOptions.IgnoreCase); MatchCollection matches = RE1.Matches(str); if (matches.Count == 0) { throw new ArgumentException($"Unable to match as a status response detailed: {str}"); } foreach (Match match in matches) { GroupCollection groups = match.Groups; version = groups["Version"].Value ?? throw new ArgumentNullException(nameof(version)); if (groups["RunningTime"].Value is null) { throw new ArgumentNullException(nameof(runningTime)); } runningTime = new TimeBlock(DateTime.Parse(groups["RunningTime"].Value)); /* * * // Version = new Regex(@"(\d|\.)+", RegexOptions.IgnoreCase).Matches; * // Coin = groups["Version"].Value ?? throw new ArgumentNullException(nameof(Coin)); * RunningTime = groups["RunningTime"].Value ?? throw new ArgumentNullException(nameof(RunningTime)); */ } }
public void ConcurrentObservableDictionaryTest() { ConcurrentObservableDictionary <int, string> dict = new ConcurrentObservableDictionary <int, string>(); var times = 0; dict.CollectionChanged += delegate { times++; }; dict.Add(1, "foo"); dict.Add(2, "moo"); dict.Add(3, "boo"); dict.AddOrReplace(1, "boo"); dict.Remove(dict.First(x => x.Value == "moo")); Assert.True(dict.Values.All(x => x == "boo")); Assert.Equal(5, times); }
public void RigConfigBuilderToJSON() { ConcurrentObservableDictionary <(MinerSWE minerSWE, string version, Coin[] coins), MinerSWAbstract> minerSWs = new ConcurrentObservableDictionary <(MinerSWE minerSWE, string version, Coin[] coins), MinerSWAbstract>(); ConcurrentObservableDictionary <int, MinerGPU> minerGPUs = new ConcurrentObservableDictionary <int, MinerGPU>(); PowerConsumption pc = new PowerConsumption(new TimeSpan(0, 1, 0), new Power(1, UnitsNet.Units.PowerUnit.Watt)); TempAndFan tf = new TempAndFan() { Temp = new Temperature(50, UnitsNet.Units.TemperatureUnit.DegreeFahrenheit), FanPct = new Ratio(95.5, UnitsNet.Units.RatioUnit.Percent) }; RigConfig rc = RigConfigBuilder.CreateNew() .AddMinerSWs(minerSWs) .AddMinerGPUs(minerGPUs) .AddPowerConsumption(pc) .AddTempAndFan(tf) .Build(); var str = JsonConvert.SerializeObject(rc); str.Should() .NotBeNull(); }
public void Test_ConcurrentObservableDictionary_AddRange_Dictionary() { var toAdd = Enumerable.Range(0, 100).Select(x => new KeyValuePair <int, int>(x, x)).ToDictionary(x => x.Key, x => x.Value); var collection = new ConcurrentObservableDictionary <int, int>(); // Record all the collection changed events List <(object, NotifyCollectionChangedEventArgs)> returnedList = new List <(object, NotifyCollectionChangedEventArgs)>(); collection.CollectionChanged += (s, e) => returnedList.Add((s, e)); collection.AddRange(toAdd); // Check just one collection changed event was fired Assert.AreEqual(1, returnedList.Count); (var returnedObject, var returnedArgs) = returnedList[0]; Assert.AreEqual(returnedObject, collection); Assert.AreEqual(returnedArgs.Action, NotifyCollectionChangedAction.Add); Assert.IsNotNull(returnedArgs.NewItems); Assert.IsNull(returnedArgs.OldItems); Assert.AreEqual(toAdd.Count(), returnedArgs.NewItems.Count); Assert.IsTrue(CollectionsAreEqual(toAdd, returnedArgs.NewItems)); }
public void ConcurrentObservableDictionaryTest() { ConcurrentObservableDictionary <int, string> dict = new ConcurrentObservableDictionary <int, string>(); _times = 0; dict.CollectionChanged += Dict_CollectionChanged; try { dict.Add(1, "foo"); dict.Add(2, "moo"); dict.Add(3, "boo"); dict.AddOrReplace(1, "boo"); dict.Remove(dict.First(x => x.Value == "moo")); Assert.DoesNotContain(dict.Values, x => x != "boo"); Assert.Equal(5, _times); } finally { dict.CollectionChanged -= Dict_CollectionChanged; } }
public MinerSWAbstract(string processName, string processPath, string version, string processStartPath, bool hasConfigurationSettings, ConcurrentObservableDictionary <string, string> configurationSettings, string configFilePath, bool hasSTDOut, bool hasERROut, bool hasAPI, string aPIDiscoveryURL, bool hasLogFiles, string logFileFolder, string logFileFnPattern, Coin[] coinsMined, string[][] pools) : base( new ComputerSoftwareProgramSignil(processName, processPath, processStartPath, version, hasSTDOut, hasERROut, hasLogFiles, logFileFolder, logFileFnPattern, hasAPI, aPIDiscoveryURL, hasConfigurationSettings, configFilePath), null ) { CoinsMined = coinsMined ?? throw new ArgumentNullException(nameof(coinsMined)); Pools = pools ?? throw new ArgumentNullException(nameof(pools)); }
public WithObservableConcurrentDictionary() { calculatedResults = new ConcurrentObservableDictionary <string, ConcurrentObservableDictionary <string, decimal> >(); }
public void ConcurrentObservableDictionarySerializationTest() { // ARRANGE // ======= // A random generator (we'll test random values to avoid hard-codings) var r = new Random(); // The data contract serializer we'll use to serialize and deserialize var dcs = new DataContractSerializer(typeof(ConcurrentObservableDictionary <int, DummyDataContract>)); // The dummy data var ddc1 = new DummyDataContract { RandomValue = r.Next() }; var ddc2 = new DummyDataContract { RandomValue = r.Next() }; var ddc3 = new DummyDataContract { RandomValue = r.Next() }; var ddc4 = new DummyDataContract { RandomValue = r.Next() }; // The original observable list using (var l1 = new ConcurrentObservableDictionary <int, DummyDataContract> { [ddc1.RandomValue] = ddc1, [ddc2.RandomValue] = ddc2, [ddc3.RandomValue] = ddc3, [ddc4.RandomValue] = ddc4, }) { // The deserialized list ConcurrentObservableDictionary <int, DummyDataContract> l2; // The serialization content string content; // ACT // === using (var ms = new MemoryStream()) { dcs.WriteObject( ms, l1); _ = ms.Seek( 0, SeekOrigin.Begin); using (var textReader = new StreamReader( ms, Encoding.UTF8, false, 32768, true)) { content = textReader.ReadToEnd(); } _ = ms.Seek( 0, SeekOrigin.Begin); l2 = dcs.ReadObject(ms) as ConcurrentObservableDictionary <int, DummyDataContract>; } try { // ASSERT // ====== // Serialization content is OK Assert.False(string.IsNullOrWhiteSpace(content)); Assert.Equal( $@"<ConcurrentObservableDDCDictionaryByint xmlns=""http://ns.ixiancorp.com/IX/IX.Observable"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><Entry><Key>{ddc1.RandomValue}</Key><Value xmlns:a=""http://schemas.datacontract.org/2004/07/IX.UnitTests.Observable""><a:RandomValue>{ddc1.RandomValue}</a:RandomValue></Value></Entry><Entry><Key>{ddc2.RandomValue}</Key><Value xmlns:a=""http://schemas.datacontract.org/2004/07/IX.UnitTests.Observable""><a:RandomValue>{ddc2.RandomValue}</a:RandomValue></Value></Entry><Entry><Key>{ddc3.RandomValue}</Key><Value xmlns:a=""http://schemas.datacontract.org/2004/07/IX.UnitTests.Observable""><a:RandomValue>{ddc3.RandomValue}</a:RandomValue></Value></Entry><Entry><Key>{ddc4.RandomValue}</Key><Value xmlns:a=""http://schemas.datacontract.org/2004/07/IX.UnitTests.Observable""><a:RandomValue>{ddc4.RandomValue}</a:RandomValue></Value></Entry></ConcurrentObservableDDCDictionaryByint>", content); // Deserialized object is OK Assert.NotNull(l2); Assert.Equal( l1.Count, l2.Count); #pragma warning disable HAA0401 // Possible allocation of reference type enumerator - Acceptable in this unit test foreach (var key in l1.Keys) #pragma warning restore HAA0401 // Possible allocation of reference type enumerator { Assert.True(l1[key].Equals(l2[key])); } } finally { l2?.Dispose(); } } }