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;
 }
        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;
            }
        }
        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;
        }
Example #6
0
        internal static bool IsCaseSensitive(
            this IDictionary <string, object> dictionary
            )
        {
            var comparerProp = dictionary?.GetType().GetProperty("Comparer");

            return(comparerProp == null
                ? BruteForceIsCaseSensitive(dictionary)
                : !CaseInsensitiveComparers.Contains(comparerProp.GetValue(dictionary)));
        }
        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 #11
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();
        }
Example #13
0
        public static bool RenderIDictionary(ref Rect position, string key, IDictionary value, Action <object> setter)
        {
            var dirty      = false;
            var dictionary = value;
            var rect       = new Rect(position);

            foreach (var dictionaryKey in dictionary.Keys)
            {
                dirty |= RenderSystemObject(
                    ref rect,
                    dictionaryKey.ToString(),
                    dictionary[dictionaryKey]?.GetType(),
                    dictionary[dictionaryKey],
                    newValue => dictionary[dictionaryKey] = newValue,
                    type => value?.GetType().GetCustomAttribute(type));
                rect.y          += rect.height;
                position.height += rect.height;
                rect.height      = 0;
            }

            return(dirty);
        }
 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 #15
0
        public static bool RenderIDictionary(string key, IDictionary value, Action <object> setter)
        {
            var dirty      = false;
            var dictionary = value;

            var keys = new List <object>();

            foreach (var dictionaryKey in dictionary.Keys)
            {
                keys.Add(dictionaryKey);
            }

            foreach (var dictionaryKey in keys.ToList())
            {
                dirty |= RenderSystemObject(
                    dictionaryKey.ToString(),
                    dictionary[dictionaryKey]?.GetType(),
                    dictionary[dictionaryKey],
                    newValue => dictionary[dictionaryKey] = newValue,
                    type => value?.GetType().GetCustomAttribute(type));
            }

            return(dirty);
        }
        private void SerializeDictionary(IDictionary o, StringBuilder sb, int depth, Dictionary <object, bool> objectsInUse)
        {
            sb.Append('{');
            bool isFirstElement = true;

            foreach (DictionaryEntry entry in (IDictionary)o)
            {
                if (!isFirstElement)
                {
                    sb.Append(',');
                }
                string key = entry.Key as string;
                if (key == null)
                {
                    throw new SerializationException(SR.Format(SR.ObjectSerializer_DictionaryNotSupported, o.GetType().FullName));
                }
                SerializeString((string)entry.Key, sb);
                sb.Append(':');
                SerializeValue(entry.Value, sb, depth, objectsInUse);
                isFirstElement = false;
            }
            sb.Append('}');
        }
Example #17
0
        public static TomlTable CreateAttached <TValue>(
            this TomlObject rootSource,
            IDictionary <string, TValue> tableData,
            TomlTable.TableTypes type = TomlTable.TableTypes.Default)
        {
            if (tableData is TomlObject)
            {
                throw new ArgumentException(string.Format(TomlObjectCreateNotAllowed2A, nameof(tableData), tableData.GetType()));
            }

            var tbl = TomlTable.CreateFromDictionary(rootSource.Root, tableData, type);

            return(tbl);
        }
Example #18
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);
                }
            }
        }
Example #19
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 #20
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]]);
     }
 }
Example #21
0
        /// <summary>
        /// Create a parameter generator for a dynamic object.
        /// </summary>
        /// <param name="command">The command to parse.</param>
        /// <returns>An action that fills in the command parameters from a dynamic object.</returns>
        private static Action <IDbCommand, object> CreateDynamicInputParameterGenerator(IDbCommand command)
        {
            var provider   = InsightDbProvider.For(command);
            var parameters = provider.DeriveParameters(command);

            return((cmd, o) =>
            {
                // make sure that we have a dictionary implementation
                IDictionary <string, object> dyn = o as IDictionary <string, object>;
                if (dyn == null)
                {
                    throw new InvalidOperationException("Dynamic object must support IDictionary<string, object>.");
                }

                foreach (var template in parameters)
                {
                    var p = provider.CloneParameter(cmd, template);

                    // get the value from the object, converting null to db null
                    // note that if the dictionary does not have the value, we leave the value null and then the parameter gets defaulted
                    object value = null;
                    if (dyn.TryGetValue(p.ParameterName, out value))
                    {
                        if (value == null)
                        {
                            value = DBNull.Value;
                        }
                        else
                        {
                            DbType sqlType = LookupDbType(value.GetType(), null, p.DbType);
                            if (sqlType == DbTypeEnumerable)
                            {
                                cmd.Parameters.Add(p);
                                ListParameterHelper.ConvertListParameter(p, value, cmd);
                                continue;
                            }
                        }
                    }

                    p.Value = value;

                    // if it's a string, fill in the length
                    IDbDataParameter dbDataParameter = p as IDbDataParameter;
                    if (dbDataParameter != null)
                    {
                        string s = value as string;
                        if (s != null)
                        {
                            int length = s.Length;
                            if (length > 4000)
                            {
                                length = -1;
                            }
                            dbDataParameter.Size = length;
                        }
                    }

                    // explicitly set the type of the parameter
                    if (value != null && _typeToDbTypeMap.ContainsKey(value.GetType()))
                    {
                        dbDataParameter.DbType = _typeToDbTypeMap[value.GetType()];
                    }

                    provider.FixupParameter(cmd, p, p.DbType, dyn.GetType(), SerializationMode.Default);
                    cmd.Parameters.Add(p);
                }
            });
        }
        ////////////////////////////////////////////////////////////////////////

        public static Object Execute(DynLanContext EvaluateContext, Object obj, IList <Object> Parameters)
        {
            Object Collection = obj;
            Object value      = Parameters != null && Parameters.Count > 0 ? Parameters[0] : null;
            Object Key        = Parameters != null && Parameters.Count > 1 ? Parameters[1] : null;

            if (Collection == null)
            {
                return(null);
            }

            if (Collection is DynLanObject)
            {
                DynLanObject DynLanObj = Collection as DynLanObject;

                String finalKey = (String)(Key.GetType() == typeof(String) ? Key :
                                           Convert.ChangeType(Key, typeof(String), System.Globalization.CultureInfo.InvariantCulture));

                Object finValue = value == null ? null : (value.GetType() == typeof(Object) ? value :
                                                          Convert.ChangeType(value, typeof(Object), System.Globalization.CultureInfo.InvariantCulture));

                DynLanObj[finalKey] = finValue;

                return(value);
            }

            if (Collection is IDictionaryWithGetter)
            {
                IDictionaryWithGetter dict = (IDictionaryWithGetter)Collection;

                Type[] arguments = dict.GetType().GetGenericArguments();
                Type   keyType   = arguments[0];
                Type   valueType = arguments[1];

                Object finalKey = Key.GetType() == keyType ? Key :
                                  Convert.ChangeType(Key, keyType, System.Globalization.CultureInfo.InvariantCulture);

                Object finValue = value == null ? null : (value.GetType() == valueType ? value :
                                                          Convert.ChangeType(value, valueType, System.Globalization.CultureInfo.InvariantCulture));

                if (dict.CanSetValueToDictionary(finalKey))
                {
                    lock (dict)
                    {
                        dict.Remove(finalKey);
                        dict.Add(finalKey, finValue);
                    }
                }

                return(value);
            }

            else if (Collection is IDictionary)
            {
                IDictionary dict = (IDictionary)Collection;

                Type[] arguments = dict.GetType().GetGenericArguments();
                Type   keyType   = arguments[0];
                Type   valueType = arguments[1];

                Object finalKey = Key.GetType() == keyType ? Key :
                                  Convert.ChangeType(Key, keyType, System.Globalization.CultureInfo.InvariantCulture);

                Object finValue = value == null ? null : (value.GetType() == valueType ? value :
                                                          Convert.ChangeType(value, valueType, System.Globalization.CultureInfo.InvariantCulture));

                lock (dict)
                {
                    dict.Remove(finalKey);
                    dict.Add(finalKey, finValue);
                }

                return(value);
            }

            else if (Collection is IDictionary <string, object> )
            {
                IDictionary <string, object> dict = (IDictionary <string, object>)Collection;

                lock (dict)
                {
                    string finalKey = UniConvert.ToString(Key);
                    dict.Remove(finalKey);
                    dict.Add(finalKey, value);
                }

                return(value);
            }

            if (Collection is IList)
            {
                Int32?index = UniConvert.ToInt32N(Key);
                if (index == null || index < 0)
                {
                    return(null);
                }

                IList list = (IList)Collection;
                if (index >= list.Count)
                {
                    return(null);
                }

                Type listType = MyTypeHelper.GetListType(list);

                Object finValue = value == null ? null : (value.GetType() == listType ? value :
                                                          Convert.ChangeType(value, listType, System.Globalization.CultureInfo.InvariantCulture));

                list[index.Value] = finValue;

                return(value);
            }

            return(null);
        }
Example #23
0
        public static string ProcessParams(string _sql, object[] args_src, List <object> args_dest)
        {
            return(rxParamsPrefix.Replace(_sql, m =>
            {
                string param = m.Value.Substring(1);

                object arg_val;

                int paramIndex;
                if (Int32.TryParse(param, out paramIndex))
                {
                    // Numbered parameter
                    if (paramIndex < 0 || paramIndex >= args_src.Length)
                    {
                        throw new ArgumentOutOfRangeException(String.Format("Parameter '@{0}' specified but only {1} parameters supplied (in `{2}`)", paramIndex, args_src.Length, _sql));
                    }
                    arg_val = args_src[paramIndex];
                }
                else
                {
                    // Look for a property on one of the arguments with this name
                    bool found = false;
                    arg_val = null;
                    foreach (object o in args_src)
                    {
                        IDictionary dict = o as IDictionary;
                        if (dict != null)
                        {
                            Type[] arguments = dict.GetType().GetGenericArguments();

                            if (arguments[0] == typeof(string))
                            {
                                object val = dict[param];
                                if (val != null)
                                {
                                    found = true;
                                    arg_val = val;
                                    break;
                                }
                            }
                        }

                        PropertyInfo pi = o.GetType().GetProperty(param);
                        if (pi != null)
                        {
                            arg_val = pi.GetValue(o, null);
                            found = true;
                            break;
                        }
                    }

                    if (!found)
                    {
                        throw new ArgumentException(String.Format("Parameter '@{0}' specified but none of the passed arguments have a property with this name (in '{1}')", param, _sql));
                    }
                }

                // Expand collections to parameter lists
                if ((arg_val as System.Collections.IEnumerable) != null &&
                    (arg_val as string) == null &&
                    (arg_val as byte[]) == null)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (object i in arg_val as System.Collections.IEnumerable)
                    {
                        int indexOfExistingValue = args_dest.IndexOf(i);
                        if (indexOfExistingValue >= 0)
                        {
                            sb.Append((sb.Length == 0 ? "@" : ",@") + indexOfExistingValue);
                        }
                        else
                        {
                            sb.Append((sb.Length == 0 ? "@" : ",@") + args_dest.Count);
                            args_dest.Add(i);
                        }
                    }
                    if (sb.Length == 0)
                    {
                        sb.AppendFormat("select 1 /*poco_dual*/ where 1 = 0");
                    }
                    return sb.ToString();
                }
                else
                {
                    int indexOfExistingValue = args_dest.IndexOf(arg_val);
                    if (indexOfExistingValue >= 0)
                    {
                        return "@" + indexOfExistingValue;
                    }

                    args_dest.Add(arg_val);
                    return "@" + (args_dest.Count - 1).ToString();
                }
            }));
        }
Example #24
0
        public override bool Equals(object obj)
        {
            if (obj == null)
            {
                return(false);
            }

            PdxType other = obj as PdxType;

            if (other == null)
            {
                return(false);
            }

            if (other == this)
            {
                return(true);
            }

            compareByteByteArray(other.m_byteByteArray, m_byteByteArray);
            GenericValCompare(other.m_char, m_char);

            GenericValCompare(other.m_bool, m_bool);
            GenericCompare(other.m_boolArray, m_boolArray);

            GenericValCompare(other.m_byte, m_byte);
            GenericCompare(other.m_byteArray, m_byteArray);
            GenericCompare(other.m_charArray, m_charArray);

            compareCompareCollection(other.m_arraylist, m_arraylist);

            if (other.m_map.Count != m_map.Count)
            {
                throw new IllegalStateException("Not got expected value for type: " + m_map.GetType().ToString());
            }

            if (other.m_hashtable.Count != m_hashtable.Count)
            {
                throw new IllegalStateException("Not got expected value for type: " + m_hashtable.GetType().ToString());
            }

            if (other.m_vector.Count != m_vector.Count)
            {
                throw new IllegalStateException("Not got expected value for type: " + m_vector.GetType().ToString());
            }

            if (other.m_chs.Count != m_chs.Count)
            {
                throw new IllegalStateException("Not got expected value for type: " + m_chs.GetType().ToString());
            }

            if (other.m_clhs.Count != m_clhs.Count)
            {
                throw new IllegalStateException("Not got expected value for type: " + m_clhs.GetType().ToString());
            }


            GenericValCompare(other.m_string, m_string);

            compareData(other.m_dateTime, m_dateTime);

            GenericValCompare(other.m_double, m_double);

            GenericCompare(other.m_doubleArray, m_doubleArray);
            GenericValCompare(other.m_float, m_float);
            GenericCompare(other.m_floatArray, m_floatArray);
            GenericValCompare(other.m_int16, m_int16);
            GenericValCompare(other.m_int32, m_int32);
            GenericValCompare(other.m_long, m_long);
            GenericCompare(other.m_int32Array, m_int32Array);
            GenericCompare(other.m_longArray, m_longArray);
            GenericCompare(other.m_int16Array, m_int16Array);
            GenericValCompare(other.m_sbyte, m_sbyte);
            GenericCompare(other.m_sbyteArray, m_sbyteArray);
            GenericCompare(other.m_stringArray, m_stringArray);
            GenericValCompare(other.m_uint16, m_uint16);
            GenericValCompare(other.m_uint32, m_uint32);
            GenericValCompare(other.m_ulong, m_ulong);
            GenericCompare(other.m_uint32Array, m_uint32Array);
            GenericCompare(other.m_ulongArray, m_ulongArray);
            GenericCompare(other.m_uint16Array, m_uint16Array);

            if (m_byte252.Length != 252 && other.m_byte252.Length != 252)
            {
                throw new Exception("Array len 252 not found");
            }

            if (m_byte253.Length != 253 && other.m_byte253.Length != 253)
            {
                throw new Exception("Array len 253 not found");
            }

            if (m_byte65535.Length != 65535 && other.m_byte65535.Length != 65535)
            {
                throw new Exception("Array len 65535 not found");
            }

            if (m_byte65536.Length != 65536 && other.m_byte65536.Length != 65536)
            {
                throw new Exception("Array len 65536 not found");
            }
            if (m_pdxEnum != other.m_pdxEnum)
            {
                throw new Exception("pdx enum is not equal");
            }

            {
                for (int i = 0; i < m_address.Length; i++)
                {
                    if (!m_address[i].Equals(other.m_address[i]))
                    {
                        throw new Exception("Address array not mateched " + i);
                    }
                }
            }

            for (int i = 0; i < m_objectArray.Count; i++)
            {
                if (!m_objectArray[i].Equals(other.m_objectArray[i]))
                {
                    return(false);
                }
            }
            return(true);
        }
Example #25
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 #26
0
        public virtual int Update(IDictionary <string, object> o, IList <WhereClause> where)
        {
            ISqlMapper mapper = new UpdateByIDMapper(Factory.CreateConverter(_helper.DBType));
            var        model  = mapper.ObjectToSql(Common.GetTableName(_key, _config.Owner, o.GetType(), _config, o), o, where, _config);
            int        result = 0;

            result = _helper.ExecNoneQueryWithSQL(model.SQL, model.Parameters.ToArray());
            return(result);
        }
Example #27
0
        public virtual DataTable SelectTopN(int TopN, IDictionary <string, object> o, IList <WhereClause> where, OrderByClause orderby)
        {
            SelectTopNMapper mapper = new SelectTopNMapper(Factory.CreateConverter(_helper.DBType));

            mapper.TopN    = TopN;
            mapper.OrderBy = orderby;

            var       model = mapper.ObjectToSql(Common.GetTableName(_key, _config.Owner, o.GetType(), _config, o), o, where, _config);
            DataTable table = new DataTable();

            table = _helper.GetTableWithSQL(model.SQL, model.Parameters.ToArray());
            return(table);
        }
Example #28
0
 public static V GetOrThrow <K, V>(this IDictionary <K, V> dictionary, K key)
     where K : notnull
 {
     if (!dictionary.TryGetValue(key, out V result))
     {
         throw new KeyNotFoundException("Key '{0}' ({1}) not found on {2}".FormatWith(key, key.GetType().TypeName(), dictionary.GetType().TypeName()));
     }
     return(result);
 }
Example #29
0
 private Type APIType(IDictionary d)
 {
     return(d.GetType().GetGenericArguments()[1]);
 }
Example #30
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 #31
0
        public static bool IsValid(this IDictionary <string, object> @this, IDictionary <string, ValidationAttribute[]> validationAttrDict, out Exception aggEx)
        {
            aggEx = null;

            if (@this == null)
            {
                return(true);
            }

            var results = new List <ValidationResult>();
            var context = new ValidationContext(@this, null, null);

            foreach (var kvp in @this)
            {
                if (!validationAttrDict.ContainsKey(kvp.Key) ||
                    validationAttrDict[kvp.Key].IsNullOrEmpty())
                {
                    continue;
                }

                context.MemberName = kvp.Key;
                Validator.TryValidateValue(kvp.Value, context, results, validationAttrDict[kvp.Key]);
            }

            if (results.Count > 0)
            {
                aggEx = new ApplicationException("Failed to validate '{0}' object. {2}{1}".FormatString(@this.GetType().FullName, ToString(results), Environment.NewLine));
                return(false);
            }
            else
            {
                return(true);
            }
        }
Example #32
0
        private static void WriteValue(object obj, JsonWriter writer, bool privateWriter, int depth)
        {
            if (depth > maxNestingDepth)
            {
                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 (privateWriter)
                {
                    writer.TextWriter.Write(((IJsonWrapper)obj).ToJson());
                }
                else
                {
                    ((IJsonWrapper)obj).ToJson(writer);
                }
                return;
            }
            if (obj is string)
            {
                writer.Write((string)obj);
                return;
            }
            if (obj is double)
            {
                writer.Write((double)obj);
                return;
            }
            if (obj is long)
            {
                writer.Write((long)obj);
                return;
            }
            if (obj is bool)
            {
                writer.Write((bool)obj);
                return;
            }
            if (obj is Array)
            {
                writer.WriteArrayStart();
                Array arr      = (Array)obj;
                Type  elemType = arr.GetType().GetElementType();
                foreach (object elem in arr)
                {
                    // if the collection contains polymorphic elements, we need to include type information for deserialization
                    if (writer.TypeHinting && elem != null & elem.GetType() != elemType)
                    {
                        writer.WriteObjectStart();
                        writer.WritePropertyName(writer.HintTypeName);
                        writer.Write(elem.GetType().FullName);
                        writer.WritePropertyName(writer.HintValueName);
                        WriteValue(elem, writer, privateWriter, depth + 1);
                        writer.WriteObjectEnd();
                    }
                    else
                    {
                        WriteValue(elem, writer, privateWriter, depth + 1);
                    }
                }
                writer.WriteArrayEnd();
                return;
            }
            if (obj is IList)
            {
                writer.WriteArrayStart();
                IList list = (IList)obj;
                // collection might be non-generic type like Arraylist
                Type elemType = typeof(object);
                if (list.GetType().GetGenericArguments().Length > 0)
                {
                    // collection is a generic type like List<T>
                    elemType = list.GetType().GetGenericArguments()[0];
                }
                foreach (object elem in list)
                {
                    // if the collection contains polymorphic elements, we need to include type information for deserialization
                    if (writer.TypeHinting && elem != null && elem.GetType() != elemType)
                    {
                        writer.WriteObjectStart();
                        writer.WritePropertyName(writer.HintTypeName);
                        writer.Write(elem.GetType().AssemblyQualifiedName);
                        writer.WritePropertyName(writer.HintValueName);
                        WriteValue(elem, writer, privateWriter, depth + 1);
                        writer.WriteObjectEnd();
                    }
                    else
                    {
                        WriteValue(elem, writer, privateWriter, depth + 1);
                    }
                }
                writer.WriteArrayEnd();
                return;
            }
            if (obj is IDictionary)
            {
                writer.WriteObjectStart();
                IDictionary dict = (IDictionary)obj;
                // collection might be non-generic type like Hashtable
                Type elemType = typeof(object);
                if (dict.GetType().GetGenericArguments().Length > 1)
                {
                    // collection is a generic type like Dictionary<T, V>
                    elemType = dict.GetType().GetGenericArguments()[1];
                }
                foreach (DictionaryEntry entry in dict)
                {
                    writer.WritePropertyName((string)entry.Key);
                    // if the collection contains polymorphic elements, we need to include type information for deserialization
                    if (writer.TypeHinting && entry.Value != null && entry.Value.GetType() != elemType)
                    {
                        writer.WriteObjectStart();
                        writer.WritePropertyName(writer.HintTypeName);
                        writer.Write(entry.Value.GetType().AssemblyQualifiedName);
                        writer.WritePropertyName(writer.HintValueName);
                        WriteValue(entry.Value, writer, privateWriter, depth + 1);
                        writer.WriteObjectEnd();
                    }
                    else
                    {
                        WriteValue(entry.Value, writer, privateWriter, depth + 1);
                    }
                }
                writer.WriteObjectEnd();
                return;
            }
            Type objType = obj.GetType();
            // Try a base or custom importer if one exists
            ExporterFunc exporter = GetExporter(objType);

            if (exporter != null)
            {
                exporter(obj, writer);
                return;
            }
            // Last option, let's see if it's an enum
            if (obj is Enum)
            {
                Type enumType = Enum.GetUnderlyingType(objType);
                if (enumType == typeof(long))
                {
                    writer.Write((long)obj);
                }
                else
                {
                    ExporterFunc enumConverter = GetExporter(enumType);
                    if (enumConverter != null)
                    {
                        enumConverter(obj, writer);
                    }
                }
                return;
            }

            // What if it's a Guid?
            if (obj is System.Guid)
            {
                writer.Write(((System.Guid)obj).ToString());
                return;
            }

            // Okay, it looks like the input should be exported as an object
            ObjectMetadata tdata = AddObjectMetadata(objType);

            writer.WriteObjectStart();
            foreach (string property in tdata.Properties.Keys)
            {
                PropertyMetadata pdata = tdata.Properties[property];
                // Don't serialize soft aliases (which get added to ObjectMetadata.Properties twice).
                if (pdata.Alias != null && property != pdata.Info.Name && tdata.Properties.ContainsKey(pdata.Info.Name))
                {
                    continue;
                }
                // Don't serialize a field or property with the JsonIgnore attribute with serialization usage
                if ((pdata.Ignore & JsonIgnoreWhen.Serializing) > 0)
                {
                    continue;
                }
                if (pdata.IsField)
                {
                    FieldInfo info = (FieldInfo)pdata.Info;
                    if (pdata.Alias != null)
                    {
                        writer.WritePropertyName(pdata.Alias);
                    }
                    else
                    {
                        writer.WritePropertyName(info.Name);
                    }
                    object value = info.GetValue(obj);
                    if (writer.TypeHinting && value != null && info.FieldType != value.GetType())
                    {
                        // the object stored in the field might be a different type that what was declared, need type hinting
                        writer.WriteObjectStart();
                        writer.WritePropertyName(writer.HintTypeName);
                        writer.Write(value.GetType().AssemblyQualifiedName);
                        writer.WritePropertyName(writer.HintValueName);
                        WriteValue(value, writer, privateWriter, depth + 1);
                        writer.WriteObjectEnd();
                    }
                    else
                    {
                        WriteValue(value, writer, privateWriter, depth + 1);
                    }
                }
                else
                {
                    PropertyInfo info = (PropertyInfo)pdata.Info;
                    if (info.CanRead)
                    {
                        if (pdata.Alias != null)
                        {
                            writer.WritePropertyName(pdata.Alias);
                        }
                        else
                        {
                            writer.WritePropertyName(info.Name);
                        }
                        object value = info.GetValue(obj, null);
                        if (writer.TypeHinting && value != null && info.PropertyType != value.GetType())
                        {
                            // the object stored in the property might be a different type that what was declared, need type hinting
                            writer.WriteObjectStart();
                            writer.WritePropertyName(writer.HintTypeName);
                            writer.Write(value.GetType().AssemblyQualifiedName);
                            writer.WritePropertyName(writer.HintValueName);
                            WriteValue(value, writer, privateWriter, depth + 1);
                            writer.WriteObjectEnd();
                        }
                        else
                        {
                            WriteValue(value, writer, privateWriter, depth + 1);
                        }
                    }
                }
            }
            writer.WriteObjectEnd();
        }
Example #33
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;

        }
        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();
        }
Example #35
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);
             }
         }
     }
 }
 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 #37
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();
        }
        public static IDictionary <TKey, TValue> Clone <TKey, TValue>
            (this IDictionary <TKey, TValue> original) where TValue : ICloneable
        {
            IDictionary <TKey, TValue> ret = (IDictionary <TKey, TValue>)Activator.CreateInstance(original.GetType());

            foreach (KeyValuePair <TKey, TValue> entry in original)
            {
                ret.Add(entry.Key, (TValue)entry.Value.Clone());
            }
            return(ret);
        }
Example #39
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;
        }
			public string Amb(IDictionary obj)
			{
				return obj.GetType().Name;
			}
        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 #42
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");
        }
Example #43
0
        internal void Serialize(IDictionary <TKey, TVal> dictionary, BinaryWriter writer)
        {
            if (dictionary == null)
            {
                writer.Write(NullLength);
                return;
            }

            writer.Write(dictionary.Count());
            var constructorIndex = _constructorsByType.TryGetValue((uint)RuntimeHelpers.GetHashCode(dictionary.GetType())).Index;

            writer.Write(constructorIndex);
            foreach (var item in dictionary)
            {
                _keySerializer(item.Key, writer);
                _valSerializer(item.Value, writer);
            }
        }
 public string Amb(IDictionary obj)
 {
     return(obj.GetType().Name);
 }
Example #45
0
        private object CloneObject(object obj)
        {
            // If it's null, return null
            if (obj == null)
            {
                return(null);
            }

            // If it's a list, we copy it.
            if (obj is IList && obj.GetType().IsGenericType&& obj.GetType().GetGenericTypeDefinition().IsAssignableFrom(typeof(List <>)))
            {
                // Create a new list of the same type.
                IList originalList = ((IList)obj);
                IList copyList     = (IList)Activator.CreateInstance(originalList.GetType());

                // Copy all the items from one list to the other.
                for (int i = 0; i < originalList.Count; i++)
                {
                    copyList.Add(CloneObject(originalList[i]));
                }

                // Return our copied list
                return(copyList);
            }

            // If it's a dictionary, we copy it.
            if (obj is IDictionary && obj.GetType().IsGenericType&& obj.GetType().GetGenericTypeDefinition().IsAssignableFrom(typeof(Dictionary <,>)))
            {
                // Create a new dictionary of the same type.
                IDictionary originalDictionary = ((IDictionary)obj);
                IDictionary copyDictionary     = ((IDictionary)Activator.CreateInstance(originalDictionary.GetType()));

                // Copy all of the items from one dictionary to the other.
                foreach (object key in originalDictionary.Keys)
                {
                    copyDictionary[key] = CloneObject(originalDictionary[key]);
                }

                // Return our copied
                return(copyDictionary);
            }

            // If this is a cloneable object, clone it.
            if (obj is ICloneable)
            {
                return(((ICloneable)obj).Clone());
            }


            // Return the object.
            return(obj);
        }
Example #46
0
        IAssignmentCollection FilterUsers(Func <IAssignment, bool> cb)
        {
            IDictionary <int, IAssignment> mapOfSubset = (IDictionary <int, IAssignment>)Activator.CreateInstance(map.GetType());

            foreach (var pair in map)
            {
                if (cb(pair.Value))
                {
                    mapOfSubset.Add(pair.Key, pair.Value);
                }
            }
            return(new AssignmentManager(mapOfSubset));
        }
Example #47
0
        public override int InsertOrUpdate(IDictionary <string, object> o)
        {
            ISqlMapper mapper = new InsertOrUpdateMapper(Factory.CreateConverter(_helper.DBType));
            var        model  = mapper.ObjectToSql(Common.GetTableName(_key, _config.Owner, o.GetType(), _config, o), o, null, _config);
            int        result = 0;

            result = _helper.ExecNoneQueryWithSQL(model.SQL, model.Parameters.ToArray());
            return(result);
        }
        private void SerializeDictionary(IDictionary o, StringBuilder sb, int depth, Hashtable objectsInUse, SerializationFormat serializationFormat)
        {
            sb.Append('{');
            bool flag  = true;
            bool flag2 = false;

            if (o.Contains("__type"))
            {
                flag  = false;
                flag2 = true;
                this.SerializeDictionaryKeyValue("__type", o["__type"], sb, depth, objectsInUse, serializationFormat);
            }
            foreach (DictionaryEntry entry in o)
            {
                string key = entry.Key as string;
                if (key == null)
                {
                    throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, " JSON_DictionaryTypeNotSupported", new object[] { o.GetType().FullName }));
                }
                if (flag2 && string.Equals(key, "__type", StringComparison.Ordinal))
                {
                    flag2 = false;
                }
                else
                {
                    if (!flag)
                    {
                        sb.Append(',');
                    }
                    this.SerializeDictionaryKeyValue(key, entry.Value, sb, depth, objectsInUse, serializationFormat);
                    flag = false;
                }
            }
            sb.Append('}');
        }
    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);
    }
Example #50
0
        private void SerializeDictionary(IDictionary o, StringBuilder sb, int depth, Hashtable objectsInUse)
        {
            sb.Append('{');
            bool isFirstElement = true, isTypeEntrySet = false;

            //make sure __type field is the first to be serialized if it exists
            if (o.Contains(ServerTypeFieldName))
            {
                isFirstElement = false;
                isTypeEntrySet = true;
                SerializeDictionaryKeyValue(ServerTypeFieldName, o[ServerTypeFieldName], sb, depth, objectsInUse);
            }

            foreach (DictionaryEntry entry in o)
            {
                var key = entry.Key as string;
                if (key == null)
                {
                    throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, AtlasWeb.JSON_DictionaryTypeNotSupported, o.GetType().FullName));
                }

                if (isTypeEntrySet && string.Equals(key, ServerTypeFieldName, StringComparison.Ordinal))
                {
                    // The dictionay only contains max one entry for __type key, and it has been iterated
                    // through, so don't need to check for is anymore.
                    isTypeEntrySet = false;
                    continue;
                }
                if (!isFirstElement)
                {
                    sb.Append(',');
                }

                this.SerializeDictionaryKeyValue(key, entry.Value, sb, depth, objectsInUse);
                isFirstElement = false;
            }
            sb.Append('}');
        }
Example #51
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 #52
0
        public static long?getOptionalLong(IDictionary <string, object> data, string key)
        {
            data.TryGetValue(key, out object val);
            if (val == null)
            {
                return(null);
            }
            else if (val is long)
            {
                return((long?)val);
            }

            throw new ArgumentException($"Expected value of type long for key {key}, instead got value of type {data.GetType().FullName}");
        }
        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 #54
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();
 }
        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;
        }
        public IDictionary ReadMap <T>(T arg, int tag, bool isRequire)
        {
            IDictionary map = BasicClassTypeUtil.CreateObject(arg.GetType()) as IDictionary;

            if (map == null)
            {
                return(null);
            }

            Type type = map.GetType();

            Type[] argsType = type.GetGenericArguments();
            if (argsType == null || argsType.Length < 2)
            {
                return(null);
            }

            var mk = BasicClassTypeUtil.CreateObject(argsType[0]);
            var mv = BasicClassTypeUtil.CreateObject(argsType[1]);

            if (SkipToTag(tag))
            {
                HeadData head = new HeadData();
                ReadHead(head);
                switch (head.type)
                {
                case (byte)TarsStructType.MAP:
                {
                    int size = Read(0, 0, true);
                    if (size < 0)
                    {
                        throw new TarsDecodeException("size invalid: " + size);
                    }
                    for (int i = 0; i < size; ++i)
                    {
                        mk = Read(mk, 0, true);
                        mv = Read(mv, 1, true);

                        if (mk != null)
                        {
                            if (map.Contains(mk))
                            {
                                map[mk] = mv;
                            }
                            else
                            {
                                map.Add(mk, mv);
                            }
                        }
                    }
                }
                break;

                default:
                {
                    throw new TarsDecodeException("type mismatch.");
                }
                }
            }
            else if (isRequire)
            {
                throw new TarsDecodeException("require field not exist.");
            }
            return(map);
        }