Example #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);
        }
        public IListTypeDefinitionFinder(IList list)
        {
            if (list == null) throw new ArgumentNullException("list");

            _listType = list.GetType();
            SetListTypeUnderlyingType();
        }
Example #4
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;
        }
Example #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();
 }
Example #6
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);
        }
Example #7
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;
        }
        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();
            }
        }
Example #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;
		}
Example #11
1
 public ArrayAdapter(IValue array)
 {
     _array = array;
     _list = array.ActualType.CreateGenericListInstance().As<IList>();
     _listType = _list.GetType().ToCachedType();
     _listType.InvokeAction("AddRange", _list, array.Instance);
 }
Example #12
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;
        }
Example #13
1
 public static Type GetListElementsType(IList Collection)
 {
     if (Collection == null)
     {
         return null;
     }
     else
     {
         return Collection.GetType().GenericTypeArguments.Single();
     }
 }
Example #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;
            }
Example #15
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);
        }
        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();
        }
Example #17
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);
     }
       }
 }
Example #18
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;
     }
 }
		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;
		}
Example #20
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);
        }
 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);
        }
        /// <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 );
    }
        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();
        }
		/// <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;
		}
		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));
			}
		}
		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));
			}
		}
		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;
		}