Ejemplo n.º 1
1
        public static void CalculateTime(IList list, int k)
        {
            // Add
            var startAdding = DateTime.Now;
            string test = "Test string";
            for (int i = 0; i < k; i++)
            {
                list.Add(test);
            }
            var finishAdding = DateTime.Now;
            Console.WriteLine("Addition time (" + k + " elements) : " + list.GetType() + "  " + (finishAdding - startAdding));
            // Search
            var startSearch = DateTime.Now;
            for (int i = 0; i < k; i++)
            {
                bool a = list.Contains(test);
            }
            var finishSearch = DateTime.Now;
            Console.WriteLine("Search time (" + k + " elements) : " + list.GetType() + "  " + (finishSearch - startSearch));

            // Remove
            k = 1000;
            var startRemoving = DateTime.Now;
            for (int i = 0; i < k; i++)
            {
                list.Remove(test);
            }
            var finishRemoving = DateTime.Now;
            Console.WriteLine("Removal time (" + k + " elements) : " + list.GetType() + "  " + (finishRemoving - startRemoving) + "\n");
        }
        protected virtual void OnItemsSourceChanged(IList oldValue, IList newValue)
        {
            if (newValue == null)
                return;

            if (ItemsSourceType == null)
                ItemsSourceType = newValue.GetType();

            if (ItemType == null)
                ItemType = newValue.GetType().GetGenericArguments()[0];

            if (newValue.Count > 0)
                SetText(newValue);
        }
Ejemplo n.º 3
1
        public static IList<IDatabaseObject> FindNew(IList<IDatabaseObject> oldsource, IList<IDatabaseObject> newsource)
        {
            if (oldsource.GetType() != newsource.GetType())
                throw new Exception("Die Datentypen müssen für einen Vergleich gleich sein.");

            if (oldsource.Count < 1) return newsource;

            List<IDatabaseObject> result = new List<IDatabaseObject>();
            Type t = oldsource[0].GetType();
            PropertyInfo i = t.GetProperty("ObjectID");

            
            
            if(i != null)
                foreach (IDatabaseObject a in newsource)
                {
                    bool isContained = false;
                    foreach (IDatabaseObject b in oldsource)
                    {
                        int id1 = (int)i.GetValue(a, null);
                        int id2 = (int)i.GetValue(b, null);
                        if (id1 == id2)
                        {
                            isContained = true;
                            break;
                        }
                    }


                    if (!isContained) result.Add(a);
                }

            return result;
        }
        /// <summary>
        /// Metodo para serializar una Lista de objetos en un XML simple
        /// </summary>
        /// <param name="thelist"> la lista de tipo List<T> </param>
        /// <returns></returns>
        public static string List2XML(IList thelist)
        {
            string xml = "";

            try
            {


                XmlSerializer xmlSer = new XmlSerializer(thelist.GetType());
                StringWriterWithEncoding sWriter = new StringWriterWithEncoding(Encoding.UTF8);

                XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
                xsn.Add(String.Empty, "");

                xmlSer.Serialize(sWriter, thelist, xsn);

                xml = sWriter.ToString();

              



            }
            catch (Exception e)
            {
               
            }

            return xml;
        }
Ejemplo n.º 5
1
 public static String GetClipboardTextFromIList(IList argList, CultureInfo argCultureInfo, Boolean argWithHeaders, String argCellSeparator)
 {
     // Create the StringBuilder
     StringBuilder finalBuilder = new StringBuilder();
     if (argWithHeaders)
     {
         foreach (PropertyInfo prop in argList.GetType().GetGenericArguments()[0].GetProperties())
         {
             finalBuilder.AppendFormat("{0}{1}", GetClipboardTextFromValueObject(prop.Name, argCultureInfo).Replace(argCellSeparator, String.Empty), argCellSeparator);
         }
         if (finalBuilder.Length > argCellSeparator.Length - 1)
         {
             finalBuilder.Length -= argCellSeparator.Length; //remove cell separator character
         }
         finalBuilder.Append("\r\n"); // add \r\n
     }
     foreach (Object item in argList)
     {
         finalBuilder.AppendFormat("{0}\r\n", GetClipboardTextFromObject(item, argCultureInfo, argCellSeparator)); // add \r\n
     }
     if (finalBuilder.Length > 1)
     {
         finalBuilder.Length -= 2; //remove \r\n character
     }
     return finalBuilder.ToString();
 }
        public IListTypeDefinitionFinder(IList list)
        {
            if (list == null) throw new ArgumentNullException("list");

            _listType = list.GetType();
            SetListTypeUnderlyingType();
        }
        public static void Apply(this FilterScheme filterScheme, IEnumerable rawCollection, IList filteredCollection)
        {
            Argument.IsNotNull("filterScheme", filterScheme);
            Argument.IsNotNull("rawCollection", rawCollection);
            Argument.IsNotNull("filteredCollection", filteredCollection);

            IDisposable suspendToken = null;
            var filteredCollectionType = filteredCollection.GetType();
            if (filteredCollectionType.IsGenericTypeEx() && filteredCollectionType.GetGenericTypeDefinitionEx() == typeof(FastObservableCollection<>))
            {
                suspendToken = (IDisposable)filteredCollectionType.GetMethodEx("SuspendChangeNotifications").Invoke(filteredCollection, null);
            }

            filteredCollection.Clear();

            foreach (object item in rawCollection)
            {
                if (filterScheme.CalculateResult(item))
                {
                    filteredCollection.Add(item);
                }
            }

            if (suspendToken != null)
            {
                suspendToken.Dispose();
            }
        }
Ejemplo n.º 8
1
        //ArrayList openElements = new ArrayList();
        public void SerializeXml(IList<StarSystem> starSystems)
        {
            MemoryStream memXmlStream = new MemoryStream();
            XmlSerializer serializer = new XmlSerializer(starSystems.GetType(), null, new Type[] { typeof(Planet), typeof(StarSystem) }, new XmlRootAttribute("Stars"), null, null);

            serializer.Serialize(memXmlStream, starSystems);

            XmlDocument xmlDoc = new XmlDocument();

            memXmlStream.Seek(0, SeekOrigin.Begin);
            xmlDoc.Load(memXmlStream);

            XmlProcessingInstruction newPI;
            String PItext = string.Format("type='text/xsl' href='{0}'", "system.xslt");
            newPI = xmlDoc.CreateProcessingInstruction("xml-stylesheet", PItext);

            xmlDoc.InsertAfter(newPI, xmlDoc.FirstChild);

            // Now write the document

            // out to the final output stream

            XmlTextWriter wr = new XmlTextWriter("system.xml", System.Text.Encoding.ASCII);
            wr.Formatting = Formatting.Indented;
            wr.IndentChar = '\t';
            wr.Indentation = 1;

            XmlWriterSettings settings = new XmlWriterSettings();
            XmlWriter writer = XmlWriter.Create(wr, settings);

            xmlDoc.WriteTo(writer);
            writer.Flush();
            //Console.Write(xmlDoc.InnerXml);
        }
Ejemplo n.º 9
1
 public ArrayAdapter(IValue array)
 {
     _array = array;
     _list = array.ActualType.CreateGenericListInstance().As<IList>();
     _listType = _list.GetType().ToCachedType();
     _listType.InvokeAction("AddRange", _list, array.Instance);
 }
Ejemplo n.º 10
1
		public ListSource(DialogViewController controller, IList list, IEnumerable<Type> viewTypes) : base(controller)
		{	
			Sections = new Dictionary<int, Section>();
			var section = new Section(controller) { DataContext = list };

			IList<Type> viewTypesList = null;
			if (viewTypes != null)
				viewTypesList = viewTypes.ToList();

			var genericType = list.GetType().GetGenericArguments().FirstOrDefault();
			CellId = new NSString(genericType.ToString());

			section.ViewTypes.Add(CellId, viewTypesList);
			
			Sections.Add(0, section);

			SelectedItems = list.GetType().CreateGenericListFromEnumerable(null);

			CellFactory = new TableCellFactory<UITableViewCell>(CellId);

//SelectionDisplayMode = SelectionDisplayMode.Collapsed;
//CollapsedList = new List<object>();
//			foreach(var item in Sections[0].DataContext)
//			{
//				CollapsedList.Add(item);
//			}
//			Sections[0].DataContext.Clear();
//
//IsCollapsed = true;
		}
Ejemplo n.º 11
1
        public object ToJsonR(IList items, Style style = Style.Full)
        {
            var jsonR = new JsonR();

            Type itemType = GetListItemType(items.GetType());
            jsonR.Type    = itemType.Name;

            SplitKeyValues(items, jsonR.Keys, jsonR.Values);
            switch (style)
            {
                case Style.Keys:
                    return jsonR.Keys;

                case Style.Values:
                    return jsonR.Values;

                case Style.Type:
                    return jsonR.Type;

                case Style.Hint:
                    return new {jsonR.Type, jsonR.Values };
            }

            return jsonR;
        }
Ejemplo n.º 12
1
 public static Type GetListElementsType(IList Collection)
 {
     if (Collection == null)
     {
         return null;
     }
     else
     {
         return Collection.GetType().GenericTypeArguments.Single();
     }
 }
Ejemplo n.º 13
1
        /// <summary>
        /// Clones an IList object and returns a list with the same type as the original list.
        /// </summary>
        public static IList CloneList(IList list)
        {
            if (list == null)
                return null;

            var newList = Activator.CreateInstance(list.GetType()) as IList;
            foreach (var item in list)
                newList.Add(item);

            return newList;
        }
Ejemplo n.º 14
1
            public SelectedItemsReflector(ListBox target, IList mirror)
            {
                if ((_target = target) == null) throw new ArgumentNullException("'target' cannot be null");
                if ((_mirror = mirror) == null) throw new ArgumentNullException("'mirror' cannot be null");

                var observable = _mirror as INotifyCollectionChanged;
                if (observable == null) throw new ArgumentException(String.Format("'mirror' has to be an instance of {0}, but {1}", typeof(INotifyCollectionChanged), _mirror.GetType()));

                _target.SelectionChanged -= SelectionChangedEventHandler;

                _target.SelectedItems.Clear();
                foreach (var item in _mirror) _target.SelectedItems.Add(item);

                _target.SelectionChanged += SelectionChangedEventHandler;
                observable.CollectionChanged += CollectionChangedEventHandler;
            }
Ejemplo n.º 15
0
        public static bool RenderIList(ref Rect position, string key, IList value, Action <object> setter)
        {
            var dirty = false;
            var rect  = new Rect(position);
            var index = 0;

            rect.height = 0;

            foreach (var element in value)
            {
                dirty |= RenderSystemObject(
                    ref rect,
                    $"{key}[{index}]",
                    element?.GetType(),
                    element,
                    newValue => value[index] = newValue,
                    type => value?.GetType().GetCustomAttribute(type));
                rect.y          += rect.height;
                position.height += rect.height;
                rect.height      = 0;

                index++;
            }

            return(true);
        }
Ejemplo n.º 16
0
        public static MvcHtmlString ListaDinamica(this HtmlHelper html, string id, IList lista)
        {
            string strLink = String.Format("<ul data-role=\"listview\" data-filter=\"true\" data-filter-placeholder=\"Buscar...\" data-inset=\"true\">");

            PropertyInfo[] properties = lista.GetType().GetProperties();
            foreach (PropertyInfo property in properties)
            {
                if (property.PropertyType.Name == "Categoria")
                {
                    foreach (Entities.Categoria categoria in lista)
                    {
                        strLink += ("<li><a href=\"../Categoria/Editar/"+ categoria.Id.ToString() +"\">" + categoria.Nome.ToString() + "</a></li>");
                    }
                }
            }
            strLink += ("</ul>");
            return new MvcHtmlString(strLink);
        }
Ejemplo n.º 17
0
        public DbSetMock(Type entityType, IList observableCollectionList)
            : base()
        {
            if (observableCollectionList.GetType().GetGenericTypeDefinition() != typeof(ObservableCollection<>))
            {
                throw new ArgumentException("El parametro debe de ser de tipo ObservableCollection<>");
            }

            this.entityType = entityType;
            this.observableCollectionList = observableCollectionList;
            this.primaryKey = entityType
              .GetProperties()
              .Select(x => new { name = x.Name, att = x.GetCustomAttribute<KeyAttribute>(), order = x.GetCustomAttribute<ColumnAttribute>()?.Order ?? 0 })
              .Where(x => x.att != null)
              .OrderBy(x => x.order)
              .Select(x => x.name)
              .ToList();
        }
Ejemplo n.º 18
0
        public static bool RenderIList(string key, IList value, Action <object> setter)
        {
            var dirty = false;
            var index = 0;

            foreach (var element in value)
            {
                dirty |= RenderSystemObject(
                    $"{key}[{index}]",
                    element?.GetType(),
                    element,
                    newValue => value[index] = newValue,
                    type => value?.GetType().GetCustomAttribute(type));

                index++;
            }

            return(true);
        }
Ejemplo n.º 19
0
 protected virtual void AssignContentToList(IList list, XmlNodeList contentNodes, Func<Type, IParcer> valueParcerResolver)
 {
     Assert.ArgumentNotNull(list, "list");
       var listGenericArgument = this.GetListGenericArgumentType(list.GetType());
       if (listGenericArgument == null)
       {
     throw new Exception("Unexpected value");
       }
       IParcer parcer = valueParcerResolver(listGenericArgument);
       if (parcer == null)
       {
     return;
       }
       foreach (XmlNode contentNode in contentNodes)
       {
     try
     {
       object contentValue = null;
       if (contentNode.FirstChild != null)
       {
     contentValue = parcer.ParceNodeValue(contentNode.FirstChild);
       }
       if (contentValue == null)
       {
     contentValue = parcer.ParceNodeValue(contentNode);
       }
       if (contentValue == null)
       {
     continue;
       }
       if (!listGenericArgument.IsInstanceOfType(contentValue))
       {
     continue;
       }
       list.Add(contentValue);
     }
     catch (Exception ex)
     {
       Log.Error("Can't parce node value", ex, this);
     }
       }
 }
        public IList TransformList(IList list)
        {
            IList result   = (IList)Activator.CreateInstance(list.GetType());
            var   distinct = new HashSet <Identity>();

            for (int i = 0; i < list.Count; i++)
            {
                object entity = list[i];
                if (distinct.Add(new Identity(entity)))
                {
                    result.Add(entity);
                }
            }

            if (log.IsDebugEnabled)
            {
                log.Debug(string.Format("transformed: {0} rows to: {1} distinct results",
                                        list.Count, result.Count));
            }
            return(result);
        }
		public IList TransformList(IList list)
		{
			IList result = (IList)Activator.CreateInstance(list.GetType());
			ISet<Identity> distinct = new HashedSet<Identity>();

			for (int i = 0; i < list.Count; i++)
			{
				object entity = list[i];
				if (distinct.Add(new Identity(entity)))
				{
					result.Add(entity);
				}
			}

			if (log.IsDebugEnabled)
			{
				log.Debug(string.Format("transformed: {0} rows to: {1} distinct results",
				                        list.Count, result.Count));
			}
			return result;
		}
Ejemplo n.º 22
0
        public void Write(IList data)
        {
            Type listType = data.GetType();

            int itemCount = data.Count;

            Type itemType;

            if (!IListToItemType.TryGetValue(listType, out itemType))
            {
                Type[] genericArguments = listType.GetGenericArguments();
                itemType = genericArguments[0];
                IListToItemType[listType] = itemType;
            }

            Array items = Array.CreateInstance(itemType, itemCount);

            data.CopyTo(items, 0);

            Write(items);
        }
Ejemplo n.º 23
0
        public IList ReadList <T>(ref T l)
        {
            int v = 0;

            this.Read(ref v);
            IList list = ((T)l) as IList;

            if (list == null)
            {
                ADebug.LogError("ReadList list == null");
                return(null);
            }
            list.Clear();
            for (int i = 0; i < v; i++)
            {
                object o = BasicClassTypeUtil.CreateListItem(list.GetType());
                this.Read <object>(ref o);
                list.Add(o);
            }
            return(list);
        }
Ejemplo n.º 24
0
 public int Run(GitTfsCommand command, IList<string> args)
 {
     try
     {
         var runMethods = command.GetType().GetMethods().Where(m => m.Name == "Run" && m.ReturnType == typeof(int)).Select(m => new { Method = m, Parameters = m.GetParameters() });
         var splitRunMethods = runMethods.Where(m => m.Parameters.All(p => p.ParameterType == typeof(string)));
         var exactMatchingMethod = splitRunMethods.SingleOrDefault(m => m.Parameters.Length == args.Count);
         if (exactMatchingMethod != null)
             return (int)exactMatchingMethod.Method.Invoke(command, args.ToArray());
         var defaultRunMethod = runMethods.FirstOrDefault(m => m.Parameters.Length == 1 && m.Parameters[0].ParameterType.IsAssignableFrom(args.GetType()));
         if (defaultRunMethod != null)
             return (int)defaultRunMethod.Method.Invoke(command, new object[] { args });
         return _help.ShowHelpForInvalidArguments(command);
     }
     catch (TargetInvocationException e)
     {
         if (e.InnerException is GitTfsException)
             throw e.InnerException;
         throw;
     }
 }
Ejemplo n.º 25
0
        void EncodeList(IList value)
        {
            var forceTypeHint = _settings.TypeNameHandling == TypeNameHandling.All ||
                                _settings.TypeNameHandling == TypeNameHandling.Arrays;

            Type listItemType = null;

            // auto means we need to know the item type of the list. If our object is not the same as the list type
            // then we need to put the type hint in.
            if (!forceTypeHint && _settings.TypeNameHandling == TypeNameHandling.Auto)
            {
                var listType = value.GetType();
                if (listType.IsArray)
                {
                    listItemType = listType.GetElementType();
                }
                else
                {
                    foreach (Type interfaceType in listType.GetInterfaces())
                    {
                        if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IList <>))
                        {
                            listItemType = listType.GetGenericArguments()[0];
                            break;
                        }
                    }
                }
            }

            WriteStartArray();

            foreach (var obj in value)
            {
                WriteValueDelimiter();
                forceTypeHint = forceTypeHint || (listItemType != null && listItemType != obj?.GetType());
                EncodeValue(obj, forceTypeHint);
            }

            WriteEndArray();
        }
Ejemplo n.º 26
0
        private static void Copy(
            IList source,
            IList target,
            MemberSettings settings,
            ReferencePairCollection referencePairs)
        {
            if ((source.IsFixedSize || target.IsFixedSize) && source.Count != target.Count)
            {
                throw State.Copy.Throw.CannotCopyFixesSizeCollections(source, target, settings);
            }

            var copyValues = State.Copy.IsCopyValue(
                        source.GetType().GetItemType(),
                        settings);
            for (var i = 0; i < source.Count; i++)
            {
                if (copyValues)
                {
                    target.SetElementAt(i, source[i]);
                    continue;
                }

                var sv = source[i];
                var tv = target.ElementAtOrDefault(i);
                bool created;
                bool needsSync;
                var clone = State.Copy.CloneWithoutSync(sv, tv, settings, out created, out needsSync);
                if (created)
                {
                    target.SetElementAt(i, clone);
                }

                if (needsSync)
                {
                    State.Copy.Sync(sv, clone, settings, referencePairs);
                }
            }

            target.TrimLengthTo(source);
        }
Ejemplo n.º 27
0
        internal static object ToFinalPayload(this object originalModel, IList <object> links)
        {
            if (originalModel == null)
            {
                throw new InvalidOperationException("It must be a non-nullable instance.");
            }

            if (!links.Any())
            {
                return(originalModel);
            }

            var originalType = originalModel.GetType();

            AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Sciensoft.Hateoas.Links"), AssemblyBuilderAccess.RunAndCollect);
            ModuleBuilder   moduleBuilder   = assemblyBuilder.DefineDynamicModule("DynamicLinkModule");
            TypeBuilder     typeBuilder     = moduleBuilder.DefineType("LinkModel", TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass, null);     // itemType

            var originalValues = new Dictionary <string, object>();

            foreach (var property in originalType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy))
            {
                CreateProperty(typeBuilder, property.Name, property.PropertyType);
                originalValues.TryAdd(property.Name, property.GetValue(originalModel));
            }

            CreateProperty(typeBuilder, "Links", links.GetType());

            var payloadType     = typeBuilder.CreateType();
            var payloadInstance = Activator.CreateInstance(payloadType);

            foreach (var pv in originalValues)
            {
                payloadType.GetProperty(pv.Key).SetValue(payloadInstance, pv.Value);
            }

            payloadType.GetProperty("Links").SetValue(payloadInstance, links);

            return(payloadInstance);
        }
        public static List <IDictionary <string, TypeValue> > AsDictionary(this IList source, Type sourceType = null, BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.Instance)
        {
            if (source == null)
            {
                return(null);
            }

            if (sourceType == null)
            {
                sourceType = source.GetType();
            }

            var properties = _dictionaryEntityPropertyInfos.GetOrAdd(sourceType, sourceType.GetProperties(bindingAttr).ToList());

            List <OrderedListItem> list = new List <OrderedListItem>();

            var lockObj = new object();

            Parallel.For(0, source.Count, index =>
            {
                var i = source[index];

                var dic = properties.ToDictionary
                          (
                    propInfo => propInfo.Name,
                    propInfo => new TypeValue {
                    Value = propInfo.GetValue(i, BindingFlags.GetProperty, null, null, null), Type = propInfo.PropertyType
                }
                          );

                lock (lockObj)
                {
                    list.Add(new OrderedListItem {
                        Order = index, Value = dic
                    });
                }
            });

            return(list.OrderBy(od => od.Order).Select(od => od.Value).ToList());
        }
Ejemplo n.º 29
0
        private void Save(
            string file,
            IList <Ticker> list)
        {
            var dir = Path.GetDirectoryName(file);

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            var ns = new XmlSerializerNamespaces();

            ns.Add(string.Empty, string.Empty);

            using (var sw = new StreamWriter(file, false, DefaultEncoding))
            {
                var xs = new XmlSerializer(list.GetType());
                xs.Serialize(sw, list, ns);
                sw.Close();
            }
        }
Ejemplo n.º 30
0
        static void AddToCollection(object Instance, IList propertyItem)
        {
            if (_log.IsDebugEnabled)
            {
                _log.DebugFormat("Starting {0}", MethodBase.GetCurrentMethod().ToString());
            }
            MethodInfo[] methodItems = propertyItem.GetType().GetMethods();
            foreach (MethodInfo m in methodItems)
            {
                if (m.Name == "Add")
                {
                    object[] signature = { Instance };
                    m.Invoke(propertyItem, signature);

                    break;
                }
            }
            if (_log.IsDebugEnabled)
            {
                _log.DebugFormat("Ending {0}", MethodBase.GetCurrentMethod().ToString());
            }
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Poistaa kaikki annettua tyyppiä olevat peliobjektit managerista.
        /// </summary>
        public void RemoveGameObjects(IEnumerable <GameObject> objectsToRemove)
        {
            List <GameObject> objects = objectsToRemove
                                        .OrderBy(o => o.GetType().Name)
                                        .ToList();
            IList lastObjectList    = null;
            IList currentObjectList = GetObjectList(objects.First().GetType());

            foreach (GameObject gameObject in objects)
            {
                if (currentObjectList.GetType().GetGenericArguments().First() != gameObject.GetType())
                {
                    lastObjectList    = currentObjectList;
                    currentObjectList = GetObjectList(gameObject.GetType());
                    RemoveIfEmpty(lastObjectList.GetType().GetGenericArguments().First());
                }

                RemoveFromLists(currentObjectList, gameObject);
            }

            RemoveIfEmpty(currentObjectList.GetType().GetGenericArguments().First());
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Increases or decrease the number of items in the list to the specified count.
        /// </summary>
        /// <param name="list">The list.</param>
        /// <param name="length">The new length.</param>
        /// <param name="newElement">Value of new elements.</param>
        public static void SetLength <T>(ref IList <T> list, int length, Func <T> newElement)
        {
            if (list == null)
            {
                throw new ArgumentNullException("list");
            }

            if (length < 0)
            {
                throw new ArgumentException("Length must be larger than or equal to 0.");
            }

            if (newElement == null)
            {
                throw new ArgumentNullException("newElement");
            }

            if (list.GetType().IsArray)
            {
                if (list.Count != length)
                {
                    T[] array = (T[])list;
                    Array.Resize(ref array, length);
                    list = array;
                }
            }
            else
            {
                while (list.Count < length)
                {
                    list.Add(newElement());
                }

                while (list.Count > length)
                {
                    list.RemoveAt(list.Count - 1);
                }
            }
        }
Ejemplo n.º 33
0
        public override bool WriteValueList(BinaryWriter Writer, IList list)
        {
            Type type     = list.GetType();
            Type dataType = type.GetGenericArguments()[0];

            if (dataType == typeof(Vector2))
            {
                writeListBytes(Writer, list as List <Vector2>);
            }
            else if (dataType == typeof(Vector3))
            {
                writeListBytes(Writer, list as List <Vector3>);
            }
            else if (dataType == typeof(Vector4))
            {
                writeListBytes(Writer, list as List <Vector4>);
            }
            else if (dataType == typeof(Color))
            {
                writeListBytes(Writer, list as List <Color>);
            }
            else if (dataType == typeof(Color32))
            {
                writeListBytes(Writer, list as List <Color32>);
            }
            else if (dataType == typeof(Rect))
            {
                writeListBytes(Writer, list as List <Rect>);
            }
            else if (dataType == typeof(Quaternion))
            {
                writeListBytes(Writer, list as List <Quaternion>);
            }
            else
            {
                return(false);
            }
            return(true);
        }
Ejemplo n.º 34
0
        void _view_CustomRowFilter(object sender, DevExpress.XtraGrid.Views.Base.RowFilterEventArgs e)
        {
            GridView                     view       = (sender as GridView);
            BaseGridController           controller = view.DataController;
            PropertyDescriptorCollection pdc        = null;
            IList source = (IList)view.DataSource;

            if (view.DataSource is ITypedList)
            {
                pdc = (view.DataSource as ITypedList).GetItemProperties(null);
            }
            else
            {
                pdc = TypeDescriptor.GetProperties(source.GetType().GetProperty("Item").PropertyType);
            }
            if (view.FindFilterText == string.Empty)
            {
                ExpressionEvaluator ev = new ExpressionEvaluator(pdc, controller.FilterCriteria);
                e.Visible = !IsEmptyDetail(e.ListSourceRow, controller) && ev.Fit(source[e.ListSourceRow]);
                e.Handled = true;
            }
        }
Ejemplo n.º 35
0
        private static void Copy <T>(
            IList <T> source,
            IList <T> target,
            MemberSettings settings,
            ReferencePairCollection referencePairs)
        {
            if (Is.FixedSize(source, target) && source.Count != target.Count)
            {
                throw State.Copy.Throw.CannotCopyFixesSizeCollections(source, target, settings);
            }

            var copyValues = State.Copy.IsCopyValue(
                source.GetType().GetItemType(),
                settings);

            for (var i = 0; i < source.Count; i++)
            {
                if (copyValues)
                {
                    target.SetElementAt(i, source[i]);
                    continue;
                }

                var sv    = source[i];
                var tv    = target.ElementAtOrDefault(i);
                var clone = State.Copy.CloneWithoutSync(sv, tv, settings, out var created, out var needsSync);
                if (created)
                {
                    target.SetElementAt(i, clone);
                }

                if (needsSync)
                {
                    State.Copy.Sync(sv, clone, settings, referencePairs);
                }
            }

            target.TrimLengthTo(source);
        }
Ejemplo n.º 36
0
            private IEnumerable <KeyValuePair <string, string> > ListConfContents(IList list, string key)
            {
                if (null == list)
                {
                    throw new ArgumentNullException(nameof(list));
                }
                if (key == null)
                {
                    var listType = list.GetType();
                    var listArgs = listType.GetGenericArguments();
                    if (listArgs.Length == 1)
                    {
                        key = listArgs[0].Name;
                    }
                }

                for (var i = 0; i < list.Count; i++)
                {
                    var k = $"{key}[{i}]";
                    var v = list[i];
                    if (v != null)
                    {
                        var vType = v.GetType();
                        if (vType.IsValueType || vType == typeof(string))
                        {
                            yield return(new KeyValuePair <string, string>(
                                             key: k,
                                             value: Multiline($"{v}")));
                        }
                        else
                        {
                            foreach (var kvp in ConfContents(v, k))
                            {
                                yield return(kvp);
                            }
                        }
                    }
                }
            }
Ejemplo n.º 37
0
        public async Task <IActionResult> ExcelAsync()
        {
            IList <Ticket> TicketsEXP = await _context.Ticket.ToListAsync();


            using (var workbook = new XLWorkbook())
            {
                var worksheet  = workbook.Worksheets.Add("Ticket");
                var currentRow = 1;
                var currentCol = 1;

                foreach (var property in TicketsEXP.GetType().GetGenericArguments()[0].GetProperties())
                {
                    worksheet.Cell(currentRow, currentCol).Style.Font.SetBold();
                    worksheet.Cell(currentRow, currentCol++).Value = property.Name;
                }
                foreach (var item in TicketsEXP)
                {
                    currentCol = 1;
                    currentRow++;

                    foreach (var property in item.GetType().GetProperties())
                    {
                        worksheet.Cell(currentRow, currentCol++).Value = property.GetValue(item);
                        //worksheet.Cell(currentRow, 10).Value = _context.School.Where(u => u.Id == TicketVM.Ticket.SchoolId).FirstOrDefault().Naam;
                    }
                }
                using (var stream = new MemoryStream())
                {
                    workbook.SaveAs(stream);
                    var content = stream.ToArray();

                    return(File(
                               content,
                               "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                               "Tickets.xlsx"));
                }
            }
        }
        /// <summary>
        /// Metodo para serializar una Lista de objetos en un XML simple
        /// </summary>
        /// <param name="thelist"> la lista de tipo List<T> </param>
        /// <returns></returns>
        public static string List2XML(IList thelist)
        {
            string xml = "";

            try
            {
                XmlSerializer            xmlSer  = new XmlSerializer(thelist.GetType());
                StringWriterWithEncoding sWriter = new StringWriterWithEncoding(Encoding.UTF8);

                XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
                xsn.Add(String.Empty, "");

                xmlSer.Serialize(sWriter, thelist, xsn);

                xml = sWriter.ToString();
            }
            catch (Exception e)
            {
            }

            return(xml);
        }
Ejemplo n.º 39
0
        private object EncodeList(IList <object> list)
        {
            var newArray = new List <object>();

#if UNITY
            // We need to explicitly cast `list` to `List<object>` rather than
            // `IList<object>` because IL2CPP is stricter than the usual Unity AOT compiler pipeline.
            if (PlatformHooks.IsCompiledByIL2CPP && list.GetType().IsArray)
            {
                list = new List <object>(list);
            }
#endif
            foreach (var item in list)
            {
                if (!IsValidType(item))
                {
                    throw new ArgumentException("Invalid type for value in an array");
                }
                newArray.Add(Encode(item));
            }
            return(newArray);
        }
Ejemplo n.º 40
0
        private void ToDataTableTest <T>(IList <T> list) where T : class
        {
            var entityProperties = list.GetType().GetGenericArguments()[0].GetProperties();
            var dataTable        = IEnumerableExtend.ToDataTable(list);
            var dataTableColumns = dataTable.Columns;

            Assert.AreEqual(entityProperties.Length, dataTable.Columns.Count, "IEnumerable.ToDataTable convert columns failed");
            for (var i = 0; i < entityProperties.Length; i++)
            {
                Assert.AreEqual(entityProperties[i].Name, dataTable.Columns[i].ColumnName, "IEnumerable.ToDataTable convert column's name failed");
                Assert.AreEqual(entityProperties[i].PropertyType, dataTable.Columns[i].DataType, "IEnumerable.ToDataTable convert column's type failed");
            }
            Assert.AreEqual(list.Count(), dataTable.Rows.Count, "IEnumerable.ToDataTable convert rows failed");
            for (var i = 0; i < list.Count(); i++)
            {
                for (var j = 0; j < entityProperties.Length; j++)
                {
                    var v = entityProperties[j].GetValue(list[i], null);
                    Assert.AreEqual(v, dataTable.Rows[i][j], "IEnumerable.ToDataTable convert cell failed");
                }
            }
        }
Ejemplo n.º 41
0
        private void MenuItem_Add_Click(object sender, RoutedEventArgs e)
        {
            object source = (MainTree.SelectedItem as TreeViewItem).ItemsSource;
            IList  list   = ((source as ICollectionView)?.SourceCollection as IList) ?? (source as IList);
            Type   t      = list.GetType().GetGenericArguments()[0];

            Debug.Assert(typeof(UndertaleResource).IsAssignableFrom(t));
            UndertaleResource obj = Activator.CreateInstance(t) as UndertaleResource;

            if (obj is UndertaleNamedResource)
            {
                string newname = obj.GetType().Name.Replace("Undertale", "").Replace("GameObject", "Object").ToLower() + list.Count;
                (obj as UndertaleNamedResource).Name = Data.Strings.MakeString(newname);
                if (obj is UndertaleRoom)
                {
                    (obj as UndertaleRoom).Caption = Data.Strings.MakeString("");
                }
            }
            list.Add(obj);
            // TODO: change highlighted too
            ChangeSelection(obj);
        }
Ejemplo n.º 42
0
        private void UpdateCollection(IList value, IEnumerable <PartModel> parts)
        {
            // Track which part links are still represented by the models
            var unused = new List <IProductPartLink>(value.OfType <IProductPartLink>());
            // Iterate over the part models
            // Create or update the part links
            var elemType = value.GetType().GetInterfaces()
                           .Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList <>))
                           .Select(i => i.GetGenericArguments()[0]).Single();

            foreach (var partModel in parts)
            {
                if (partModel is null)
                {
                    continue;
                }

                var match = unused.Find(r => r.Id == partModel?.Id);
                if (match == null)
                {
                    match = (IProductPartLink)Activator.CreateInstance(elemType);
                    value.Add(match);
                }
                else
                {
                    unused.Remove(match);
                }

                EntryConvert.UpdateInstance(match, partModel.Properties);
                match.Product = ProductManager.LoadType(partModel.Product.Id);
            }

            // Clear all values no longer present in the model
            foreach (var link in unused)
            {
                value.Remove(link);
            }
        }
Ejemplo n.º 43
0
        public static bool ElementsUnitializedValue <T>(IList <T> values)
        {
            if (values == null)
            {
                throw new ArgumentNullException("values");
            }

            Type elementType = GetListType(values.GetType());

            if (elementType.IsValueType)
            {
                object unitializedValue = GetTypeUnitializedValue(elementType);

                for (int i = 0; i < values.Count; i++)
                {
                    if (!values[i].Equals(unitializedValue))
                    {
                        return(false);
                    }
                }
            }
            else if (elementType.IsClass)
            {
                for (int i = 0; i < values.Count; i++)
                {
                    if (values[i] != null)
                    {
                        return(false);
                    }
                }
            }
            else
            {
                throw new ArgumentException("Type is neither a ValueType or a Class", "valueType");
            }

            return(true);
        }
Ejemplo n.º 44
0
        /// <summary>
        /// Toes the view.
        /// </summary>
        /// <param name="list">The list.</param>
        /// <returns></returns>
        private DataTable ToDataTable <T>(IList <T> list)
        {
            if (list.Count < 1)
            {
                return(null);
            }

            var table      = new DataTable(list.GetType().Name);
            var properties = list[0].GetType().GetProperties();

            foreach (var info in properties)
            {
                try
                {
                    table.Columns.Add(new DataColumn(info.Name, info.PropertyType));
                }
                catch (NotSupportedException)
                {
                    table.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType)));
                }
                catch (Exception)
                {
                    table.Columns.Add(new DataColumn(info.Name, typeof(object)));
                }
            }

            foreach (object t in list)
            {
                var row = new object[properties.Length];
                for (var i = 0; i < row.Length; i++)
                {
                    row[i] = properties[i].GetValue(t, null);
                }

                table.Rows.Add(row);
            }
            return(table);
        }
Ejemplo n.º 45
0
        public static IList <int> IntersectSorted(IList <int> sequence1, IList <int> sequence2, IComparer <int> comparer)
        {
            if (sequence1.GetType() == typeof(IntervalList) && sequence2.GetType() == typeof(IntervalList))
            {
                return(IntersectSorted((IntervalList)sequence1, (IntervalList)sequence2, null));
            }
            if (IsTheSame(sequence1, sequence2))
            {
                return(sequence1.ToList());
            }
            var        smaller = sequence1.Count < sequence2.Count ? sequence1 : sequence2;
            var        bigger  = smaller == sequence1 ? sequence2 : sequence1;
            List <int> r       = new List <int>(smaller.Count);

            //if (smaller.Count*10 < bigger.Count)
            //{
            //    var secix = 0;
            //    var seccount = bigger.Count;
            //    foreach (var item in smaller)
            //    {
            //        var ix = bigger.BinarySearch(secix, seccount, item, null);
            //        if (ix >= 0)
            //        {
            //            r.Add(item);
            //            secix = ix;
            //            seccount = bigger.Count - secix;
            //        }
            //    }
            //}
            //else
            //{
            //    return IntersectSorted((IEnumerable<int>)smaller, (IEnumerable<int>)bigger, null).ToList();
            //}
            return(IntersectSorted((IEnumerable <int>)smaller, (IEnumerable <int>)bigger, null).ToList());


            //return r;
        }
Ejemplo n.º 46
0
        /// <summary>
        /// Append all elements in the 'from' list to the 'to' list.
        /// </summary>
        /// <param name="to"></param>
        /// <param name="from"></param>
        public static void AddAll(IList to, IList from)
        {
            System.Action addNull = null;
            foreach (object obj in from)
            {
                // There is bug in .NET, before version 4, where adding null to a List<Nullable<T>> through the non-generic IList interface throws an exception.
                // TODO: Everything but the to.Add(obj) should be conditionally compiled only for versions of .NET earlier than 4.
                if (obj == null)
                {
                    if (addNull == null)
                    {
                        var toType = to.GetType();
                        if (toType.IsGenericType &&
                            toType.GetGenericTypeDefinition() == typeof(List <>) &&
                            toType.GetGenericArguments()[0].IsNullable())
                        {
                            MethodInfo addMethod     = toType.GetMethod("Add");
                            var        addMethodCall = System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression.Constant(to),
                                                                                               addMethod,
                                                                                               System.Linq.Expressions.Expression.Constant(null, toType.GetGenericArguments()[0]));
                            System.Linq.Expressions.LambdaExpression addLambda =
                                System.Linq.Expressions.Expression.Lambda(addMethodCall);

                            addNull = (System.Action)addLambda.Compile();
                        }
                        else
                        {
                            addNull = () => to.Add(null);
                        }
                    }
                    addNull();
                }
                else
                {
                    to.Add(obj);
                }
            }
        }
Ejemplo n.º 47
0
        private Type GetElementType(IList v)
        {
            Type t = null;

            try
            {
                Type   type = v.GetType();
                string name = type.FullName;
                if (name.EndsWith("[]"))
                {
                    string typeName = name.Substring(0, name.Length - 2);
                    foreach (Assembly b in AppDomain.CurrentDomain.GetAssemblies())
                    {
                        Type bT = b.GetType(typeName);
                        if (bT != null)
                        {
                            t = bT;
                            break;
                        }
                    }

                    if (t == null)
                    {
                        Debug.Log($"{type}的数组类型找不到");
                    }
                }
                else
                {
                    Debug.Log($"{type}不是数组");
                }
            }
            catch (Exception e)
            {
                Debug.LogException(e);
            }

            return(t);
        }
Ejemplo n.º 48
0
        /// <summary>
        /// Adds an element to a <see cref="IList{T}"/> if it doesn't exists, otherwise it updates it.
        /// </summary>
        /// <exception cref="ArgumentNullException">Thrown if the source is null.</exception>
        /// <exception cref="InvalidOperationException">Thrown if <see cref="ICollection{T}.IsReadOnly"/> returns true.</exception>
        /// <typeparam name="T">The type of the element to be added.</typeparam>
        /// <param name="source">The source collection.</param>
        /// <param name="element">The element to search.</param>
        public static void AddOrUpdate <T>(this IList <T> source, T element)
        {
            if (source is null)
            {
                Throw.NullArgument(nameof(source));
            }

            if (source.IsReadOnly)
            {
                Throw.InvalidOperation($"{source.GetType().Name} is a Read-Only collection");
            }

            var index = source.IndexOf(element);

            if (index == -1)
            {
                source.Add(element);
            }
            else
            {
                source[index] = element;
            }
        }
Ejemplo n.º 49
0
        internal static JniValueMarshalerState  CreateArgumentState <TArray> (IList <T>?value, ParameterAttributes synchronize, Func <IList <T>, bool, TArray> creator)
            where TArray : JavaArray <T>
        {
            if (value == null)
            {
                return(new JniValueMarshalerState());
            }
            if (value is TArray v)
            {
                return(new JniValueMarshalerState(v));
            }
            var list = value as IList <T>;

            if (list == null)
            {
                throw CreateMarshalNotSupportedException(value.GetType(), typeof(TArray));
            }
            synchronize = GetCopyDirection(synchronize);
            var c = (synchronize & ParameterAttributes.In) == ParameterAttributes.In;
            var a = creator(list, c);

            return(new JniValueMarshalerState(a));
        }
Ejemplo n.º 50
0
        private void PopulateExistingXRefProperties(PropertyInfo property, IList o, IEnumerable <dynamic> xRefProperties)
        {
            Type elementType = o.GetType().GetGenericArguments().Single();

            int[] ids = new int[xRefProperties.Count()];
            int   i   = 0;

            foreach (dynamic d in xRefProperties)
            {
                foreach (KeyValuePair <string, object> kvp in d)
                {
                    if (kvp.Key == String.Format("{0}Id", elementType.Name))
                    {
                        ids[i++] = Convert.ToInt32(kvp.Value);
                        break;
                    }
                }
            }
            string subQuery = String.Format("SELECT * FROM [{0}] WHERE Id in ({1})", _pluralisationService.Pluralize(elementType.Name), String.Join(",", ids));
            IEnumerable <dynamic> subProperties = _connection.Query <dynamic>(subQuery);

            Populate(o, subProperties, elementType);
        }
Ejemplo n.º 51
0
 private object EncodeList(IList<object> list)
 {
     var newArray = new List<object>();
     #if UNITY
       // We need to explicitly cast `list` to `List<object>` rather than
       // `IList<object>` because IL2CPP is stricter than the usual Unity AOT compiler pipeline.
       if (PlatformHooks.IsCompiledByIL2CPP && list.GetType().IsArray) {
     list = new List<object>(list);
       }
     #endif
       foreach (var item in list) {
     if (!IsValidType(item)) {
       throw new ArgumentException("Invalid type for value in an array");
     }
     newArray.Add(Encode(item));
       }
       return newArray;
 }
 private IList CopyGenericList(IList source)
 {
     var type = source.GetType();
     var typeArguments = type.GetGenericArguments();
     var enumerable = typeof(Enumerable);
     var toList = enumerable.GetMethod("ToList");
     var toListGeneric = toList.MakeGenericMethod(typeArguments);
     return (IList)toListGeneric.Invoke(enumerable, new[] { source });
 }
        private void SerializeList(JsonWriter writer, IList values, JsonArrayContract contract, JsonProperty member, JsonContract collectionValueContract)
        {
            contract.InvokeOnSerializing(values, Serializer.Context);

              SerializeStack.Add(values);

              bool isReference = contract.IsReference ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Arrays);
              bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Arrays, contract, member, collectionValueContract);

              if (isReference || includeTypeDetails)
              {
            writer.WriteStartObject();

            if (isReference)
            {
              writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
              writer.WriteValue(Serializer.ReferenceResolver.GetReference(values));
            }
            if (includeTypeDetails)
            {
              WriteTypeProperty(writer, values.GetType());
            }
            writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName);
              }

              JsonContract childValuesContract = Serializer.ContractResolver.ResolveContract(contract.CollectionItemType ?? typeof(object));

              writer.WriteStartArray();

              int initialDepth = writer.Top;

              for (int i = 0; i < values.Count; i++)
              {
            try
            {
              object value = values[i];
              JsonContract valueContract = GetContractSafe(value);

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

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

              writer.WriteEndArray();

              if (isReference || includeTypeDetails)
              {
            writer.WriteEndObject();
              }

              SerializeStack.RemoveAt(SerializeStack.Count - 1);

              contract.InvokeOnSerialized(values, Serializer.Context);
        }
Ejemplo n.º 54
0
		private bool IsListHomogeneous(IList list)
		{
			if (list == null)
				throw new ArgumentNullException("list");

			if (list.GetType().IsArray)
				return true;

			Type itemType = null;
			foreach (object item in list)
			{
				if (item.GetType() != itemType)
				{
					if (itemType == null)
						itemType = item.GetType();
					else
						return false;
				}
			}

			return true;
		}
Ejemplo n.º 55
0
        private Type GetObjectType(IList sourceList)
        {
            Type listType = sourceList.GetType();
            if (listType.IsArray)
            {
                if (listType.HasElementType) return listType.GetElementType();
            }
            else if (listType.IsGenericType)
            {
                var args = listType.GetGenericArguments();
                if (args.Length == 1) return args[0];
            }

            return sourceList[0].GetType();
        }
Ejemplo n.º 56
0
		/// <summary>
		/// Initializes a new instance of the <see cref="ObjectListView"/> class.
		/// </summary>
		/// <param name="list">The list of objects to view.</param>
		public ObjectListView(IList list)
		{
			if (list == null)
				throw new ArgumentNullException("list");
			if (!this.IsListHomogeneous(list))
				throw new ArgumentException("The list contains multiple item types", "list");

			this.list = list;

			if (this.ListSupportsListChanged(list))
			{
				this.supportsListChanged = true;
				this.WireListChangedEvent(list);
			}

			// Monitor list item change events.
			this.monitorItemChanges = ListItemChangeEvents.INotifyPropertyChanged | ListItemChangeEvents.PropertyChangedEvents;

			// If the list implements IRaiseItemChangedEvents (e.g. BindingList<T>), it will convert list item changes for INotifyChanged.PropertyChanged
			// into ListChanged events, but not for .NET 1.x-style propertyNameChanged events.
			if (list is IRaiseItemChangedEvents)
			{
				if (((IRaiseItemChangedEvents)list).RaisesItemChangedEvents)
					this.monitorItemChanges = ListItemChangeEvents.PropertyChangedEvents;
			}

			Type listType = list.GetType();

			// Infer item type from existing list items or generic list parameters.
			if (list.Count > 0)
			{
				this.ItemType = list[0].GetType();

				// If needed, attach handlers to item change events for existing list items.
				if (this.monitorItemChanges != ListItemChangeEvents.None)
				{
					foreach (object item in list)
						WirePropertyChangedEvents(item);
				}
			}
			else if (listType.IsGenericType)
			{
				Type[] genericArgs = listType.GetGenericArguments();
				if (genericArgs.Length == 1)
					this.ItemType = genericArgs[0];
			}
			else if (listType.IsArray)
			{
				this.ItemType = listType.GetElementType();
			}

			RebuildSortIndexes();

			this.allowEdit = !list.IsReadOnly;
			this.allowNew = !list.IsReadOnly && !list.IsFixedSize;
			this.allowRemove = !list.IsReadOnly && !list.IsFixedSize;
			this.synced = list.IsSynchronized && list.SyncRoot != null;
		}
Ejemplo n.º 57
0
		private void WireListChangedEvent(IList list)
		{
			if (list == null)
				throw new ArgumentNullException("list");

			if (list is IBindingList)
			{
				((IBindingList)list).ListChanged += new ListChangedEventHandler(list_ListChanged);
			}
			else
			{
				EventInfo listChanged = list.GetType().GetEvent("ListChanged");
				if (listChanged != null)
					listChanged.AddEventHandler(list, new ListChangedEventHandler(this.list_ListChanged));
			}
		}
Ejemplo n.º 58
0
		private bool ListSupportsListChanged(IList list)
		{
			if (list == null)
				throw new ArgumentNullException("list");

			if (list is IBindingList)
			{
				return true;
			}
			else
			{
				EventInfo listChanged = list.GetType().GetEvent("ListChanged");
				return (listChanged != null && listChanged.EventHandlerType == typeof(ListChangedEventHandler));
			}
		}
Ejemplo n.º 59
0
        /// <summary>
        /// Returns the element type for a list.
        /// </summary>
        private Type GetListElementType(IList list)
        {
            if (list != null)
            {
                for (Type type = list.GetType(); type != null; type = type.BaseType)
                {
                    if (type.IsGenericType)
                    {
                        Type[] argTypes = type.GetGenericArguments();

                        if (argTypes.Length > 0)
                        {
                            return argTypes[0];
                        }
                    }
                }
            }

            return typeof(object);
        }
    protected virtual void OnItemsSourceChanged( IList oldValue, IList newValue )
    {
      if( newValue == null )
        return;

      if( ItemsSourceType == null )
        ItemsSourceType = newValue.GetType();

      if( ItemType == null && newValue.GetType().ContainsGenericParameters )
        ItemType = newValue.GetType().GetGenericArguments()[ 0 ];

      SetText( newValue );
    }