private void btnStart_Click(object sender, RoutedEventArgs e) { Task.Run(async () => { bool isOpened = await this.tmp102.OpenAsync(); IDictionary bag = new Dictionary<SensorType, float>(); while (true) { float temperature = tmp102.Temperature(); SensorType sensorType = SensorType.Temperature; if (!bag.Contains(sensorType)) bag.Add(sensorType, temperature); else bag[sensorType] = temperature; if ((this.iotClient != null) && (this.iotClient.IsOpen)) { this.iotClient.SendAsync(bag); } await Task.Delay(5000); } }); }
private void btnStart_Click(object sender, RoutedEventArgs e) { Task.Run(async () => { IDictionary bag = new Dictionary<SensorType, float>(); var rnd = new Random(); while (true) { var temperature = (float)GetRandomNumber(rnd, -10, 50); SensorType sensorType = SensorType.Temperature; if (!bag.Contains(sensorType)) bag.Add(sensorType, temperature); else bag[sensorType] = temperature; if ((this.iotClient != null) && (this.iotClient.IsOpen)) { this.iotClient.SendAsync(bag); } await Task.Delay(5000); } }); }
public void WriterWriteEmptyString() { string outputPath = Guid.NewGuid().ToString() + ".plist"; IDictionary dict = new Dictionary<string, object>(); dict["Empty"] = string.Empty; BinaryPlistWriter writer = new BinaryPlistWriter(); writer.WriteObject(outputPath, dict); BinaryPlistReader reader = new BinaryPlistReader(); dict = reader.ReadObject(outputPath); Assert.IsTrue(dict.Contains("Empty")); Assert.AreEqual(string.Empty, dict["Empty"]); }
public async void Run(IBackgroundTaskInstance taskInstance) { // // TODO: Insert code to start one or more asynchronous methods // BackgroundTaskDeferral deferral = taskInstance.GetDeferral(); this.tmp102 = new TMP102(); // set and open the IoT client if (this.iotClient == null) { //this.iotClient = new IoTClient("raspberrypi2", Guid.NewGuid().ToString(), this.connectionString, this.eventHubEntity); this.iotClient = new IoTClientConnectTheDots("raspberrypi2", Guid.NewGuid().ToString(), this.connectionString, this.eventHubEntity); } if (!this.iotClient.IsOpen) this.iotClient.Open(); bool isOpened = await this.tmp102.OpenAsync(); IDictionary bag = new Dictionary<SensorType, float>(); while (true) { float temperature = tmp102.Temperature(); SensorType sensorType = SensorType.Temperature; if (!bag.Contains(sensorType)) bag.Add(sensorType, temperature); else bag[sensorType] = temperature; if ((this.iotClient != null) && (this.iotClient.IsOpen)) { this.iotClient.SendAsync(bag); } await Task.Delay(5000); } deferral.Complete(); }
public void IDictionary_Contains () { IDictionary d = new Dictionary<int, int> (); d.Add (1, 2); Assert.IsTrue (d.Contains (1)); Assert.IsFalse (d.Contains (2)); Assert.IsFalse (d.Contains ("x")); }
/// <summary> /// Execute the MSBuild Task. /// </summary> /// <returns></returns> public override bool Execute() { _modifiedFiles = new ArrayList(); _deletedFiles = new ArrayList(); // Parse local manifest to retrieve list of files and their hashes. string[] localManifest = File.ReadAllLines(_localManifestFile); Dictionary<string, string> localFiles = new Dictionary<string,string>(); for (int i = 0; i < localManifest.Length; i++) { if (localManifest[i].StartsWith("Archive-Asset-Name: ")) { string assetName = localManifest[i].Substring(20); i++; if (localManifest[i].StartsWith("Archive-Asset-SHA-512-Digest: ")) { string assetHash = localManifest[i].Substring(30); localFiles.Add(assetName, assetHash); } else { return false; } } } // Do the same for the target manifest. string[] targetManifest = File.ReadAllLines(_targetManifestFile); Dictionary<string, string> targetFiles = new Dictionary<string,string>(); for (int i = 0; i < targetManifest.Length; i++) { if (targetManifest[i].StartsWith("Archive-Asset-Name: ")) { string assetName = targetManifest[i].Substring(20); i++; if (targetManifest[i].StartsWith("Archive-Asset-SHA-512-Digest: ")) { string assetHash = targetManifest[i].Substring(30); targetFiles.Add(assetName, assetHash); } else { return false; } } } // Compare hashes and populate the lists of modified and deleted files. string[] targetFileMap = File.ReadAllLines(_targetFileMap); foreach (KeyValuePair<string, string> file in localFiles) { // For some reason this MANIFEST.bbr file appears in the manifest, even though // it doesn't actually exist anywhere...? It doesn't seem to correspond to // MANIFEST.MF either. if (file.Key == "META-INF/MANIFEST.bbr") { continue; } // If the target manifest doesn't contain the same key/value pair, // that means the local file has been either added or modified. if (!targetFiles.Contains(file)) { TaskItem item = new TaskItem(file.Key); item.SetMetadata("SourcePath", getSourcePath(file.Key, targetFileMap)); _modifiedFiles.Add(item); } } IDictionaryEnumerator targetEnum = targetFiles.GetEnumerator(); while (targetEnum.MoveNext()) { // If the local manifest doesn't contain the same key, // that means the target file has been deleted from the project. if (!localFiles.ContainsKey((string)targetEnum.Key)) { TaskItem item = new TaskItem((string)targetEnum.Key); _deletedFiles.Add(item); } } // For some reason the manifest file doesn't show up in the target file map // or the manifest itself, so we add it manually here and always upload it. TaskItem manifestItem = new TaskItem("META-INF/MANIFEST.MF"); manifestItem.SetMetadata("SourcePath", "localManifest.mf"); _modifiedFiles.Add(manifestItem); return true; }
public void Contains_Enumerable_OnDictionary_IsTranslatedAsAContainsResultOperator () { var dictionary = new Dictionary<string, int>(); var query = from c in QuerySource where dictionary.Contains (new KeyValuePair<string, int> (c.Name, c.ID)) select c; var queryModel = QueryParser.GetParsedQuery (query.Expression); var whereClause = (WhereClause) queryModel.BodyClauses.Single (); Assert.That (whereClause.Predicate, Is.InstanceOf<SubQueryExpression> ()); var subQueryModel = ((SubQueryExpression) whereClause.Predicate).QueryModel; Assert.That (subQueryModel.ResultOperators, Has.Count.EqualTo (1)); Assert.That (subQueryModel.ResultOperators.Single(), Is.TypeOf<ContainsResultOperator>()); }
public void Contains_IDictionary_IsNotTranslatedAsAContainsResultOperator () { IDictionary dictionary = new Dictionary<string, int> (); var query = from c in QuerySource where dictionary.Contains (c.Name) select c; var queryModel = QueryParser.GetParsedQuery (query.Expression); var whereClause = (WhereClause) queryModel.BodyClauses.Single(); Assert.That (whereClause.Predicate, Is.Not.InstanceOf<SubQueryExpression> ()); Assert.That (whereClause.Predicate, Is.InstanceOf<MethodCallExpression> ()); }
public void ReadOnlyDictionary_Unit_GetEnumerator1_Optimal() { IDictionary<String, String> dictionary = new Dictionary<String, String>() { { "Key1", "Value1" }, { "Key2", "Value2" }, { "Key3", "Value3" } }; ReadOnlyDictionary<String, String> target = new ReadOnlyDictionary<String, String>(dictionary); using (IEnumerator<KeyValuePair<String, String>> actual = target.GetEnumerator()) { Int32 count = 0; while (actual.MoveNext()) { count++; Assert.IsTrue(dictionary.Contains(actual.Current)); } Assert.AreEqual(dictionary.Count, count); } }
private void SendData() { Task.Run(() => { IDictionary bag = new Dictionary<SensorType, float>(); var rate = (float)currentRate; SensorType sensorType = SensorType.Temperature; if (!bag.Contains(sensorType)) bag.Add(sensorType, rate); else bag[sensorType] = rate; if ((this.iotClient != null) && (this.iotClient.IsOpen)) { this.iotClient.SendAsync(bag); } }); }
public void ShouldLog_IfExceptionDataContainsLoggedByOfIncompatibleType_ReturnsTrue() { // Arrange Mock<ExceptionLogger> mock = new Mock<ExceptionLogger>(); mock.CallBase = true; ExceptionLogger product = mock.Object; IDictionary data = new Dictionary(); data.Add(ExceptionLogger.LoggedByKey, null); Exception exception = CreateException(data); ExceptionLoggerContext context = CreateMinimalValidLoggerContext(exception); // Act bool shouldLog = product.ShouldLog(context); // Assert Assert.Equal(true, shouldLog); Assert.True(data.Contains(ExceptionLogger.LoggedByKey)); object updatedLoggedBy = data[ExceptionLogger.LoggedByKey]; Assert.Null(updatedLoggedBy); }
public void ShouldLog_IfExceptionDataContainsLoggedByLogger_ReturnsFalse() { // Arrange Mock<ExceptionLogger> mock = new Mock<ExceptionLogger>(); mock.CallBase = true; ExceptionLogger product = mock.Object; IDictionary data = new Dictionary(); ICollection<object> loggedBy = new List<object>() { product }; data.Add(ExceptionLogger.LoggedByKey, loggedBy); Exception exception = CreateException(data); ExceptionLoggerContext context = CreateMinimalValidLoggerContext(exception); // Act bool shouldLog = product.ShouldLog(context); // Assert Assert.Equal(false, shouldLog); Assert.True(data.Contains(ExceptionLogger.LoggedByKey)); object updatedLoggedBy = data[ExceptionLogger.LoggedByKey]; Assert.Same(loggedBy, updatedLoggedBy); Assert.Equal(1, loggedBy.Count); }
public void ShouldLog_IfExceptionDataIsEmpty_AddsLoggedByKeyWithLoggerValueAndReturnsTrue() { // Arrange Mock<ExceptionLogger> mock = new Mock<ExceptionLogger>(); mock.CallBase = true; ExceptionLogger product = mock.Object; IDictionary data = new Dictionary(); Exception exception = CreateException(data); ExceptionLoggerContext context = CreateMinimalValidLoggerContext(exception); // Act bool shouldLog = product.ShouldLog(context); // Assert Assert.Equal(true, shouldLog); Assert.True(data.Contains(ExceptionLogger.LoggedByKey)); object loggedBy = data[ExceptionLogger.LoggedByKey]; Assert.IsAssignableFrom<ICollection<object>>(loggedBy); Assert.Contains(product, (ICollection<object>)loggedBy); }
public void NonNullDictionary_Unit_GetEnumerator3_Optimal() { IDictionary<String, String> dictionary = new Dictionary<String, String>() { { "Key1", "Value1" }, { "Key2", "Value2" }, { "Key3", "Value3" } }; IEnumerable target = new NonNullDictionary<String, String>(dictionary); IEnumerator actual = target.GetEnumerator(); Int32 count = 0; while (actual.MoveNext()) { count++; Assert.IsTrue(dictionary.Contains((KeyValuePair<String, String>)actual.Current)); } Assert.AreEqual(dictionary.Count, count); }
public void NonNullDictionary_Unit_CopyTo_Optimal() { IDictionary<String, String> dictionary = new Dictionary<String, String>() { { "Key1", "Value1" }, { "Key2", "Value2" }, { "Key3", "Value3" } }; ICollection<KeyValuePair<String, String>> target = new NonNullDictionary<String, String>(dictionary); KeyValuePair<String, String>[] array = new KeyValuePair<String, String>[dictionary.Count]; Int32 arrayIndex = 0; target.CopyTo(array, arrayIndex); Assert.AreEqual(dictionary.Count, array.Length); foreach (KeyValuePair<String, String> pair in array) { Assert.IsTrue(dictionary.Contains(pair)); } }
public void IDictionary_Contains2 () { IDictionary d = new Dictionary<int, int> (); d.Contains (null); }
public void Contains() { IDictionary<string, string> dict = new Dictionary<string, string>(); dict.Add("Key", "Value"); dict.Add("OtherKey", "OtherValue"); dict = dict.ToReadOnlyDictionary(); Assert.IsTrue(dict.Contains(KeyValuePair.Create("Key", "Value"))); Assert.IsTrue(dict.Contains(KeyValuePair.Create("OtherKey", "OtherValue"))); Assert.IsFalse(dict.Contains(KeyValuePair.Create("NonExistent", "NonExistentValue"))); }
static void ReplaceVars(ref string value, bool pVerbose) { if (pVerbose) WriteLine("Variables detected! Running parser..."); // Get the variables such as %USERNAME%, $HOME, etc. MatchCollection Results = Regex.Matches(value, @"(\$\w+)|(%\w+%)", RegexOptions.ECMAScript); // A dictionary of environment variables, please note that user variables // are acted upon first. Proof: Type in "set" in a cmd session. IDictionary envs = new Dictionary<string, string>(128, StringComparer.OrdinalIgnoreCase); string userprofile = GetFolderPath(SpecialFolder.UserProfile); /************************* * Linux common examples * ************************* HOME=/home/dd HOSTNAME=dd-vm HOSTTYPE=x86_64 PWD=/home/dd/Desktop SHELL=/bin/bash UID=1000 USER=dd *USERNAME=dd *Already in Windows. */ envs.Add("HOME", userprofile); envs.Add("HOSTNAME", MachineName); envs.Add("HOSTTYPE", Is64BitOperatingSystem ? "x86_64" : "i686"); envs.Add("USER", UserName); envs.Add("PWD", GetFolderPath(SpecialFolder.Desktop)); /** * Windows auto-generated variables * TMP and TEMP are already user variables. */ envs.Add("SYSTEMROOT", Path.GetDirectoryName(SystemDirectory)); // C:\Windows envs.Add("SYSTEMDRIVE", Path.GetPathRoot(SystemDirectory)); // C:\ // <HKEY_CURRENT_USER\Volatile> Variables envs.Add("APPDATA", $@"{userprofile}\AppData\Roaming"); envs.Add("HOMEDRIVE", Path.GetPathRoot(userprofile).Replace("\\", "")); // C: envs.Add("HOMEPATH", userprofile.Replace(envs["HOMEDRIVE"].ToString(), "")); // \Users\DD envs.Add("LOCALAPPDATA", $@"{userprofile}\AppData\Local"); envs.Add("LOGONSERVER", $@"\\{UserDomainName}"); // Unsure envs.Add("USERDOMAIN", UserDomainName); envs.Add("USERDOMAIN_ROAMINGPROFILE", UserDomainName); // Unsure envs.Add("USERPROFILE", userprofile); //envs.Add("", ""); foreach (DictionaryEntry i in GetEnvironmentVariables(EnvironmentVariableTarget.User)) if (!envs.Contains(i.Key)) envs.Add(i.Key, i.Value); foreach (DictionaryEntry i in GetEnvironmentVariables(EnvironmentVariableTarget.Machine)) if (!envs.Contains(i.Key)) envs.Add(i.Key, i.Value); foreach (Match result in Results) { string t = result.Value.StartsWith("$") ? result.Value.TrimStart('$') : result.Value.Trim('%'); if (envs.Contains(t)) { if (pVerbose) WriteLine($"Variable: {result.Value} -> {envs[t]}"); value = value.Replace(result.Value, envs[t].ToString()); } else if (pVerbose) WriteLine($"ENV NOT FOUND: {t}"); } }