public void Write_BuiltsXmlNode_IfAGenericDictionary() { var parentNode = NewMock<INodeWriter>(); var dictNode = CreateXmlNode("topNode"); var itemsNode = CreateXmlNode("dictionary"); var value = new Dictionary<string, int>(); value.Add("first key", 11); StubTypeMapper(); Expect.Once.On(valuesCache).Method("Add").With(value).Will(Return.Value(7)); Expect.Once.On(ownerDocument).Method("CreateTypedElement").With("dict", value.GetType().ToString(), parentNode).Will( Return.Value(dictNode)); Expect.Once.On(dictNode).Method("AddAttribute").With("ID", "7"); Expect.Once.On(dictNode).Method("Dispose").WithNoArguments(); Expect.Once.On(itemsNode).Method("Dispose").WithNoArguments(); Expect.Once.On(ownerDocument).Method("CreateElement").With("items", dictNode).Will(Return.Value(itemsNode)); Expect.Once.On(objectWriter).Method("Write").With("first key", itemsNode, typeof (string)); Expect.Once.On(objectWriter).Method("Write").With(11, itemsNode, typeof (Int32)); Expect.Once.On(itemsNode).Method("AddAttribute").With("count", 1); writer.Write(value, parentNode, value.GetType()); }
private void RegisterClick(object sender, RoutedEventArgs e) { if (UsernameField.Text == "" || PasswordField.Password == "" || ConfirmPasswordField.Password == "") { ErrorField.Text = "All fields are mandatory."; return; } if (PasswordField.Password != ConfirmPasswordField.Password) { ErrorField.Text = "Password and Confirmation don't match."; return; } ErrorField.Text = ""; APIRequest request = new APIRequest(APIRequest.POST, this, APIRequest.requestCodeType.Register, "register"); Dictionary<string, string> dict = new Dictionary<string, string>() { {"username", UsernameField.Text}, {"password", PasswordField.Password} }; var serializer = new DataContractJsonSerializer(dict.GetType(), new DataContractJsonSerializerSettings() { UseSimpleDictionaryFormat = true }); MemoryStream stream = new MemoryStream(); serializer.WriteObject(stream, dict); byte[] bytes = stream.ToArray(); string content = Encoding.UTF8.GetString(bytes, 0, bytes.Length); request.Execute(null, content); }
static void Main(string[] args) { Type guyType = typeof(Guy); Console.WriteLine("{0} extends {1}", guyType.FullName, guyType.BaseType.FullName); // output: TypeExamples.Guy extends System.Object Type nestedClassType = typeof(NestedClass.DoubleNestedClass); Console.WriteLine(nestedClassType.FullName); // output: TypeExamples.Program+NestedClass+DoubleNestedClass List<Guy> guyList = new List<Guy>(); Console.WriteLine(guyList.GetType().Name); // output: List`1 Dictionary<string, Guy> guyDictionary = new Dictionary<string, Guy>(); Console.WriteLine(guyDictionary.GetType().Name); // output: Dictionary`2 Type t = typeof(Program); Console.WriteLine(t.FullName); // output: TypeExamples.Program Type intType = typeof(int); Type int32Type = typeof(Int32); Console.WriteLine("{0} - {1}", intType.FullName, int32Type.FullName); // System.Int32 - System.Int32 Console.WriteLine("{0} {1}", float.MinValue, float.MaxValue); // output:-3.402823E+38 3.402823E+38 Console.WriteLine("{0} {1}", int.MinValue, int.MaxValue); // output:-2147483648 2147483647 Console.WriteLine("{0} {1}", DateTime.MinValue, DateTime.MaxValue); // output: 1/1/0001 12:00:00 AM 12/31/9999 11:59:59 PM Console.WriteLine(12345.GetType().FullName); // output: System.Int32 Console.ReadKey(); }
public void GetDictionaryType_StringInt() { var dsi = new Dictionary<string, int>(); Type keyType, valueType; ReflectionHelper.GetDictionaryType(dsi.GetType(), out keyType, out valueType); Assert.AreEqual(typeof(string), keyType); Assert.AreEqual(typeof(int), valueType); }
public void GetDictionaryType_DoubleDateTime() { var dsi = new Dictionary<double, DateTime>(); Type keyType, valueType; ReflectionHelper.GetDictionaryType(dsi.GetType(), out keyType, out valueType); Assert.AreEqual(typeof(double), keyType); Assert.AreEqual(typeof(DateTime), valueType); }
public void checkifgenericdictionary() { var dict = new Dictionary<string, object>(); //Debug.WriteLine(IsGenericDictionary(dict.GetType(), dict)); Type contextType = dict.GetType(); if (contextType.GetInterface("IDictionary`2") != null) { } }
public void GetGenericArgumentCount_WhenGivenNonGenericArguments_ReturnsTwo() { // ARRANGE var item = new Dictionary<int, string>(); var type = item.GetType(); // ACT var actual = type.GetGeneGetGenricArgumentCount(); // ASSERT Assert.AreEqual(2, actual); }
public void WriteTypeRegularTest() { Dictionary<string, IEnumerable<DateTime>[]> o = new Dictionary<string, IEnumerable<DateTime>[]>(); Type t = o.GetType(); TypeWriter writer = new TypeWriter(); Console.WriteLine(writer.WriteType(t)); Console.WriteLine(writer.WriteType(t.GetGenericTypeDefinition())); Assert.AreEqual("System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Collections.Generic.IEnumerable`1[[System.DateTime, mscorlib]][], mscorlib]], mscorlib", writer.WriteType(t)); Assert.AreEqual("System.Collections.Generic.Dictionary`2, mscorlib", writer.WriteType(t.GetGenericTypeDefinition())); }
public static void ReturnStructDict <K, T>(Dictionary <K, T> obj) where T : struct { if (!SpriterConfig.PoolingEnabled || obj == null) { return; } obj.Clear(); Type type = obj.GetType(); var pool = GetPool(type, Pools); pool.Push(obj); }
public void IsDictionaryOfKV() { var o = 1; Assert.IsFalse(ReflectionHelper.IsDictionaryOfKV(o.GetType())); var li = new List <int>(); Assert.IsFalse(ReflectionHelper.IsDictionaryOfKV(li.GetType())); var dsi = new Dictionary <string, int>(); Assert.IsTrue(ReflectionHelper.IsDictionaryOfKV(dsi.GetType())); }
public void TestGenericParameter() { IDictionary <List <int>, List <string> > dico = new Dictionary <List <int>, List <string> >(); Console.WriteLine(typeof(IDictionary <,>).FullName); Console.WriteLine(dico.GetType().FullName); string assemblyQualifiedName = dico.GetType().AssemblyQualifiedName; Type type = TypeUtils.ResolveType(assemblyQualifiedName); Assert.IsNotNull(type); MyGeneric <Dictionary <List <int>, List <string> >, string, List <int>, decimal> gen = new MyGeneric <Dictionary <List <int>, List <string> >, string, List <int>, decimal>(); Console.WriteLine(gen.GetType().FullName); assemblyQualifiedName = gen.GetType().AssemblyQualifiedName; type = TypeUtils.ResolveType(assemblyQualifiedName); Assert.IsNotNull(type); //Assert.That(gen, Is.InstanceOfType(type)); }
public static void LogErrorIntoDb() { ErrorEnum errType = ErrorEnum.Other; string errMsg = string.Empty; bool isSuccess = false; try { if (_errorLogsForDb.Count > 0) { DataContractSerializer serializer = new DataContractSerializer(_errorLogsForDb.GetType()); StringWriter sw = new StringWriter(); using (XmlTextWriter writer = new NoNamespaceXmlWriter(sw)) { // add formatting so the XML is easy to read in the log writer.Formatting = Formatting.Indented; serializer.WriteObject(writer, _errorLogsForDb); writer.Flush(); } string logXml = sw.ToString(); List <SqlParameter> sqlParams = new List <SqlParameter>(); sqlParams.Add(new SqlParameter { ParameterName = "@distId", SqlDbType = SqlDbType.VarChar, Value = User.DistId }); sqlParams.Add(new SqlParameter { ParameterName = "@logText", SqlDbType = SqlDbType.Xml, Value = logXml }); sqlParams.Add(new SqlParameter { ParameterName = "@macId", SqlDbType = SqlDbType.VarChar, Value = Network.GetActiveMACAddress() }); sqlParams.Add(new SqlParameter { ParameterName = "@action", SqlDbType = SqlDbType.VarChar, Value = "ADD" }); DataSet ds = ConnectionManager.Exec("Sp_Logger", sqlParams, out errType, out errMsg, out isSuccess); if ((ds != null) && (ds.Tables.Count > 0) && (ds.Tables[0].Rows.Count > 0)) { _errorLogsForDb.Clear(); } } } catch (Exception ex) { EmailHelper.SendErrorMail(ex); } }
// Entry point static void Main(string[] args) { Type guyType = typeof(Guy); Console.WriteLine("{0} extends {1}", guyType.FullName, guyType.BaseType.FullName); // output: LeftOver5.Guy extends System.Object Type nestedClassType = typeof(NestedClass.DoubleNestedClass); Console.WriteLine(nestedClassType.FullName); // output: LeftOver5.Program+NestedClass+DoubleNestedClass List <Guy> guyList = new List <Guy>(); Console.WriteLine(guyList.GetType().Name); // output: List`1 Dictionary <string, Guy> guyDictionary = new Dictionary <string, Guy>(); Console.WriteLine(guyDictionary.GetType().Name); // output: Dictionary`2 Type t = typeof(Program); Console.WriteLine(t.FullName); // output: LeftOver5.Program Type intType = typeof(int); // Alias for System.Int32 Type int32Type = typeof(Int32); Console.WriteLine("{0} - {1}", intType.FullName, int32Type.FullName); // output: System.Int32 - System.Int32 Console.WriteLine("{0} {1}", float.MinValue, float.MaxValue); // float is an alias for System.Single // output: -3.402823E+38 3.402823E+38 Console.WriteLine("{0} {1}", int.MinValue, int.MaxValue); // output: -2147483648 2147483648 Console.WriteLine("{0} {1}", DateTime.MinValue, DateTime.MaxValue); // output: 1/1/0001 12:00:00 AM 12/31/9999 11:59:59 PM // Literal Type Console.WriteLine(12345.GetType().FullName); // output: System.Int32 Console.ReadKey(); }
public void StartScenario(IScenario view) { if (_currentScenarios.ContainsKey(view.GetType())) { D.LogWarning(LoggingTags.Services, string.Format("scenario {0} overriden by {1}", _currentScenarios.GetType(), view.GetType())); CleanScenario(view.GetType()); } _currentScenarios[view.GetType()] = view; _currentScenarioSteps[view.GetType()] = view.Scenario().GetEnumerator(); _currentScenarioName = view.GetType().ToString(); D.Log(LoggingTags.Services, "=> Start scenario: " + _currentScenarioName); MoveNextStep(view.GetType()); }
public void GenerateValueCode_ShouldReturnNumberDictionaryCode() { var numberDisctionary = new Dictionary <int, string>() { { 1, "1" }, { 2, "2" }, { 3, "3" }, { 4, "4" }, { 5, "5" }, }; var numberListCode = _generator.GenerateValueCode(numberDisctionary.GetType(), numberDisctionary); Assert.Equal("{ 1: '1', 2: '2', 3: '3', 4: '4', 5: '5' }", numberListCode); }
public static bool Equals <TKey, TValue> (this Dictionary <TKey, TValue> dict, object obj) //where TKey: Type where TValue: Type { if (obj is null) { return(false); } if (ReferenceEquals(dict, obj)) { return(true); } if (dict.GetType() != obj.GetType()) { return(false); } var other = (Dictionary <TKey, TValue>)obj; if (dict.Count != other.Count) { return(false); } // check keys are the same foreach (TKey k in dict.Keys) { if (!other.ContainsKey(k)) { return(false); } } // check values are the same foreach (TKey key in dict.Keys) { // both null considered to be the same if (dict[key] == null && other[key] == null) { continue; } if (dict[key] == null || !dict[key].Equals(other[key])) { return(false); } } return(true); }
public void WriteTypeMinimalTest() { Dictionary<string, IEnumerable<DateTime>[]> o = new Dictionary<string, IEnumerable<DateTime>[]>(); Type t = o.GetType(); TypeWriter writer = new TypeWriter(); writer.WithAssembly = false; Console.WriteLine(writer.WriteType(t)); Console.WriteLine(writer.WriteType(t.GetGenericTypeDefinition())); Assert.AreEqual("System.Collections.Generic.Dictionary`2[[System.String],[System.Collections.Generic.IEnumerable`1[[System.DateTime]][]]]", writer.WriteType(t)); Assert.AreEqual("System.Collections.Generic.Dictionary`2", writer.WriteType(t.GetGenericTypeDefinition())); }
static void Main(string[] args) { Type guyType = typeof(Guy); Console.WriteLine("{0} rozszerza {1}", guyType.FullName, guyType.BaseType.FullName); // wyniki: TypeExamples.Guy rozszerza System.Object Type nestedClassType = typeof(NestedClass.DoubleNestedClass); Console.WriteLine(nestedClassType.FullName); // wyniki: TypeExamples.Program+NestedClass+DoubleNestedClass List <Guy> guyList = new List <Guy>(); Console.WriteLine(guyList.GetType().Name); // wyniki: List`1 Dictionary <string, Guy> guyDictionary = new Dictionary <string, Guy>(); Console.WriteLine(guyDictionary.GetType().Name); // wyniki: Dictionary`2 Type t = typeof(Program); Console.WriteLine(t.FullName); // wyniki: TypeExamples.Program Type intType = typeof(int); Type int32Type = typeof(Int32); Console.WriteLine("{0} - {1}", intType.FullName, int32Type.FullName); // System.Int32 - System.Int32 Console.WriteLine("{0} {1}", float.MinValue, float.MaxValue); // wyniki: -3.402823E+38 3.402823E+38 Console.WriteLine("{0} {1}", int.MinValue, int.MaxValue); // wyniki: -2147483648 2147483647 Console.WriteLine("{0} {1}", DateTime.MinValue, DateTime.MaxValue); // wyniki: 1/1/0001 12:00:00 AM 12/31/9999 11:59:59 PM Console.WriteLine(12345.GetType().FullName); // wyniki: System.Int32 Console.ReadKey(); }
public void WriteTypeMinimalTest() { Dictionary <string, IEnumerable <DateTime>[]> o = new Dictionary <string, IEnumerable <DateTime>[]>(); Type t = o.GetType(); TypeWriter writer = new TypeWriter(); writer.WithAssembly = false; Console.WriteLine(writer.WriteType(t)); Console.WriteLine(writer.WriteType(t.GetGenericTypeDefinition())); Assert.AreEqual("System.Collections.Generic.Dictionary`2[[System.String],[System.Collections.Generic.IEnumerable`1[[System.DateTime]][]]]", writer.WriteType(t)); Assert.AreEqual("System.Collections.Generic.Dictionary`2", writer.WriteType(t.GetGenericTypeDefinition())); }
async static Task DictionaryConcurrentAccessDetection<TKey, TValue>(Dictionary<TKey, TValue> dictionary, bool isValueType, object comparer, Action<Dictionary<TKey, TValue>> add, Action<Dictionary<TKey, TValue>> get, Action<Dictionary<TKey, TValue>> remove, Action<Dictionary<TKey, TValue>> removeOutParam) { Task task = Task.Factory.StartNew(() => { //break internal state var entriesType = dictionary.GetType().GetField("_entries", BindingFlags.NonPublic | BindingFlags.Instance); var entriesInstance = (Array)entriesType.GetValue(dictionary); var field = entriesInstance.GetType().GetElementType(); var entryArray = (Array)Activator.CreateInstance(entriesInstance.GetType(), new object[] { ((IDictionary)dictionary).Count }); var entry = Activator.CreateInstance(field); entriesType.SetValue(dictionary, entryArray); Assert.Equal(comparer, dictionary.GetType().GetField("_comparer", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(dictionary)); Assert.Equal(isValueType, dictionary.GetType().GetGenericArguments()[0].IsValueType); Assert.Equal("ThrowInvalidOperationException_ConcurrentOperationsNotSupported", Assert.Throws<InvalidOperationException>(() => add(dictionary)).TargetSite.Name); Assert.Equal("ThrowInvalidOperationException_ConcurrentOperationsNotSupported", Assert.Throws<InvalidOperationException>(() => get(dictionary)).TargetSite.Name); //Remove is not resilient yet //Assert.Equal("ThrowInvalidOperationException_ConcurrentOperationsNotSupported", Assert.Throws<InvalidOperationException>(() => remove(dictionary)).TargetSite.Name); //Assert.Equal("ThrowInvalidOperationException_ConcurrentOperationsNotSupported", Assert.Throws<InvalidOperationException>(() => removeOutParam(dictionary)).TargetSite.Name); }, TaskCreationOptions.LongRunning); //Wait max 60 seconds, could loop forever Assert.True((await Task.WhenAny(task, Task.Delay(TimeSpan.FromSeconds(60))) == task) && task.IsCompletedSuccessfully); }
public void TestCacheableMethodPocoVoidTimed() { var tValue = new Dictionary <object, object>(); var tCachedInvoke = new CacheableInvocation(InvocationKind.InvokeMemberAction, "Clear"); var tWatch = TimeIt.Go(() => tCachedInvoke.Invoke(tValue)); var tMethodInfo = tValue.GetType().GetMethod("Clear", new Type[] { }); var tWatch2 = TimeIt.Go(() => tMethodInfo.Invoke(tValue, new object[] { })); TestContext.WriteLine("Impromptu: " + tWatch.Elapsed); TestContext.WriteLine("Reflection: " + tWatch2.Elapsed); TestContext.WriteLine("Impromptu VS Reflection: {0:0.0} x faster", (double)tWatch2.Elapsed.Ticks / tWatch.Elapsed.Ticks); Assert.Less(tWatch.Elapsed, tWatch2.Elapsed); }
public void WriteDictionaryWithCustomContractTest() { var converter = new XmlDictionaryConverter(); var value = new Dictionary <int, string> { { 1, "one" }, { 2, "two" } }; var expected = "<xml><item><key>1</key><value>one</value></item><item><key>2</key><value>two</value></item></xml>"; var actual = converter.ToXml(value.GetType(), value, contract: GetCustomContract()); Assert.That(actual, IsXml.Equals(expected)); }
private async Task DictionaryConcurrentAccessDetection <TKey, TValue>(Dictionary <TKey, TValue> dictionary, bool isValueType, object comparer, Action <Dictionary <TKey, TValue> > add, Action <Dictionary <TKey, TValue> > get, Action <Dictionary <TKey, TValue> > remove, Action <Dictionary <TKey, TValue> > removeOutParam) { Task task = Task.Factory.StartNew(() => { // Get the Dictionary into a corrupted state, as if it had been corrupted by concurrent access. // We this deterministically by clearing the _entries array using reflection; // this means that every Entry struct has a 'next' field of zero, which causes the infinite loop // that we want Dictionary to break out of FieldInfo entriesType = dictionary.GetType().GetField("_entries", BindingFlags.NonPublic | BindingFlags.Instance); Array entriesInstance = (Array)entriesType.GetValue(dictionary); Array entryArray = (Array)Activator.CreateInstance(entriesInstance.GetType(), new object[] { ((IDictionary)dictionary).Count }); entriesType.SetValue(dictionary, entryArray); Assert.Equal(comparer, dictionary.GetType().GetField("_comparer", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(dictionary)); Assert.Equal(isValueType, dictionary.GetType().GetGenericArguments()[0].IsValueType); Assert.Equal("ThrowInvalidOperationException_ConcurrentOperationsNotSupported", Assert.Throws <InvalidOperationException>(() => add(dictionary)).TargetSite.Name); Assert.Equal("ThrowInvalidOperationException_ConcurrentOperationsNotSupported", Assert.Throws <InvalidOperationException>(() => get(dictionary)).TargetSite.Name); Assert.Equal("ThrowInvalidOperationException_ConcurrentOperationsNotSupported", Assert.Throws <InvalidOperationException>(() => remove(dictionary)).TargetSite.Name); Assert.Equal("ThrowInvalidOperationException_ConcurrentOperationsNotSupported", Assert.Throws <InvalidOperationException>(() => removeOutParam(dictionary)).TargetSite.Name); }, TaskCreationOptions.LongRunning); // If Dictionary regresses, we do not want to hang here indefinitely Assert.True((await Task.WhenAny(task, Task.Delay(TimeSpan.FromSeconds(60))) == task) && task.IsCompletedSuccessfully); }
public static void SerializeHosts(Dictionary<string, SMBHost> hosts, string outFile) { var serializer = new DataContractSerializer(hosts.GetType()); try { using (FileStream stream = File.Create(outFile + "_SMBHosts.xml")) { serializer.WriteObject(stream, hosts); } } catch (Exception e) { Console.WriteLine("[-] Error on serializing results (" + e.Message + ")."); } }
public static string GetAllHints(string etid) { List<DJ_Workers> ListGw= new BLLDJTourGroup().GetTourGroupByTeId(int.Parse(etid)).ToList(); Dictionary<string, string> data = new Dictionary<string, string>(); foreach (DJ_Workers item in ListGw) { data.Add(Guid.NewGuid().ToString(), item.Name + "/" + item.IDCard.Substring(0, 6) + "********" + item.IDCard.Substring(14)); } DataContractJsonSerializer serializer = new DataContractJsonSerializer(data.GetType()); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, data); return System.Text.Encoding.UTF8.GetString(ms.ToArray()); } }
public void IndexIntoGenericPropertyContainingMap() { var property = new Dictionary <string, string>(); property.Add("foo", "bar"); Property = property; var parser = new SpelExpressionParser(); var expression = parser.ParseExpression("Property"); Assert.Equal(property.GetType(), expression.GetValueType(this)); Assert.Equal(property, expression.GetValue(this)); Assert.Equal(property, expression.GetValue(this, typeof(IDictionary))); expression = parser.ParseExpression("Property['foo']"); Assert.Equal("bar", expression.GetValue(this)); }
/// <summary> /// Get Page Num according to the param and post data /// </summary> /// <param name="currPageNumStr">[0-9+-]|First|Last|Prev|Next</param> /// <param name="dss">the data from post data</param> /// <param name="currPageNumKeyName">the key name of currPageNum in dss</param> /// <param name="pageTotalCountKeyName">the key name of pageTotalCount in dss</param> /// <returns></returns> public static string GetPageNum(string currPageNumStr, Dictionary <string, string> dss, string currPageNumKeyName = "currPageNum", string pageTotalCountKeyName = "pageTotalCount") { string result = "1"; try { if (null != dss && typeof(Dictionary <string, string>) == dss.GetType()) { #region get Page Num string tmpNowPage = (dss.TryGetValue(currPageNumKeyName, out tmpNowPage) ? tmpNowPage : "1"); int tmpNowPageNum = int.TryParse((tmpNowPage ?? String.Empty).Trim(), out tmpNowPageNum) ? tmpNowPageNum : 1; tmpNowPageNum = (tmpNowPageNum < 1 ? 1 : tmpNowPageNum); int nowPageNum = int.TryParse((currPageNumStr ?? String.Empty).Trim(), out nowPageNum) ? nowPageNum : tmpNowPageNum; nowPageNum = (nowPageNum < 1 ? 1 : nowPageNum); string lastPage = dss.TryGetValue(pageTotalCountKeyName, out lastPage) ? lastPage : currPageNumStr; int lastPageNum = int.TryParse((lastPage ?? String.Empty).Trim(), out lastPageNum) ? lastPageNum : nowPageNum; switch (currPageNumStr) { case "Next": case "+": currPageNumStr = (((tmpNowPageNum + 1) > lastPageNum) ? lastPageNum : (tmpNowPageNum + 1)).ToString(); break; case "Prev": case "-": currPageNumStr = (--tmpNowPageNum > 0 ? tmpNowPageNum : 1).ToString(); break; case "First": currPageNumStr = "1"; break; case "Last": currPageNumStr = lastPage; break; default: currPageNumStr = (nowPageNum > lastPageNum ? lastPageNum : nowPageNum).ToString(); break; } result = currPageNumStr; #endregion } else { } } catch (Exception ex) { } return(result); }
public void Register <T>(IEventHandler <IDomainEvent> handler) { if (_handlers.ContainsKey(typeof(T))) { if (!_handlers[typeof(T)].Exists(m => m.GetType() == _handlers.GetType())) { _handlers[typeof(T)].Add(handler); } } else { _handlers.Add(typeof(T), new List <IEventHandler <IDomainEvent> > { handler }); } }
public void ConvertToTest() { var itemsInt = new Dictionary <int, string>(); itemsInt.Add(10, "aa"); itemsInt.Add(20, "bb"); itemsInt.Add(30, "cc"); itemsInt.Add(40, "dd"); itemsInt.Add(50, "ff"); var converterInt = TypeDescriptor.GetConverter(itemsInt.GetType()); var _intConvertActual = converterInt.ConvertTo(itemsInt, typeof(string)) as string; Assert.IsNotNull(_intConvertActual); Assert.AreEqual(_intConvertActual, "10, aa;20, bb;30, cc;40, dd;50, ff"); }
public void DictionaryFromJSON_typeTest() { // Arrange var utilJson = UtilJSON.Instance; var json = "{\"q1\":\"a1\"}"; // Act var result = utilJson.DictionaryFromJSON(json); // Assert Assert.NotNull(result); var dict = new Dictionary <string, string>(); Type type = dict.GetType(); Assert.IsType(type, result); }
public void WriteAndReadTypeTest() { Dictionary<string, IEnumerable<DateTime>[]> o = new Dictionary<string, IEnumerable<DateTime>[]>(); Type t = o.GetType(); TypeWriter writer = new TypeWriter(); Console.WriteLine(writer.WriteType(t)); Console.WriteLine(writer.WriteType(t.GetGenericTypeDefinition())); Type t1 = Type.GetType(writer.WriteType(t)); Type t2 = Type.GetType(writer.WriteType(t.GetGenericTypeDefinition())); Assert.AreEqual(t, t1); Assert.AreEqual(t.GetGenericTypeDefinition(), t2); }
public void ReadDictionaryWithCustomContractTest() { var converter = new XmlDictionaryConverter(); var value = "<xml><item><key>1</key><value>one</value></item><item><key>2</key><value>two</value></item></xml>"; var expected = new Dictionary <int, string> { { 1, "one" }, { 2, "two" } }; var actual = converter.ParseXml(expected.GetType(), value, contract: GetCustomContract()); Assert.AreEqual(expected, actual); }
public void WriteAndReadTypeTest() { Dictionary <string, IEnumerable <DateTime>[]> o = new Dictionary <string, IEnumerable <DateTime>[]>(); Type t = o.GetType(); TypeWriter writer = new TypeWriter(); Console.WriteLine(writer.WriteType(t)); Console.WriteLine(writer.WriteType(t.GetGenericTypeDefinition())); Type t1 = Type.GetType(writer.WriteType(t)); Type t2 = Type.GetType(writer.WriteType(t.GetGenericTypeDefinition())); Assert.AreEqual(t, t1); Assert.AreEqual(t.GetGenericTypeDefinition(), t2); }
internal static bool Save(string filename, Dictionary m) { try { using (FileStream fs = new FileStream(filename, FileMode.Create)) { XmlSerializer xs = new XmlSerializer(m.GetType()); xs.Serialize(fs, m); } return(true); } catch { return(false); } }
public static bool ParseValue <T>(Dictionary <byte, object> parametersDic, byte key, out T value) { value = default(T); object valueObj = null; if (!parametersDic.TryGetValue(1, out valueObj)) { return(false); } if (parametersDic.GetType() != typeof(T)) { return(false); } value = (T)valueObj; return(true); }
public void DictionaryTest() { // arrange var instance01 = new CollectionProject(); var expected = new Dictionary <string, string>(); var expectedCount = 10; // act var actual = instance01.DictionaryTest(); var actualCount = actual.Count; // assert Assert.AreEqual(expectedCount, actualCount); Assert.IsInstanceOfType(actual, expected.GetType()); }
public void WriteTypeFullTest() { Dictionary<string, IEnumerable<DateTime>[]> o = new Dictionary<string, IEnumerable<DateTime>[]>(); Type t = o.GetType(); TypeWriter writer = new TypeWriter(); writer.WithVersion = true; writer.WithCulture = true; writer.WithPublicKeyToken = true; Console.WriteLine(writer.WriteType(t)); Console.WriteLine(writer.WriteType(t.GetGenericTypeDefinition())); Assert.AreEqual("System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Collections.Generic.IEnumerable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]][], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", writer.WriteType(t)); Assert.AreEqual("System.Collections.Generic.Dictionary`2, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", writer.WriteType(t.GetGenericTypeDefinition())); }
public void CanGetTotalRevenueListedByCustomer() { RevenueFactory revenueFactory = new RevenueFactory(); Dictionary <string, int> CustomerRev = revenueFactory.GetRevenueByCustomer(); Assert.Equal(typeof(Dictionary <string, int>), CustomerRev.GetType()); Assert.Equal(CustomerRev, revenueFactory.GetRevenueByCustomer()); Assert.NotNull(CustomerRev); Assert.NotEmpty(CustomerRev); foreach (KeyValuePair <string, int> r in CustomerRev) { Assert.NotNull(r.Key); Assert.NotNull(r.Value); } }
void Start() { string jsonString = "{ \"array\": [1.44,22,33]" + "\"object\": {\"key1\":\"value1\", \"key2\":256}, " + "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " + "\"unicode\": \"\\u3041 Men\\u00fa sesi\\u00f3n\", " + "\"int\": 65536, " + "\"float\": 3.1415926, " + "\"bool\": true, " + "\"null\": null }"; string ArrayString = "[1,2,3,4,5,6,7]"; //Dictionary<string, object> dict = MiniJSON.LC_MiniJson.Deserialize(jsonString) as Dictionary.<string. Object>; Dictionary <string, object> dict = Json.Deserialize(jsonString) as Dictionary <string, object>; Debug.Log("deserialized: " + dict.GetType()); //double[][] arrayList = MiniJSON.LC_MiniJson.Deserialize((dict["array"] as List<object>)[0].ToString()) as double[][]; List <object> lst = (List <object>)dict["array"]; Debug.Log("dict['array'][0]: " + lst[2]); Debug.Log("dict['string']: " + dict["string"].ToString()); Debug.Log("dict['float']: " + dict["float"]); // floats come out as doubles Debug.Log("dict['int']: " + dict["int"]); // ints come out as longs Debug.Log("dict['unicode']: " + dict["unicode"].ToString()); Dictionary <string, object> dict2 = (dict["object"]) as Dictionary <string, object>; int[,] hh = new int[2, 3] { { 1, 2, 3 }, { 4, 5, 6 } }; List <object> szTest = Json.Deserialize(ArrayString) as List <object>; long p = (long)szTest[0]; Debug.Log(szTest + "===" + szTest.Count + "===" + p); string str = Json.Serialize(dict["array"]); Debug.Log("serialized: " + str); }
public void DictionaryTestType_WhenGetCombinationForDictionaryThatHaveMultipleKeys_ShouldReturnCorrectKey() { var dictionaryTestType = new DictionaryTestType(); var dictionary = new Dictionary <string, int> { ["test1"] = 10, ["test2"] = 10, ["test3"] = 10 }; var result = dictionaryTestType.GetTestValues("test", dictionary.GetType(), dictionary, null, new TestValueFactory()); Assert.AreEqual(6, result.Length); Assert.AreEqual("test[test1]", result[0].MemberPath); Assert.AreEqual("test[test2]", result[2].MemberPath); Assert.AreEqual("test[test3]", result[4].MemberPath); }
// Convert header map to json public static void SerializeHeaderMapToJson(Dictionary <string, object> map, ref JObject json) { Debug.Assert(json != null); foreach (var item in map) { if (item.GetType() == map.GetType()) { JObject doc = new JObject(); SerializeHeaderMapToJson((Dictionary <string, object>)item.Value, ref doc); json[item.Key] = doc; } else { json[item.Key] = MessageHelper.AnyValueToJson(item.Value); } } }
public static string SerializeDict(Dictionary <string, Facebook.JSONObject> jsonDict) { // serialize the dictionary DataContractSerializer serializer = new DataContractSerializer(jsonDict.GetType()); using (StringWriter sw = new StringWriter()) { using (XmlTextWriter writer = new XmlTextWriter(sw)) { // add formatting so the XML is easy to read in the log writer.Formatting = Formatting.Indented; serializer.WriteObject(writer, jsonDict); writer.Flush(); return(sw.ToString()); } } }
public void TestDataBindingDictionary() { var dict = new Dictionary<string, double> { {"zero", 3}, {"one", 3.1}, {"two", 3.14} }; var collectionInfo = CollectionInfo.ForType(dict.GetType()); CollectionAssert.AreEqual(dict.Keys, collectionInfo.GetKeys(dict).Cast<string>().ToArray()); CollectionAssert.AreEqual(dict, collectionInfo.GetItems(dict).Cast<KeyValuePair<string,double>>().ToArray()); foreach (var key in collectionInfo.GetKeys(dict)) { var kvp = (KeyValuePair<string, double>) collectionInfo.GetItemFromKey(dict, key); Assert.AreEqual(key, kvp.Key); Assert.AreEqual(dict[(string)key], kvp.Value); } }
public void Execute() { var theList = new List<int> {1, 2, 3, 4, 5}; var theDictionary = new Dictionary<int, string> {{1, "hoge"}, {2, "hehe"}}; // // Genericなオブジェクトの型引数の型を取得するには、System.Typeクラスの以下のメソッドを利用する。 // // ・GetGenericArguments() // // GetGenericArgumentsメソッドは、System.Typeの配列を返すので、これを利用して型引数の型を判別する。 // var genericArgTypes = theList.GetType().GetGenericArguments(); Output.WriteLine("=============== List<int>の場合 ================="); Output.WriteLine("型引数の数={0}, 型引数の型=({1})", genericArgTypes.Count(), string.Join(",", genericArgTypes.Select(item => item.Name))); genericArgTypes = theDictionary.GetType().GetGenericArguments(); Output.WriteLine("=============== Dictionary<int, string>の場合 ================="); Output.WriteLine("型引数の数={0}, 型引数の型=({1})", genericArgTypes.Count(), string.Join(",", genericArgTypes.Select(item => item.Name))); }
public static string SerializeDict(Dictionary<string, int> d) { // serialize the dictionary DataContractSerializer serializer = new DataContractSerializer(d.GetType()); using (StringWriter sw = new StringWriter()) { using (XmlTextWriter writer = new XmlTextWriter(sw)) { // add formatting so the XML is easy to read in the log writer.Formatting = Formatting.Indented; serializer.WriteObject(writer, d); writer.Flush(); return sw.ToString(); } } }
public static string GetAllHints() { Dictionary<string, string> data = new Dictionary<string, string>(); data.Add("苹果4代iphone正品", "21782"); data.Add("苹果4代 手机套", "238061"); data.Add("苹果4", "838360"); data.Add("苹果皮", "242721"); data.Add("苹果笔记本", "63348"); data.Add("苹果4s", "24030"); data.Add("戴尔笔记本", "110105"); data.Add("戴尔手机", "18870"); data.Add("戴尔键盘", "30367"); DataContractJsonSerializer serializer = new DataContractJsonSerializer(data.GetType()); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, data); return System.Text.Encoding.UTF8.GetString(ms.ToArray()); } }
public void TestWriteInt8KeyMap() { var name = "test"; var value = new Dictionary<byte, dynamic>() { {1, "0"}, {2, "1"} }; var attribute = XFireAttributeFactory.Instance.GetAttribute(value.GetType()); using (var ms = new MemoryStream()) { using (var writer = new BinaryWriter(ms)) { attribute.WriteAll(writer, name, value); } var expected = new byte[] { 0x04, 0x74, 0x65, 0x73, 0x74, 0x09, 0x02, 0x01, 0x01, 0x01, 0x00, 0x030, 0x02, 0x01, 0x01, 0x00, 0x31 }; Assert.IsTrue(ms.ToArray().SequenceEqual(expected)); } }
public void DeleteShare() { APIRequest request = request = new APIRequest(APIRequest.POST, this, APIRequest.requestCodeType.PortfolioRemove, "portfolio/remove"); var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; var token = localSettings.Values["token"]; Dictionary<string, string> dict = new Dictionary<string, string>() { {"symbol", Symbol} }; var serializer = new DataContractJsonSerializer(dict.GetType(), new DataContractJsonSerializerSettings() { UseSimpleDictionaryFormat = true }); MemoryStream stream = new MemoryStream(); serializer.WriteObject(stream, dict); byte[] bytes = stream.ToArray(); string content = Encoding.UTF8.GetString(bytes, 0, bytes.Length); request.Execute((string)token, content); }
public void ClearLimit(object sender, RoutedEventArgs routedEventArgs) { APIRequest request = null; if((string)((Button)sender).Tag == "ClearUp") request = new APIRequest(APIRequest.POST, this, APIRequest.requestCodeType.ClearLimitUp, "portfolio/setlimitup"); else if((string)((Button)sender).Tag == "ClearDown") request = new APIRequest(APIRequest.POST, this, APIRequest.requestCodeType.ClearLimitDown, "portfolio/setlimitdown"); var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; var token = localSettings.Values["token"]; Dictionary<string, string> dict = new Dictionary<string, string>() { {"symbol", Symbol}, {"limit", null} }; var serializer = new DataContractJsonSerializer(dict.GetType(), new DataContractJsonSerializerSettings() { UseSimpleDictionaryFormat = true }); MemoryStream stream = new MemoryStream(); serializer.WriteObject(stream, dict); byte[] bytes = stream.ToArray(); string content = Encoding.UTF8.GetString(bytes, 0, bytes.Length); request.Execute((string)token, content); }
public void MainClick(object sender, RoutedEventArgs routedEventArgs) { if (Favorite == false) { APIRequest request = new APIRequest(APIRequest.POST, this, APIRequest.requestCodeType.Favorite, "portfolio/favorite"); Dictionary<string, string> dict = new Dictionary<string, string>() { {"symbol", Symbol} }; var serializer = new DataContractJsonSerializer(dict.GetType(), new DataContractJsonSerializerSettings() { UseSimpleDictionaryFormat = true }); MemoryStream stream = new MemoryStream(); serializer.WriteObject(stream, dict); byte[] bytes = stream.ToArray(); string content = Encoding.UTF8.GetString(bytes, 0, bytes.Length); var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; var token = localSettings.Values["token"]; request.Execute((string) token, content); } else { APIRequest request = new APIRequest(APIRequest.POST, this, APIRequest.requestCodeType.Unfavorite, "portfolio/unfavorite"); var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; var token = localSettings.Values["token"]; request.Execute((string)token, null); } }
public void DictionaryToListTest() { Serializer s = new Serializer(typeof(Dictionary<string, SimpleObject>)); DictionaryToListConverter converter = new DictionaryToListConverter(); converter.Context = "StringValue"; s.Config.RegisterTypeConverter(typeof(Dictionary<string, SimpleObject>), converter); Dictionary<string, SimpleObject> dictionary = new Dictionary<string, SimpleObject>(); dictionary["One"] = new SimpleObject(); dictionary["One"].StringValue = "One"; dictionary["One"].IntValue = 1; dictionary["Two"] = new SimpleObject(); dictionary["Two"].StringValue = "Two"; dictionary["Two"].IntValue = 2; object list = converter.ConvertFrom(dictionary, s.Context); Assert.IsTrue(s.Config.TypeHandlerFactory[list.GetType()].IsCollection(), "Converted list is not a collection"); Dictionary<string, SimpleObject> targetDictionary = (Dictionary<string, SimpleObject>) converter.ConvertTo(list, dictionary.GetType(), s.Context); Assert.AreEqual(2, targetDictionary.Count, "Wrong number of items"); Assert.IsTrue(targetDictionary.ContainsKey("One"), "Key (One) not in converted dictionary"); Assert.IsTrue(targetDictionary.ContainsKey("Two"), "Key (Two) not in converted dictionary"); Assert.AreEqual(1, targetDictionary["One"].IntValue, "One Value wrong"); Assert.AreEqual(2, targetDictionary["Two"].IntValue, "Two Value wrong"); }
public void CanWrite_IsTrue_IfAGenericDictionary() { var value = new Dictionary<string, int>(); Assert.IsTrue(writer.CanWrite(value, value.GetType())); }
public void Apply(Form form, Localization localization) { FieldInfo messages_field; Dictionary<string, string> dict; dict = localization.langFile.getSectionKeys(form.Name + ".Text"); foreach(KeyValuePair<string, string> entry in dict) { Control[] controls = form.Controls.Find(entry.Key, true); foreach(Control control in controls) { if(!(control is ComboBox)) control.Text = entry.Value; } } messages_field = form.GetType().GetField("strings"); Dictionary<string, string> messages = new Dictionary<string, string>(); if(messages_field != null && messages_field.FieldType == messages.GetType()) { messages = messages_field.GetValue(form) as Dictionary<string, string>; ApplyStrings(form.Name, messages, localization); } messages_field = form.GetType().GetField("tooltip_messages"); Dictionary<string, string[]> tips = new Dictionary<string, string[]>(); if(messages_field != null && messages_field.FieldType == tips.GetType()) { tips = messages_field.GetValue(form) as Dictionary<string, string[]>; messages_field = form.GetType().GetField("toolTip"); ToolTip toolTip = messages_field.GetValue(form) as ToolTip; dict = localization.langFile.getSectionKeys(form.Name + ".ToolTips"); foreach (KeyValuePair<string, string> entry in dict) { if (tips.ContainsKey(entry.Key)) { foreach(string controlName in tips[entry.Key]) { Control[] controls = form.Controls.Find(controlName, true); foreach(Control control in controls) toolTip.SetToolTip(control, entry.Value); } } else { Control[] controls = form.Controls.Find(entry.Key, true); foreach(Control control in controls) { if(control is TabPage) (control as TabPage).ToolTipText = entry.Value; } } } } }
public void Should_render_include_with_untyped_model() { var model = new Dictionary<string, object>(); model.Add("Name", "Joe"); RegisterTemplate("person", SyntaxTree.Block( SyntaxTree.WriteExpression(SyntaxTreeExpression.LateBound("Name")) )); var template = SyntaxTree.Block( SyntaxTree.WriteString("Hello "), SyntaxTree.Include("person", SyntaxTreeExpression.Self(model.GetType())) ); var result = ExecuteTemplate(template, model); Assert.That(result, Is.EqualTo("Hello Joe")); }
private Dictionary<string, string> SerializeSettings(string json) { // TODO: PROTECT THIS WITH TRY/CATCH Dictionary<string, string> o = new Dictionary<string,string>(); using (Stream stream = new MemoryStream()) { byte[] data = System.Text.Encoding.UTF8.GetBytes(json); stream.Write(data, 0, data.Length); stream.Position = 0; DataContractJsonSerializer deserializer = new DataContractJsonSerializer(o.GetType()); o = (Dictionary<string, string>)deserializer.ReadObject(stream); textBoxProject.Text = o["Project"]; textBoxVersion.Text = o["Version"]; textBoxLocation.Text = o["Location"]; return o; } }
private string DeserializeSettings() { Dictionary<string, string> o = new Dictionary<string,string>(); o["Project"] = textBoxProject.Text; o["Version"] = textBoxVersion.Text; o["Location"] = textBoxLocation.Text; using (MemoryStream memoryStream = new MemoryStream()) using (StreamReader reader = new StreamReader(memoryStream)) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(o.GetType()); serializer.WriteObject(memoryStream, o); memoryStream.Position = 0; return reader.ReadToEnd(); } }
/// <summary> /// This method can be used for serialize a token without have the connection opened :-) /// </summary> /// <param name="token"></param> /// <param name="configurationType"></param> /// <param name="additionalMetaData"></param> /// <returns></returns> public Stream SerializeSecurityTokenEx(ICloudStorageAccessToken token, Type configurationType, Dictionary<String, String> additionalMetaData) { var items = new Dictionary<String, String>(); var stream = new MemoryStream(); var serializer = new DataContractSerializer(items.GetType()); // add the metadata if (additionalMetaData != null) { foreach (KeyValuePair<String, string> kvp in additionalMetaData) { items.Add(TokenMetadataPrefix + kvp.Key, kvp.Value); } } // save the token into our list StoreToken(items, token, configurationType); // write the data to stream serializer.WriteObject(stream, items); // go to start stream.Seek(0, SeekOrigin.Begin); // go ahead return stream; }
public void ShouldAssingMapWithArrayKeysToNativeArrayKeyDictionary() { var arrayKeyDictionary = new Dictionary<int[], string>{ {new int[]{1}, "test"} }; SinTDArray keyArray = new SinTDArray(); keyArray.elementType = SinTDInstance.GetSinTDType("i32"); SinTDMap SinTDMap = new SinTDMap(); SinTDMap.keyType = keyArray; SinTDMap.elementType = SinTDInstance.GetSinTDType("string"); Dictionary<int[], string> nativeDictionary = (Dictionary<int[], string>)SinTDMap .AssignValuesToNativeType(arrayKeyDictionary, arrayKeyDictionary.GetType()); Assert.AreEqual(arrayKeyDictionary.Keys, nativeDictionary.Keys); Assert.AreEqual(arrayKeyDictionary.Values, nativeDictionary.Values); }
public void IsGenericTypeWithFirstDynamicTypeArgument_WhenGivenGenericTypeWithMoreThanOneGenericType_ReturnsFalse() { // ARRANGE var item = new Dictionary<int, string>(); var type = item.GetType(); // ACT var actual = type.IsGenericTypeWithFirstDynamicTypeArgument(); // ASSERT Assert.IsFalse(actual); }
private System.CodeDom.Compiler.CodeDomProvider SafeGetCSharpVersion3Compiler() { System.CodeDom.Compiler.CodeDomProvider provider = null; foreach (ConstructorInfo info in typeof(CSharpCodeProvider).GetConstructors()) { ParameterInfo[] parameters = info.GetParameters(); if (parameters.Length == 1) { Dictionary<string, string> dictionary = new Dictionary<string, string>(); dictionary["CompilerVersion"] = "v3.5"; if (parameters[0].ParameterType.IsAssignableFrom(dictionary.GetType())) { provider = (System.CodeDom.Compiler.CodeDomProvider) info.Invoke(new object[] { dictionary }); break; } } } if (provider == null) { throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, AddTypeStrings.SpecialNetVersionRequired, new object[] { Microsoft.PowerShell.Commands.Language.CSharpVersion3.ToString(), "3.5" })); } return provider; }