public loadsetting()
 {
     JavaScriptSerializer serializer = new JavaScriptSerializer();
     string text = System.IO.File.ReadAllText(settingfile,Encoding.UTF8);
     set = new Dictionary<string, object>();
     set = (IDictionary<string, object>)serializer.Deserialize(text, set.GetType());
 }
Example #2
0
 private IDictionary<string, object> CloneCustomDictionary(IDictionary<string, object> source)
 {
     var clone = Activator.CreateInstance(source.GetType()) as IDictionary<string, object>;
     if (clone == null) throw new InvalidOperationException("Internal data structure cannot be cloned.");
     CopyDictionaryAndCloneNestedDictionaries(source, clone);
     return clone;
 }
 public IDictionary Convert(IDictionary source)
 {
     if (source != null && source.Contains(nameof(Type)))
     {
         var type = source[nameof(Type)].ToString();
         if (Types != null && Types.ContainsKey(type))
         {
             try
             {
                 var _type = Types[type];
                 if (_type == null) throw new Exception($"Types['{type}'] was null");
                 var dictionary = Activator.CreateInstance(_type) as IDictionary;
                 if(dictionary == null)
                 {
                     throw new Exception($"unable to create instance of type {_type.FullName}");
                 }
                 Copy(source, dictionary);
                 return dictionary;
             }
             catch(Exception ex)
             {
                 throw new Exception($"Exception while converting type '{type}', fullname {Types[type].FullName}", ex);
             }
         }
         
     }
     if(source != null)
     {
         var result = Activator.CreateInstance(source.GetType()) as IDictionary;
         Copy(source, result);
         return result;
     }
     return source;
 }
        private static bool IsValidDictionaryType(IDictionary dictionary)
        {
            if (dictionary == null)
            {
                return false;
            }

            Type[] genericParameters = dictionary.GetType().GetGenericArguments();

            // Support non-generics IDictionary
            if (genericParameters.Length == 0)
            {
                return true;
            }

            // Only support IDictionary<string|object, object>
            if (genericParameters[0] != typeof(string) && genericParameters[0] != typeof(object))
            {
                return false;
            }

            if (genericParameters[1] != typeof(object))
            {
                return false;
            }

            return true;
        }
        protected string GetClientClass( IDictionary dictionary )
        {
            Type type = dictionary.GetType();
            string className = type.IsGenericType && type.FullName != null
                             ? type.FullName.Substring( 0, type.FullName.IndexOf( "`" ) )
                             : type.FullName;
#if (FULL_BUILD)
            string clientClass = null;
            string mappingClassName = ORBConstants.CLIENT_MAPPING + className;
            IDictionary props = ThreadContext.getProperties();

            if( props.Contains( className ) )
                clientClass = (string) props[ mappingClassName ];
#else
            string clientClass = null;
#endif
            if( clientClass == null )
            {
                clientClass = Types.Types.getClientClassForServerType( className );

                if( clientClass == null && type.IsGenericType )
                {
                    Type keyType = type.GetGenericArguments()[ 0 ];

                    if( !keyType.IsPrimitive && !StringUtil.IsStringType( keyType ) )
                        clientClass = "flash.utils.Dictionary";
                }

                return clientClass;
            }
            else
            {
                return clientClass;
            }
        }
        public static Func<int, IDictionary<string, object>> CreateFunc(IDictionary<string, object> source)
        {
            var dictionary = source as Dictionary<string, object>;
            if (dictionary != null) return cap => new Dictionary<string, object>(cap, dictionary.Comparer);
            var sortedDictionary = source as SortedDictionary<string, object>;
            if (sortedDictionary != null) return cap => new SortedDictionary<string, object>(sortedDictionary.Comparer);
            if (source is ConcurrentDictionary<string,object>) return cap => new ConcurrentDictionary<string, object>();

            var type = source.GetType();
            return cap => (IDictionary<string, object>) Activator.CreateInstance(type);
        }
 public static IDictionary ConvertTypes(IDictionary source, Dictionary<string, Type> types,string typeKey = "Type")
 {
     if (source == null) return null;
     if (types == null) return source;
     var copy = Activator.CreateInstance(source.GetType()) as IDictionary;
     if (copy == null) throw new Exception($"failed to create instance of type {source.GetType().FullName}");
     var typename = GetTypeName(source,typeKey);
     if (typename.Length > 0 && types.ContainsKey(typename))
     {
         var targetType = types[typename];
         if (targetType == null) throw new Exception($"types['{typename}'] was null");
         if (source.GetType() != targetType)
         {
             copy = Activator.CreateInstance(targetType) as IDictionary;
             if (copy == null) throw new Exception($"failed to create instance of type {targetType.FullName}");
         }
     }
     foreach (var key in source.Keys)
     {
         var value = source[key];
         var childDictionary = value as IDictionary;
         if (childDictionary != null)
         {
             copy[key] = ConvertTypes(childDictionary, types,typeKey);
         }
         else
         {
             var childEnumerable = value as IEnumerable;
             if (childEnumerable != null && childEnumerable.GetType() != typeof(string))
             {
                 copy[key] = IEnumerableExtension.ConvertTypes(childEnumerable, types,typeKey);
             }
             else
             {
                 if (copy.Contains(key)) copy[key] = value;
                 else copy.Add(key, value);
             }
         }
     }
     return copy;
 }
        private void BenchImpl(IDictionary<int, string> dictionary, int count)
        {
            dictionary[0] = "0"; // Force JIT

            var watch = Stopwatch.StartNew();
            for (int i = 0; i < count; i++)
                dictionary[i] = i.ToString();
            string ignored;
            for (int i = 0; i < count; i++)
                ignored = dictionary[i];
            _output.WriteLine(string.Format("Time to process with dictionary of type '{0}': {1}.",
                dictionary.GetType(),
                watch.Elapsed));
        }
        private IDictionary Create(IDictionary source)
        {
            IDictionary result = null;

            if (source.Contains(nameof(Type)))
            {
                var type = source[nameof(Type)].ToString();
                if (Types != null && Types.ContainsKey(type))
                {
                    result = Activator.CreateInstance(Types[type]) as IDictionary;
                }
            }
            if(result == null) result = System.Activator.CreateInstance(source.GetType()) as IDictionary;
            return result;
        }
Example #10
0
        private static void BenchImpl(IDictionary<string, int> dictionary, int count)
        {
            Console.WriteLine("Start...");
            var watch = Stopwatch.StartNew();
            for (int i = 0; i < count; i++)
                dictionary[i.ToString()] = i;
            var sets = watch.Elapsed;
            Console.WriteLine(string.Format("      Sets: {0}.", sets));

            int ignored;
            for (int i = 0; i < count; i++)
                ignored = dictionary[i.ToString()];
            Console.WriteLine(string.Format("      Gets: {0}.", watch.Elapsed - sets));

            Console.WriteLine(string.Format("Global time to process with dictionary of type '{0}': {1}.",
                dictionary.GetType(),
                watch.Elapsed));
        }
        public void AddKeyValueTest(IDictionary<int, object> anyDictionary, int size)
        {
            const string path = @"E:\results.txt";
            StreamWriter tr = File.AppendText(path);

            var sw = new Stopwatch();
            sw.Start();
            for (int i = 0; i < size; i++)
            {
                anyDictionary.Add(i, "Value" + i);
            }

            sw.Stop();
            tr.WriteLine("AddKeyValueTest for " + anyDictionary.GetType().Name + " size: " + size + " took {0}ms",
                         sw.ElapsedMilliseconds.ToString());
            Console.WriteLine("Elapsed time for AddKeyValue is: {0}ms", sw.Elapsed);
            Assert.AreEqual(size, anyDictionary.Count);
            sw.Reset();
            tr.Close();
            tr.Dispose();
        }
 internal static IDictionary CloneDictionary(IDictionary source)
 {
     if (source == null)
     {
         return null;
     }
     if (source is ICloneable)
     {
         return (IDictionary) ((ICloneable) source).Clone();
     }
     IDictionary dictionary = (IDictionary) Activator.CreateInstance(source.GetType());
     IDictionaryEnumerator enumerator = source.GetEnumerator();
     while (enumerator.MoveNext())
     {
         ICloneable key = enumerator.Key as ICloneable;
         ICloneable cloneable2 = enumerator.Value as ICloneable;
         if ((key != null) && (cloneable2 != null))
         {
             dictionary.Add(key.Clone(), cloneable2.Clone());
         }
     }
     return dictionary;
 }
Example #13
0
        public TypedMapType(IDictionary value)
        {
            Type[] argumentTypes = value.GetType().GetInterface("IDictionary`2").GetGenericArguments();
             keyType = JmxTypeMapping.GetJmxXmlType(argumentTypes[0].AssemblyQualifiedName);
             valueType = JmxTypeMapping.GetJmxXmlType(argumentTypes[1].AssemblyQualifiedName);

             List<MapTypeEntry> mapTypeEntries = new List<MapTypeEntry>();
             foreach (DictionaryEntry entry in value)
             {
            mapTypeEntries.Add(new MapTypeEntry
            {
               Key = new GenericValueType(entry.Key),
               Value = new GenericValueType(entry.Value)
            });
             }
             Entry = mapTypeEntries.ToArray();
        }
    private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract)
    {
      contract.InvokeOnSerializing(values);

      SerializeStack.Add(values);
      writer.WriteStartObject();

      bool isReference = contract.IsReference ?? HasFlag(_serializer.PreserveReferencesHandling, PreserveReferencesHandling.Objects);
      if (isReference)
      {
        writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
        writer.WriteValue(_serializer.ReferenceResolver.GetReference(values));
      }
      if (HasFlag(_serializer.TypeNameHandling, TypeNameHandling.Objects))
      {
        WriteTypeProperty(writer, values.GetType());
      }

      foreach (DictionaryEntry entry in values)
      {
        string propertyName = entry.Key.ToString();
        object value = entry.Value;

        if (ShouldWriteReference(value, null))
        {
          writer.WritePropertyName(propertyName);
          WriteReference(writer, value);
        }
        else
        {
          if (!CheckForCircularReference(value, null))
            continue;

          writer.WritePropertyName(propertyName);
          SerializeValue(writer, value, null);
        }
      }

      writer.WriteEndObject();
      SerializeStack.RemoveAt(SerializeStack.Count - 1);

      contract.InvokeOnSerialized(values);
    }
        public void RemoveElementByKeyTest(IDictionary<int, object> anyDictionary, int size)
        {
            const string path = @"E:\results.txt";
            StreamWriter tr = File.AppendText(path);

            //Lets add 3 items in the dictionary
            for (int i = 0; i < size; i++)
            {
                anyDictionary.Add(i, "Value" + i);
            }
            Assert.AreEqual(size, anyDictionary.Count);
            var s = new Stopwatch();
            s.Start();
            for (int i = 0; i < size; i++)
            {
                anyDictionary.Remove(i);
            }
            //anyDictionary.Remove(99);
            s.Stop();
            Console.WriteLine("Elapsed time for RemoveKey is: {0}ms", s.Elapsed);
            tr.WriteLine("RemoveByKey for " + anyDictionary.GetType().Name + " size: " + size + " took {0}ms",
                         s.ElapsedMilliseconds);
            Assert.AreEqual(0, anyDictionary.Count);

            s.Reset();
            tr.Close();
            tr.Dispose();
        }
 public void TestContainsLastTwo100(IDictionary<int, object> anyDictionary)
 {
     const string path = @"E:\results.txt";
     StreamWriter tr = File.AppendText(path);
     var sw = new Stopwatch();
     Console.WriteLine("Elapsed time for Contains is: {0}ms", sw.ElapsedMilliseconds);
     sw.Stop();
     tr.WriteLine("ContainsKey test for " + anyDictionary.GetType().Name.ToString() + " size: " + 100 + " took {0}ms",
                  sw.ElapsedMilliseconds);
     tr.Close();
     sw.Reset();
 }
Example #17
0
 private static void XmlSerializeIDictionary(XmlWriter writer, IDictionary obj, Type keyType, Type valueType)
 {
     Type objType = obj.GetType();
     writer.WriteStartElement(GetCleanName(objType.Name));
     IDictionaryEnumerator de = obj.GetEnumerator();
     if (objType.IsGenericType)
     {
         if (keyType == null)
         {
             string keyTypeName = Arithmetic.GetInlineItem(objType.FullName, 1, '[', ']');
             if (!string.IsNullOrEmpty(keyTypeName))
             {
                 keyType = Type.GetType(keyTypeName);
             }
         }
         if (valueType == null)
         {
             string valueTypeName = Arithmetic.GetInlineItem(objType.FullName, 2, '[', ']');
             if (!string.IsNullOrEmpty(valueTypeName))
             {
                 valueType = Type.GetType(valueTypeName);
             }
         }
     }
     bool writeKeyType = (keyType == null) || keyType.Equals(Generic<object>.Type);
     if (!(writeKeyType || SimpleTypes.ContainsValue(keyType)))
     {
         writer.WriteAttributeString("keyType", GetTypeName(keyType));
     }
     bool writeValueType = (valueType == null) || valueType.Equals(Generic<object>.Type);
     if (!(writeValueType || SimpleTypes.ContainsValue(valueType)))
     {
         writer.WriteAttributeString("valueType", GetTypeName(valueType));
     }
     while (de.MoveNext())
     {
         Type type;
         writer.WriteStartElement("Item");
         if (de.Key != null)
         {
             type = de.Key.GetType();
             if (!((!writeKeyType && (type == keyType)) || IsKnownType(type)))
             {
                 writer.WriteAttributeString("keyType", GetTypeName(type));
             }
         }
         if (de.Value != null)
         {
             type = de.Value.GetType();
             if (!((!writeValueType && (type == valueType)) || IsKnownType(type)))
             {
                 writer.WriteAttributeString("valueType", GetTypeName(type));
             }
         }
         XmlWriterSerialize(writer, de.Key, keyType);
         XmlWriterSerialize(writer, de.Value, valueType);
         writer.WriteEndElement();
     }
     writer.WriteEndElement();
 }
Example #18
0
        /// <summary>
        /// Writes a dictionary as a JSON object.
        /// </summary>
        public void Write(IDictionary dictionary)
        {
            if (dictionary == null)
                throw new ArgumentNullException("dictionary");

            // already implements serialization interface?
            IJSonWritable jValue = dictionary as IJSonWritable;

            if (jValue != null)
            {
                jValue.Write(this);
                return;
            }

            // is marked with serialization attribute?
            Type oType = dictionary.GetType();
            JSonSerializableAttribute jsonAttribute = ReflectionHelper.GetCustomAttribute<JSonSerializableAttribute>(oType);

            if (jsonAttribute != null)
            {
                WriteAttributedObject(dictionary, oType, jsonAttribute);
                return;
            }

            WriteObjectBegin();
            foreach (DictionaryEntry entry in dictionary)
            {
                WriteMember(entry.Key.ToString());
                WriteEmbeddedValue(entry.Value);
            }
            WriteObjectEnd();
        }
Example #19
0
        private void WriteDictionary(IDictionary dictionary, int depth, out List<CimInstance> listOfCimInstances)
        {
            listOfCimInstances = new List<CimInstance>();
            Dbg.Assert(dictionary != null, "caller should validate the parameter");

            IDictionaryEnumerator dictionaryEnum = null;
            try
            {
                dictionaryEnum = dictionary.GetEnumerator();
            }
            catch (Exception exception) // ignore non-severe exceptions
            {
                // Catch-all OK. This is a third-party call-out.
                CommandProcessorBase.CheckForSevereException(exception);

                PSEtwLog.LogAnalyticWarning(
                    PSEventId.Serializer_EnumerationFailed, PSOpcode.Exception, PSTask.Serialization,
                    PSKeyword.Serializer | PSKeyword.UseAlwaysAnalytic,
                    dictionary.GetType().AssemblyQualifiedName,
                    exception.ToString());
            }

            if (dictionaryEnum != null)
            {
                while (true)
                {
                    object key = null;
                    object value = null;
                    try
                    {
                        if (!dictionaryEnum.MoveNext())
                        {
                            break;
                        }
                        else
                        {
                            key = dictionaryEnum.Key;
                            value = dictionaryEnum.Value;
                        }
                    }
                    catch (Exception exception)
                    {
                        // Catch-all OK. This is a third-party call-out.
                        CommandProcessorBase.CheckForSevereException(exception);

                        PSEtwLog.LogAnalyticWarning(
                            PSEventId.Serializer_EnumerationFailed, PSOpcode.Exception, PSTask.Serialization,
                            PSKeyword.Serializer | PSKeyword.UseAlwaysAnalytic,
                            dictionary.GetType().AssemblyQualifiedName,
                            exception.ToString());

                        break;
                    }

                    Dbg.Assert(key != null, "Dictionary keys should never be null");
                    if (key == null) break;
                    CimInstance dictionaryEntryInstance = CreateCimInstanceForDictionaryEntry(key, value, depth);
                    listOfCimInstances.Add(dictionaryEntryInstance);
                }
            }
        }
        private void SerializeDictionary(IDictionary dictionary)
        {
            Type keyType = dictionary.GetType().GetGenericArguments()[0];
            Type valueType = dictionary.GetType().GetGenericArguments()[1];

            this.writer.Write(dictionary.Count);
            this.writer.Write(keyType.FullName);
            this.writer.Write(valueType.FullName);

            foreach (object key in dictionary.Keys)
            {
                // Write key.
                if (keyType.IsSealed() || key == null)
                {
                    this.Serialize(key, keyType);
                }
                else
                {
                    this.SerializeValueWithType(new ValueWithType(key));
                }

                // Write value.
                object value = dictionary[key];

                if (valueType.IsSealed() || value == null)
                {
                    this.Serialize(value, valueType);
                }
                else
                {
                    this.SerializeValueWithType(new ValueWithType(value));
                }
            }
        }
Example #21
0
        private static string WriteIDictionary(IDictionary dict, string indent)
        {
            if (dict == null) { return "[null]"; }
            if (dict.Keys.Count == 0) { return "[empty]"; }

            //StringBuilder sbDetail = new StringBuilder("[IDictionary]");
            StringBuilder sbDetail = new StringBuilder("[" + dict.GetType().ToString() + "]");

            foreach (object key in dict.Keys)
            {
                string detail = FormatObject(dict[key], indent);
                sbDetail.AppendFormat(indent + "'{0}' = {1}", key, detail);
            }

            return sbDetail.ToString();
        }
Example #22
0
        public static void CalculateTime(IDictionary table, int k)
        {
            // Add
            var startAdding = DateTime.Now;
            string[] test = { "Key string", "Test string" };
            for (int i = 0; i < k; i++)
            {
                table.Add(i, test[1]);
            }
            var finishAdding = DateTime.Now;
            Console.WriteLine("Addition time (" + k + " elements) : " + table.GetType() + "  " + (finishAdding - startAdding));

            // Search
            var startSearch = DateTime.Now;
            for (int i = 0; i < k; i++)
            {
                bool a = table.Contains("Key");
            }
            var finishSearch = DateTime.Now;
            Console.WriteLine("Search time (" + k + " elements) : " + table.GetType() + "  " + (finishSearch - startSearch));

            // Remove
            k = 1000000;
            var startRemoving = DateTime.Now;
            for (int i = 0; i < k; i++)
            {
                table.Remove(i);
            }
            var finishRemoving = DateTime.Now;
            Console.WriteLine("Removal time (" + k + " elements) : " + table.GetType() + "  " + (finishRemoving - startRemoving) + "\n");
        }
			public string Amb(IDictionary obj)
			{
				return obj.GetType().Name;
			}
Example #24
0
        private static Type GetDictionaryKeyType(IDictionary value) 
        {
            Type type = value.GetType(); 
            Type result; 

            if (_keyTypeMap == null) 
                _keyTypeMap = new Dictionary<Type, Type>();
            if (!_keyTypeMap.TryGetValue(type, out result))
            {
                foreach (Type interfaceType in type.GetInterfaces()) 
                {
                    if (interfaceType.IsGenericType) 
                    { 
                        Type genericTypeDefinition = interfaceType.GetGenericTypeDefinition();
                        if (genericTypeDefinition == typeof(System.Collections.Generic.IDictionary<,>)) 
                            return interfaceType.GetGenericArguments()[0];
                    }
                }
                result = typeof(object); 
                _keyTypeMap[type] = result;
            } 
            return result; 
        }
Example #25
0
 void HighlightDictionary(IDictionary value, string name, bool addAnnotation)
 {
     Type keyType;
     Type valueType;
     ContainerHelper.GetDictionaryTypes(value.GetType(), out keyType, out valueType);
     if(valueType == typeof(de.unika.ipd.grGen.libGr.SetValueType))
     {
         foreach(DictionaryEntry entry in value)
         {
             if(entry.Key is IGraphElement)
                 HighlightSingleValue(entry.Key, name, addAnnotation);
         }
     }
     else
     {
         int cnt = 0;
         foreach(DictionaryEntry entry in value)
         {
             if(entry.Key is INode && entry.Value is INode)
             {
                 HighlightMapping((INode)entry.Key, (INode)entry.Value, name, cnt, addAnnotation);
                 ++cnt;
             }
             else
             {
                 if(entry.Key is IGraphElement)
                     HighlightSingleValue(entry.Key, name + ".Domain -> " + EmitHelper.ToString(entry.Value, shellProcEnv.ProcEnv.NamedGraph), addAnnotation);
                 if(entry.Value is IGraphElement)
                     HighlightSingleValue(entry.Value, EmitHelper.ToString(entry.Key, shellProcEnv.ProcEnv.NamedGraph) + " -> " + name + ".Range", addAnnotation);
             }
         }
     }
 }
Example #26
0
        static List<TestResult> TestDictionary(IDictionary<string, string> dictionary, List<string> keys, List<string> values, int iterations, int[] threadCounts)
        {
            if (iterations > keys.Count)
                iterations = keys.Count;
            if (iterations > values.Count)
                iterations = values.Count;

            //test with 1 thread
            List<TestResult> testresults = new List<TestResult>();

            foreach (var threadCount in threadCounts)
            {

                try
                {
                    //test write
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    var results = TestingPlatform.Test(threadCount, iterations, delegate(int i)
                    {
                        dictionary[keys[i]] = values[i];
                    });

                    testresults.Add(new TestResult
                    {
                        DictionaryType = dictionary.GetType().Name,
                        ElapsedMilliseconds = results.ElapsedMilliseconds,
                        Error = (results.Exception != null),
                        Read = false,
                        Threads = threadCount,
                        Write = true
                    });

                    Console.WriteLine("Time took to write dictionary {0} with {1} threads: {2} ms", dictionary.GetType().Name, results.ThreadNumber, results.ElapsedMilliseconds);

                    if (results.Exception != null)
                        Console.WriteLine("Dictionary {0} threw an exception during the write test with {1} threads", dictionary.GetType().Name,results.ThreadNumber);

                    //test read
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    results = TestingPlatform.Test(threadCount, iterations, delegate(int i)
                    {
                        var retval = dictionary[keys[i]];
                    });

                    testresults.Add(new TestResult
                    {
                        DictionaryType = dictionary.GetType().Name,
                        ElapsedMilliseconds = results.ElapsedMilliseconds,
                        Error = (results.Exception != null),
                        Read = true,
                        Threads = threadCount,
                        Write = false
                    });

                    Console.WriteLine("Time took to read dictionary {0} with {1} threads: {2} ms", dictionary.GetType().Name, results.ThreadNumber, results.ElapsedMilliseconds);

                    if (results.Exception != null)
                        Console.WriteLine("Dictionary {0} threw an exception during the read test with {1} threads", dictionary.GetType().Name, results.ThreadNumber);

                    //test read
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    results = TestingPlatform.Test(threadCount, iterations, delegate(int i)
                    {
                        dictionary[keys[i]] = values[i];
                        var retval = dictionary[keys[i]];
                    });

                    testresults.Add(new TestResult
                    {
                        DictionaryType = dictionary.GetType().Name,
                        ElapsedMilliseconds = results.ElapsedMilliseconds,
                        Error = (results.Exception != null),
                        Read = true,
                        Threads = threadCount,
                        Write = true
                    });

                    Console.WriteLine("Time took to read/write dictionary {0} with {1} threads: {2} ms", dictionary.GetType().Name, results.ThreadNumber, results.ElapsedMilliseconds);

                    if (results.Exception != null)
                        Console.WriteLine("Dictionary {0} threw an exception during the read test with {1} threads", dictionary.GetType().Name, results.ThreadNumber);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Couldn't test dictionary {0} with {1} threads, error", dictionary.GetType().Name, threadCount);
                }

            }
            return testresults;

        }
        private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract)
        {
            contract.InvokeOnSerializing(values, Serializer.Context);

              SerializeStack.Add(values);
              writer.WriteStartObject();

              bool isReference = contract.IsReference ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Objects);
              if (isReference)
              {
            writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
            writer.WriteValue(Serializer.ReferenceResolver.GetReference(values));
              }
              if (HasFlag(Serializer.TypeNameHandling, TypeNameHandling.Objects))
              {
            WriteTypeProperty(writer, values.GetType());
              }

              int initialDepth = writer.Top;

              foreach (DictionaryEntry entry in values)
              {
            string propertyName = GetPropertyName(entry);

            try
            {
              object value = entry.Value;
              JsonContract valueContract = GetContractSafe(value);

              if (ShouldWriteReference(value, null, valueContract))
              {
            writer.WritePropertyName(propertyName);
            WriteReference(writer, value);
              }
              else
              {
            if (!CheckForCircularReference(value, null))
              continue;

            writer.WritePropertyName(propertyName);

            SerializeValue(writer, value, null, valueContract);
              }
            }
            catch (Exception ex)
            {
              if (IsErrorHandled(values, contract, propertyName, ex))
            HandleError(writer, initialDepth);
              else
            throw;
            }
              }

              writer.WriteEndObject();
              SerializeStack.RemoveAt(SerializeStack.Count - 1);

              contract.InvokeOnSerialized(values, Serializer.Context);
        }
Example #28
0
 protected virtual void AssertPlainMapContent(IDictionary map)
 {
     Assert.AreEqual(ItemFactory().ContainerClass(), map.GetType());
     Assert.AreEqual(Elements().Length, map.Count);
     for (var eltIdx = 0; eltIdx < Elements().Length; eltIdx++)
     {
         Assert.AreEqual(Values()[eltIdx], map[Elements()[eltIdx]]);
     }
 }
        private fsResult AddItemToDictionary(IDictionary dictionary, object key, object value) {
            // Because we're operating through the IDictionary interface by default (and not the
            // generic one), we normally send items through IDictionary.Add(object, object). This
            // works fine in the general case, except that the add method verifies that it's
            // parameter types are proper types. However, mono is buggy and these type checks do
            // not consider null a subtype of the parameter types, and exceptions get thrown. So,
            // we have to special case adding null items via the generic functions (which do not
            // do the null check), which is slow and messy.
            //
            // An example of a collection that fails deserialization without this method is
            // `new SortedList<int, string> { { 0, null } }`. (SortedDictionary is fine because
            // it properly handles null values).
            if (key == null || value == null) {
                // Life would be much easier if we had MakeGenericType available, but we don't. So
                // we're going to find the correct generic KeyValuePair type via a bit of trickery.
                // All dictionaries extend ICollection<KeyValuePair<TKey, TValue>>, so we just
                // fetch the ICollection<> type with the proper generic arguments, and then we take
                // the KeyValuePair<> generic argument, and whola! we have our proper generic type.

                var collectionType = fsReflectionUtility.GetInterface(dictionary.GetType(), typeof(ICollection<>));
                if (collectionType == null) {
                    return fsResult.Warn(dictionary.GetType() + " does not extend ICollection");
                }

                var keyValuePairType = collectionType.GetGenericArguments()[0];
                object keyValueInstance = Activator.CreateInstance(keyValuePairType, key, value);
                MethodInfo add = collectionType.GetFlattenedMethod("Add");
                add.Invoke(dictionary, new object[] { keyValueInstance });
                return fsResult.Success;
            }

            // We use the inline set methods instead of dictionary.Add; dictionary.Add will throw an exception
            // if the key already exists.
            dictionary[key] = value;
            return fsResult.Success;
        }
Example #30
0
        /// <summary>
        /// 转换字典类型的对象到LuaTable。
        /// </summary>
        /// <param name="target"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public static bool PackLuaTable(IDictionary target, out LuaTable result)
        {
            Type[] types = target.GetType().GetGenericArguments();
            result = new LuaTable();
            try
            {
                foreach (DictionaryEntry item in target)
                {
                    if (IsBaseType(types[1]))
                    {
                        object value;
                        if (types[1] == typeof(bool))//判断值是否布尔类型,是则做特殊转换
                            value = (bool)item.Value ? 1 : 0;
                        else
                            value = item.Value;

                        if (types[0] == typeof(int))//判断键是否为整型,是则标记键为整型,转lua table字符串时有用
                            result.Add(item.Key.ToString(), false, value);
                        else
                            result.Add(item.Key.ToString(), value);
                    }
                    else
                    {
                        LuaTable value;
                        var flag = PackLuaTable(item.Value, out value);
                        if (flag)
                        {
                            if (types[0] == typeof(int))
                                result.Add(item.Key.ToString(), false, value);
                            else
                                result.Add(item.Key.ToString(), value);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LoggerHelper.Error("PackLuaTable dictionary error: " + ex.Message);
            }
            return true;
        }