Ejemplo n.º 1
0
        /// <summary>
        /// Create an IDataReader over an instance of IEnumerable&lt;>.
        /// 
        /// Note: anonymous type arguments are acceptable.
        /// 
        /// Use other constructor for IEnumerable.
        /// </summary>
        /// <param name="collection">IEnumerable&lt;>. For IEnumerable use other constructor and specify type.</param>
        public EnumerableDataReader(IEnumerable collection)
        {
            foreach (Type intface in collection.GetType().GetInterfaces())
            {
                if (intface.IsGenericType && intface.GetGenericTypeDefinition() == typeof (IEnumerable<>))
                {
                    _type = intface.GetGenericArguments()[0]; 
                }
            }

            if (_type ==null && collection.GetType().IsGenericType)
            {
                _type = collection.GetType().GetGenericArguments()[0];
                
            }
            
            
            if (_type == null )
            {
                throw new ArgumentException(
                    "collection must be IEnumerable<>. Use other constructor for IEnumerable and specify type");
            }

            SetFields(_type);

            _enumerator = collection.GetEnumerator();

        }
Ejemplo n.º 2
0
 public static IEnumerable ConvertTypes(IEnumerable source, Dictionary<string, Type> types,string typeKey="Type")
 {
     if (source == null) return null;
     IList copy = new List<dynamic>();
     if (typeof(IList).IsAssignableFrom(source.GetType()))
     {
         // TODO: convert arrays of double[], int[], string[], etc when appropriate
         if (source.GetType().GetConstructor(Type.EmptyTypes) != null)
         {
             copy = Activator.CreateInstance(source.GetType()) as IList;
         }
     }
     foreach (var value in source)
     {
         var childDictionary = value as IDictionary;
         if (childDictionary != null)
         {
             copy.Add(IDictionaryExtension.ConvertTypes(childDictionary, types,typeKey));
         }
         else
         {
             var childEnumerable = value as IEnumerable;
             if (childEnumerable != null && childEnumerable.GetType() != typeof(string))
             {
                 copy.Add(ConvertTypes(childEnumerable, types));
             }
             else
             {
                 copy.Add(value);
             }
         }
     }
     return Simplify(copy);
     //return copy;
 }
Ejemplo n.º 3
0
        private static void ItemsSourceChanged(BindableObject bindable, IEnumerable oldValue, IEnumerable newValue) {
            var picker = (Picker)bindable;
            if (picker == null)
                throw new Exception("only support Picker");

            var selected = picker.SelectedIndex;

            var type = newValue.GetType().GenericTypeArguments[0].GetTypeInfo();
            var dp = (string)bindable.GetValue(DisplayPathProperty);
            PropertyInfo p = null;
            if (!string.IsNullOrWhiteSpace(dp)) {
                p = type.GetDeclaredProperty(dp);
            }
            foreach (var o in newValue) {
                object value = null;
                if (p != null)
                    value = p.GetValue(o);
                else
                    value = o;

                if (value != null)
                    picker.Items.Add(value.ToString());
            }

            picker.SelectedIndex = selected;
        }
        public static void AddToCollection(this IEnumerable items, IEnumerable collection, Type elementType,
            Type resourceType, string propertyName, Type propertyType)
        {
            Contract.Assert(items != null);
            Contract.Assert(collection != null);
            Contract.Assert(elementType != null);
            Contract.Assert(resourceType != null);
            Contract.Assert(propertyName != null);
            Contract.Assert(propertyType != null);

            MethodInfo addMethod = null;
            IList list = collection as IList;

            if (list == null)
            {
                addMethod = collection.GetType().GetMethod("Add", new Type[] { elementType });
                if (addMethod == null)
                {
                    string message = Error.Format(SRResources.CollectionShouldHaveAddMethod, propertyType.FullName, propertyName, resourceType.FullName);
                    throw new SerializationException(message);
                }
            }
            else if (list.GetType().IsArray)
            {
                string message = Error.Format(SRResources.GetOnlyCollectionCannotBeArray, propertyName, resourceType.FullName);
                throw new SerializationException(message);
            }

            items.AddToCollectionCore(collection, elementType, list, addMethod);
        }
Ejemplo n.º 5
0
        public static bool CollectionEquals <T>(IEnumerable <T> col1, IEnumerable <T> col2)
        {
            if (ReferenceEquals(col1, col2))
            {
                return(true);
            }

            if (col1.IsEmpty() && col2.IsEmpty())
            {
                return(true);
            }

            if (col1?.GetType() != col2?.GetType())
            {
                return(false);
            }
            var list1 = col1.ToList();
            var list2 = col2.ToList();

            if (list1.Count != list2.Count)
            {
                return(false);
            }

            return(!list1.Where((t, i) => !t.Equals(list2[i])).Any());
        }
Ejemplo n.º 6
0
        private static HyperMediaLink GetLinkImplementation(this IEnumerable <HyperMediaLink> linkEntity, string key, bool throwOnMissingLink = true)
        {
            if (linkEntity == null || string.IsNullOrWhiteSpace(key))
            {
                if (throwOnMissingLink)
                {
                    throw new MissingLinkException(key, linkEntity?.GetType());
                }

                return(null);
            }

            var link = linkEntity.FirstOrDefault(l => string.Equals(l.Rel, key, StringComparison.OrdinalIgnoreCase));

            if (link == null)
            {
                if (throwOnMissingLink)
                {
                    throw new MissingLinkException(key, linkEntity.GetType());
                }

                return(null);
            }

            return(link);
        }
 /// <summary>
 /// Fills dropdownlist list with data from dataSource     
 /// <param name="list"></param>
 /// <param name="dataSource"></param>
 /// <param name="needEmpty">Indicates if we have to add empty element to dropDownList</param>
 /// <param name="dataValueField">value</param>
 /// <param name="dataTextField">text</param>
 /// <param name="emptyText">displayed text in emptyElement </param>
 public void FillDropDownList(DropDownList list, IEnumerable dataSource, String dataValueField = "", String dataTextField = "", bool needEmpty = false, String emptyText = "")
 {
     //if string[,] array is datasource
     if(dataSource.GetType() == typeof(System.String[,]))
     {
         list.DataSource = dataSource;
     }
     else //if any List<object> is datasource
     {
         list.DataSource = dataSource;
     }
     //if value or text fields are identified
     if(!string.IsNullOrEmpty(dataValueField))
     {
         list.DataValueField = dataValueField;
     }
     if(!string.IsNullOrEmpty(dataTextField))
     {
         list.DataTextField = dataTextField;
     }
     list.DataBind();
     //if we have to add an empty element to dropDownList
     if(needEmpty)
     {
         list.Items.Insert(0, new ListItem(emptyText, Constants.EpmtyDDLValue));
     }
 }
Ejemplo n.º 8
0
		public static Type GetElementType(IEnumerable enumerable)
		{
			Type elementType = null;
			var enumerableType = enumerable.GetType();
			
			do
			{	
				if (enumerableType.IsGenericType)
				{
					var genericArguments = enumerableType.GetGenericArguments();
					if (genericArguments.Length > 0)
					{
						elementType = genericArguments[0];
					}
				}

				enumerableType = enumerableType.BaseType;
			} while (elementType == null && enumerableType != null);
			
			if (elementType == null)
			{
				var enumItems = enumerable.GetEnumerator();
				if (enumItems.MoveNext())
				{
					if (enumItems.Current != null)
					{
						elementType = enumItems.Current.GetType();
					}
				}
			}
			return elementType;
		}
        private static bool PerformListFieldComparison(IEnumerable list1, IEnumerable list2, ObjectReferenceDictionary recursiveObjects, bool logOnFail = true)
        {
            bool equals;
            var  failMessage = string.Empty;

            if ((list1 == null) || (list2 == null))
            {
                equals = ((list1 == null) && (list2 == null));
            }
            else if (ReferenceEquals(list1, list2))
            {
                equals = true;
            }
            else
            {
                equals = CompareListElements(list1, list2, recursiveObjects, ref failMessage);
            }

            if (!equals && logOnFail)
            {
                var type = list1?.GetType() ?? list2.GetType();

                LogFailedComparison(failMessage, type, list1, list2);
            }

            return(equals);
        }
        ///// <summary>
        ///// 序列化物件
        ///// </summary>
        ///// <typeparam name="T"></typeparam>
        ///// <param name="value"></param>
        ///// <returns></returns>
        //public string ObjectToString<T>(T value)
        //{
        //    XmlSerializer ser = new XmlSerializer(value.GetType());
        //    MemoryStream stream = new MemoryStream();
        //    ser.Serialize(stream, value);
        //    stream.Position = 0;
        //    StreamReader reader = new StreamReader(stream);
        //    string result = reader.ReadToEnd();
        //    stream.Dispose();
        //    reader.Dispose();
        //    return result;

        //}

        public string ToDataTableXmlString(IEnumerable value)
        {
            var type = value.GetType().GetGenericArguments()[0];
            DataTable dataTable = new DataTable(type.Name);
            PropertyInfo[] Props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo prop in Props)
            {
                dataTable.Columns.Add(prop.Name);
            }
            foreach (object item in value)
            {
                var values = new object[Props.Length];
                for (int i = 0; i < Props.Length; i++)
                {
                    values[i] = Props[i].GetValue(item, null);
                }
                dataTable.Rows.Add(values);
            }

            using (var memoryStream = new MemoryStream())
            {
                dataTable.WriteXml(memoryStream);
                memoryStream.Position = 0;
                using (var reader = new StreamReader(memoryStream))
                {
                    return reader.ReadToEnd();
                }
            }

        }
        public static void AddRange <T>(this IEnumerable <T> inlineCollection, IEnumerable <T> range,
                                        bool throwException = false)
        {
            if (range == null)
            {
                return;
            }
            var c = inlineCollection as IInlineCollection <T>;
            var l = inlineCollection as ICollection <T>;

            if (c != null)
            {
                c.AddRange(range);
            }
            else if (l != null)
            {
                foreach (var item in range)
                {
                    l.Add(item);
                }
            }
            else if (throwException)
            {
                throw new ArgumentException($"{inlineCollection?.GetType().FullName} does not support operation",
                                            nameof(inlineCollection));
            }
        }
 public ItemValidationExceptionException(
     [CanBeNull, NoEnumeration] IEnumerable collection,
     [CanBeNull, InvokerParameterName] string collectionName = null,
     [CanBeNull] string message = null)
     : this(collection?.GetType().FullName, collectionName, message)
 {
 }
Ejemplo n.º 13
0
        public static List <BeatmapDataModel> ToDataModelList(this IEnumerable <IMapIdentifiable> identifiable, bool distinctByVersion = false)
        {
            List <BeatmapDataModel> ret;

            switch (identifiable)
            {
            case ObservableCollection <Beatmap> beatmaps1:
                ret = beatmaps1.InnerToDataModelList();
                break;

            case List <Beatmap> beatmaps:
                ret = beatmaps.InnerToDataModelList();
                break;

            case ObservableCollection <BeatmapDataModel> dataModels1:
                ret = dataModels1.ToList();
                break;

            case List <BeatmapDataModel> dataModels:
                ret = dataModels;
                break;

            case List <BeatmapSettings> infos:
                ret = _beatmapDbOperator.GetBeatmapsByIdentifiable(infos).InnerToDataModelList();
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(identifiable), identifiable?.GetType(),
                                                      "Not support source type.");
            }

            return(ret.Distinct(new DataModelComparer(distinctByVersion)).ToList());
        }
        /// <summary>
        /// Creates a view schema with a set of typed results and an optional set of keyName properties on those results
        /// </summary>
        internal EntityDataSourceViewSchema(IEnumerable results, string[] keyNames)
        {
            Type type = GetListItemType(results.GetType());
            PropertyInfo[] infos = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);

            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(type);
            CreateColumnsFromPropDescs(properties, keyNames);
        }
Ejemplo n.º 15
0
 private void BuildHeaders(IEnumerable modelList, StringBuilder sb)
 {
     foreach (PropertyInfo property in modelList.GetType().GetElementType().GetProperties())
     {
         sb.AppendFormat("{0},", property.Name);
     }
     sb.NewLine();
 }
Ejemplo n.º 16
0
 private void BuildRowData(IEnumerable modelList, object modelItem, StringBuilder sb)
 {
     foreach (PropertyInfo info in modelList.GetType().GetElementType().GetProperties())
     {
         object value = info.GetValue(modelItem, new object[0]);
         sb.AppendFormat("{0},", value);
     }
 }
Ejemplo n.º 17
0
		public static object Create(Type resultCollectionType, MocksRepository repo, IMockReplicator replicator, IEnumerable collection)
		{
			if (resultCollectionType == typeof(string))
				return null;

			Type sourceType = collection.GetType();
			if (resultCollectionType.IsAssignableFrom(sourceType))
				return collection;

			var enumerableType = resultCollectionType.GetImplementationOfGenericInterface(typeof(IEnumerable<>)) ?? typeof(IEnumerable);
			if (!enumerableType.IsAssignableFrom(resultCollectionType))
				throw new MockException("Return value is not an enumerable type.");

			var elementType = enumerableType.IsGenericType ? enumerableType.GetGenericArguments()[0] : typeof(object);

			var ilistType = typeof(IList<>).MakeGenericType(elementType);
			var iqueryableType = typeof(IQueryable<>).MakeGenericType(elementType);

			IEnumerable list;
			if (typeof(ICollection).IsAssignableFrom(sourceType))
			{
				list = collection;
			}
			else
			{
				var listType = typeof(List<>).MakeGenericType(elementType);
				var castMethod = typeof(Enumerable).GetMethod("Cast").MakeGenericMethod(elementType);

				var castCollection = castMethod.Invoke(null, new[] { collection });
				list = (IEnumerable)MockingUtil.CreateInstance(listType, castCollection);
			}

			var listBehavior = new DelegatedImplementationBehavior(list,
				new[]
				{
					ilistType,
					typeof(IList),
				});

			var queryable = list.AsQueryable();
			var queryableType = queryable.GetType();
			var queryableBehavior = new DelegatedImplementationBehavior(queryable,
				new[] { queryableType.GetImplementationOfGenericInterface(typeof(IQueryable<>)) });

			if (replicator != null)
			{
				var mock = replicator.CreateSimilarMock(repo, resultCollectionType, null, true, null);
				var mockMixin = MocksRepository.GetMockMixin(mock, null);
				mockMixin.FallbackBehaviors.Insert(0, queryableBehavior);
				mockMixin.FallbackBehaviors.Insert(0, listBehavior);
				return mock;
			}
			else
			{
				return repo.Create(resultCollectionType, null, Behavior.Loose, MockingUtil.EmptyTypes, null,
					null, null, new List<IBehavior> { listBehavior, queryableBehavior });
			}
		}
 internal static string GetItemDisplayPrefix(IEnumerable collection)
 {
     Type elementType = ElementType(collection.GetType());
     if (elementType == null)
     {
         return "item";
     }
     return elementType.Name;
 }
Ejemplo n.º 19
0
 public ItemNullsNotAllowedException(
     [CanBeNull, NoEnumeration] IEnumerable collection,
     [CanBeNull, InvokerParameterName] string collectionName = null,
     [CanBeNull] string message = null)
     : base(message)
 {
     CollectionClassName = collection?.GetType().FullName;
     CollectionName      = collectionName;
 }
Ejemplo n.º 20
0
 private static string JsonContacts(IEnumerable<ContactInfo> contacts)
 {
     var serializer = new DataContractJsonSerializer(contacts.GetType());
     using (var ms = new MemoryStream())
     {
         serializer.WriteObject(ms, contacts);
         return Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length);
     }
 }
Ejemplo n.º 21
0
        public static void showListContents(IEnumerable list)
        {
            DI.log.debug("Showing contents of list of type: {0}\n", list.GetType());
            int itemCount = 0;
            foreach (object item in list)
                DI.log.info("      [{0}]   {1}", itemCount++, item.ToString());

            DI.log.info("");
        }
 // ----------------------------------------------------------------------
 public static bool AreEqual( IEnumerable enumerable, object obj )
 {
     bool equal = enumerable == obj;
     if ( !equal && enumerable != null && obj != null && enumerable.GetType() == obj.GetType() )
     {
         equal = HaveSameContents( enumerable, obj as IEnumerable );
     }
     return equal;
 }
Ejemplo n.º 23
0
        public ModelExplorer GetModelExplorer(IEnumerable items)
        {
            var type = items.GetType().GenericTypeArguments.First();

            var instance = Activator.CreateInstance(type);

            var model = _provider.GetModelExplorerForType(type, instance);

            return model;
        }
Ejemplo n.º 24
0
 // ----------------------------------------------------------------------
 public static bool AreEqual( IEnumerable enumerable, object obj )
 {
     bool equal = enumerable == obj;
     // ReSharper disable PossibleMultipleEnumeration
     if ( !equal && enumerable != null && obj != null && enumerable.GetType() == obj.GetType() )
     {
         equal = HaveSameContents( enumerable, obj as IEnumerable );
     // ReSharper restore PossibleMultipleEnumeration
     }
     return equal;
 }
Ejemplo n.º 25
0
    // PropertyInfo, MethodInfo, EventInfo и т.е ВСЕ НАСЛЕДУЮТСЯ ОТ MemberInfo
    private static void PrintValues(this IEnumerable <MemberInfo> memberInfos)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine(memberInfos?.GetType().GetElementType()?.Name);     //была коллекция->взяли тип коллекции->взяли тип элемента->взяли имя элемента
        Console.ForegroundColor = ConsoleColor.Green;

        foreach (MemberInfo memberInfo in memberInfos)
        {
            Console.WriteLine(memberInfo);
        }
        Console.WriteLine(new string('-', 40));
    }
 public static PropertyDescriptorCollection GetDataFields(IEnumerable dataSource)
 {
     if (dataSource is ITypedList)
     {
         return ((ITypedList) dataSource).GetItemProperties(new PropertyDescriptor[0]);
     }
     PropertyInfo info = dataSource.GetType().GetProperty("Item", BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, null, null, new Type[] { typeof(int) }, null);
     if ((info != null) && (info.PropertyType != typeof(object)))
     {
         return TypeDescriptor.GetProperties(info.PropertyType);
     }
     return null;
 }
Ejemplo n.º 27
0
        public static object Adjust(IEnumerable results, Type returnType) {
            if (returnType == typeof(void) ||
                results == null ||
                results.GetType() == returnType) {
                return results;
            }

            // acquire method:
            // static IEnumerable<T> IEnumerable.OfType<T>(this IEnumerable source)
            // where T is from returnType's IEnumerable<T>
            var enumerableOfTypeT = _enumerableOfTypeTDictionary.GetOrAdd( returnType, type => typeof(Enumerable).GetGenericMethod("OfType", type.GetGenericArguments(), new[] { typeof(IEnumerable) }, typeof(IEnumerable<>)));
            return enumerableOfTypeT.Invoke(null, new[] { results });
        }
        public static void AddToCollection(this IEnumerable items, IEnumerable collection, Type elementType, Type resourceType, string propertyName, Type propertyType)
        {
            Contract.Assert(items != null);
            Contract.Assert(collection != null);
            Contract.Assert(elementType != null);
            Contract.Assert(resourceType != null);
            Contract.Assert(propertyName != null);
            Contract.Assert(propertyType != null);

            MethodInfo addMethod = null;
            IList list = collection as IList;

            if (list == null)
            {
                addMethod = collection.GetType().GetMethod("Add", new Type[] { elementType });
                if (addMethod == null)
                {
                    string message = Error.Format(SRResources.CollectionShouldHaveAddMethod, propertyType.FullName, propertyName, resourceType.FullName);
                    throw new SerializationException(message);
                }
            }
            else if (list.GetType().IsArray)
            {
                string message = Error.Format(SRResources.GetOnlyCollectionCannotBeArray, propertyName, resourceType.FullName);
                throw new SerializationException(message);
            }

            bool isNonstandardEdmPrimitiveCollection;
            EdmLibHelpers.IsNonstandardEdmPrimitive(elementType, out isNonstandardEdmPrimitiveCollection);

            foreach (object item in items)
            {
                object element = item;

                if (isNonstandardEdmPrimitiveCollection && element != null)
                {
                    // convert non-standard edm primitives if required.
                    element = EdmPrimitiveHelpers.ConvertPrimitiveValue(element, elementType);
                }

                if (list != null)
                {
                    list.Add(element);
                }
                else
                {
                    Contract.Assert(addMethod != null);
                    addMethod.Invoke(collection, new object[] { element });
                }
            }
        }
 /// <summary>
 /// Save clippings to xml file.
 /// </summary>
 /// <param name="clippingsList">Clippings list.</param>
 /// <param name="path">Path to save.</param>
 private void Save(string path, IEnumerable<ClippingItem> clippingsList)
 {
     try
     {
         path += ".xml";
         XmlSerializer serializer = new XmlSerializer(clippingsList.GetType());
         TextWriter writer = new StreamWriter(path);
         serializer.Serialize(writer, clippingsList);
         writer.Close();
     }
     catch (Exception ex)
     {
         ShowBox.ShowError("Error while saving xml file. \n" + ex.Message);
     }
 }
Ejemplo n.º 30
0
        public static void Save(IEnumerable<EntryViewModel> entries)
        {
            var xs = new XmlSerializer(entries.GetType());

            var path = StoragePath;
            var file = new FileInfo(path);
            if (file.DirectoryName == null)
                throw new Exception("DirectoryName should not be null");
            if (!Directory.Exists(file.DirectoryName))
                Directory.CreateDirectory(file.DirectoryName);

            using (TextWriter writer = new StreamWriter(path))
            {
                xs.Serialize(writer, entries);
            }
        }
        protected virtual void VisitEnumerable(IEnumerable value)
        {
            var members = GetMembersFromEnumerableElements(value);

            var numberOfMembers = members.Count() == 0 ? 1 : members.Count();

            VisitEnumerableHeader(value.GetType(), value.Cast<object>().Count(), numberOfMembers);

            if(members.Any())
                VisitTypeInEnumerableMembers(members);

            foreach (var element in value)
                VisitEnumerableElement(element, members);

            VisitEnumerableFooter();
        }
Ejemplo n.º 32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Configuration"/> class.
 /// </summary>
 /// <param name="format">The format.</param>
 /// <param name="primitiveSerializers">The primitive serializers.</param>
 /// <param name="compositeSerializers">The composite serializers.</param>
 public Configuration(IFormat format,
     IEnumerable<IPrimitiveSerializer> primitiveSerializers,
     IEnumerable<ICompositeSerializer> compositeSerializers)
   : this(false) {
   this.Format = format;
   this.compositeSerializers.AddRange(compositeSerializers);
   foreach (var primitiveSerializer in primitiveSerializers) {
     if (primitiveSerializer.SerialDataType != format.SerialDataType)
       throw new ArgumentException(string.Format(
         "primitive serializer's ({0}) serialized data type ({1}) " + Environment.NewLine +
         "is not compatible with selected format's ({2}) seriali data type ({3})",
         primitiveSerializers.GetType().FullName, primitiveSerializer.SerialDataType.FullName,
         format.Name, format.SerialDataType.FullName));
     this.primitiveSerializers.Add(primitiveSerializer.SourceType, primitiveSerializer);
   }
 }
 /// <summary>
 /// Отформатировать коллекцию элементов в строку 
 /// </summary>
 /// <param name="collection"></param>
 /// <returns></returns>
 public static string PrepareCollectionToLog(IEnumerable collection)
 {
     if (collection != null)
     {
         StringBuilder res = new StringBuilder(string.Format("Collection type:{0}", collection.GetType()));
         foreach (object obj in collection)
         {
             if (obj is string || obj is ValueType)
                 res.AppendFormat("({0})", obj);
             else
                 res.Append(ToString(obj));
         }
         return res.ToString();
     }
     else
         return "Empty collection";
 }
Ejemplo n.º 34
0
        protected override void PerformDataBinding(IEnumerable data)
        {
            //If in DesignMode, don't do anything special. Just call base and return.
            if (DesignMode)
            {
                base.PerformDataBinding(data);
                return;
            }

            //Count the data items.(I wish I knew a better way to do this.)
            int objectItemCount = 0;

            foreach (object o in data)
            {
                objectItemCount++;
            }

            //If there is a count, don't do anything special. Just call base and return.
            if (objectItemCount > 0)
            {
                base.PerformDataBinding(data);
                return;
            }

            //Set these values so the GridView knows what's up.
            SelectArguments.TotalRowCount++;
            _isEmpty = true;

            //If it's a DataView, it will work without having to handle the MustAddARow event.
            if (data.GetType() == typeof(DataView))
            {
                //Add a row and use that new view.
                DataView dv = (DataView)data;
                dv.Table.Rows.InsertAt(dv.Table.NewRow(), 0);
                base.PerformDataBinding(dv.Table.DefaultView);
                return;
            }
            else
            {
                //If you are using some custom object, you need to handle this event.
                base.PerformDataBinding(OnMustAddARow(data));
                return;
            }
        }
Ejemplo n.º 35
0
        public static Object CreateResult(
            TypeInfo propertyTypeInfo,
            IEnumerable enumerable,
            IResolveBuilder builder,
            IEnumerable<ResolveFailure> failures
        )
        {
            if (propertyTypeInfo == null)
            {
                throw Logger.Fatal.ArgumentNull(nameof(propertyTypeInfo));
            }

            if (enumerable == null)
            {
                throw Logger.Fatal.ArgumentNull(nameof(enumerable));
            }

            if (builder == null)
            {
                throw Logger.Fatal.ArgumentNull(nameof(builder));
            }

            if (failures == null)
            {
                throw Logger.Fatal.ArgumentNull(nameof(failures));
            }

            var property = ResolvedPropertyTypeInfo.Parse(propertyTypeInfo);

            var enumerableTypes =
                GetEnumerableTypes(enumerable.GetType())
                .ToArray();

            if (!enumerableTypes.Contains(property.ResolvedType))
            {
                enumerable = CreateConverter(enumerable, property.ResolvedType);
            }

            var result = CreateResult(property);
            result.ResolveBuilder = builder;
            result.ResolveFailures = failures;
            result.Results = enumerable;
            return result;
        }
Ejemplo n.º 36
0
        private Type GetElementType(IEnumerable valueArray)
        {
            Type valueArrayType = valueArray.GetType();

            if (valueArray is Array)
            {
                Type elementType = valueArrayType.GetElementType();
                return elementType;
            }

            if (valueArrayType.IsGenericType)
            {
                Type elementType = valueArrayType.GetGenericArguments()[0];
                return elementType;
            }

            //TODO: Typed exception
            throw  new Exception("Can not find element type");
        }
Ejemplo n.º 37
0
        public static void Backup(IEnumerable<EntryViewModel> entries)
        {
            var xs = new XmlSerializer(entries.GetType());

            var path = StoragePath;
            var file = new FileInfo(path);
            if (file.DirectoryName == null)
                throw new Exception("DirectoryName should not be null");
            if (!Directory.Exists(file.DirectoryName))
                Directory.CreateDirectory(file.DirectoryName);
            var newFileName = "entries_" + DateTime.Now.ToString(
                "yyyyMMddhhmmss") + ".manvan";
            var newFilePath = Path.Combine(
                file.DirectoryName, newFileName);
            using (TextWriter writer = new StreamWriter(newFilePath))
            {
                xs.Serialize(writer, entries);
            }
        }
Ejemplo n.º 38
0
        private static string BuildTable(string name, IEnumerable items, IDictionary<string, object> attributes)
        {
            StringBuilder sb = new StringBuilder();

            Type itemType = items.GetType().GetGenericArguments()[0];

            var properties = itemType.GetProperties()
               .Where(pr => pr.IsDefined(typeof(DataTablesColumnAttribute), false))
               .OrderBy(pr => ((DataTablesColumnAttribute)pr.GetCustomAttributes(typeof(DataTablesColumnAttribute), false).Single()).Order)
               .ToList();

            var allowEdit = attributes.ContainsKey("data-allow-edit") && Convert.ToBoolean(attributes["data-allow-edit"]);
            var allowDelete = attributes.ContainsKey("data-allow-delete") && Convert.ToBoolean(attributes["data-allow-delete"]);
            var allowNew = attributes.ContainsKey("data-allow-new") && Convert.ToBoolean(attributes["data-allow-new"]);


            BuildTableHeader(sb, properties, allowEdit || allowDelete);
            sb.AppendLine("\t<tbody>");
            foreach (var item in items)
            {
                BuildTableRow(sb, item, properties);
            }
            sb.AppendLine("\t</tbody>");

            TagBuilder builder = new TagBuilder("table");
            builder.MergeAttributes(attributes);
            if (allowEdit || allowDelete) builder.MergeAttribute("data-key-properties", GetKeys(properties));
            builder.MergeAttribute("name", name);
            builder.InnerHtml = sb.ToString();

            TagBuilder div = new TagBuilder("div");
            div.InnerHtml = builder.ToString(TagRenderMode.Normal);

            if (allowNew)
            {
                TagBuilder addButton = new TagBuilder("a");
                addButton.AddCssClass("btn btn-success datatables_novo");
                addButton.SetInnerText("Novo");
                div.InnerHtml += addButton.ToString(TagRenderMode.Normal);
            }

            return div.ToString(TagRenderMode.Normal);
        }
Ejemplo n.º 39
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Gets a list of IInspectorObject objects representing all the properties for the
        /// specified object, which is assumed to be at the specified level.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        protected virtual List <IInspectorObject> GetInspectorObjects(object obj, int level)
        {
            IInspectorObject ioParent = obj as IInspectorObject;

            if (ioParent != null)
            {
                obj = ioParent.Object;
            }

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

            // We used to check if the object implemented ICollection but that didn't
            // work for Linq results. This works for both, but we need to make sure the
            // object is not a string because we don't want to show strings as an array
            // of characters.
            IEnumerable enumList = obj as IEnumerable;

            if (enumList != null && enumList.GetType() != typeof(string))
            {
                int i = 0;
                foreach (object item in enumList)
                {
                    IInspectorObject io = CreateInspectorObject(item, obj, ioParent, level);
                    io.DisplayName = string.Format("[{0}]", i++);
                    list.Add(io);
                }

                return(list);
            }

            //ICollection collection = obj as ICollection;
            //if (collection != null)
            //{
            //    int i = 0;
            //    foreach (object item in collection)
            //    {
            //        IInspectorObject io = CreateInspectorObject(item, obj, ioParent, level);
            //        io.DisplayName = string.Format("[{0}]", i++);
            //        list.Add(io);
            //    }

            //    return list;
            //}

            PropertyInfo[] props = GetPropsForObj(obj);
            foreach (PropertyInfo pi in props)
            {
                try
                {
                    object propObj = pi.GetValue(obj, null);
                    list.Add(CreateInspectorObject(pi, propObj, obj, ioParent, level));
                }
                catch (Exception e)
                {
                    list.Add(CreateExceptionInspectorObject(e, obj, pi.Name, level, ioParent));
                }
            }

            list.Sort(CompareInspectorObjectNames);
            return(list);
        }
Ejemplo n.º 40
0
        private object CoerceList(Type targetType, Type arrayType, IEnumerable value)
        {
            if (targetType.IsArray)
            {
                return(this.CoerceArray(targetType.GetElementType(), value));
            }

            // targetType serializes as a JSON array but is not an array
            // assume is an ICollection / IEnumerable with AddRange, Add,
            // or custom Constructor with which we can populate it

            // many ICollection types take an IEnumerable or ICollection
            // as a constructor argument.  look through constructors for
            // a compatible match.
            ConstructorInfo[] ctors       = targetType.GetConstructors();
            ConstructorInfo   defaultCtor = null;

            foreach (ConstructorInfo ctor in ctors)
            {
                ParameterInfo[] paramList = ctor.GetParameters();
                if (paramList.Length == 0)
                {
                    // save for in case cannot find closer match
                    defaultCtor = ctor;
                    continue;
                }

                if (paramList.Length == 1 &&
                    paramList[0].ParameterType.IsAssignableFrom(arrayType))
                {
                    try
                    {
                        // invoke first constructor that can take this value as an argument
                        return(ctor.Invoke(
                                   new object[] { value }
                                   ));
                    }
                    catch
                    {
                        // there might exist a better match
                        continue;
                    }
                }
            }

            if (defaultCtor == null)
            {
                throw new JsonTypeCoercionException(
                          String.Format(TypeCoercionUtility.ErrorDefaultCtor, targetType.FullName));
            }
            object collection;

            try
            {
                // always try-catch Invoke() to expose real exception
                collection = defaultCtor.Invoke(null);
            }
            catch (TargetInvocationException ex)
            {
                if (ex.InnerException != null)
                {
                    throw new JsonTypeCoercionException(ex.InnerException.Message, ex.InnerException);
                }
                throw new JsonTypeCoercionException("Error instantiating " + targetType.FullName, ex);
            }

            // many ICollection types have an AddRange method
            // which adds all items at once
            MethodInfo method = targetType.GetMethod("AddRange");

            ParameterInfo[] parameters = (method == null) ?
                                         null : method.GetParameters();
            Type paramType = (parameters == null || parameters.Length != 1) ?
                             null : parameters[0].ParameterType;

            if (paramType != null &&
                paramType.IsAssignableFrom(arrayType))
            {
                try
                {
                    // always try-catch Invoke() to expose real exception
                    // add all members in one method
                    method.Invoke(
                        collection,
                        new object[] { value });
                }
                catch (TargetInvocationException ex)
                {
                    if (ex.InnerException != null)
                    {
                        throw new JsonTypeCoercionException(ex.InnerException.Message, ex.InnerException);
                    }
                    throw new JsonTypeCoercionException("Error calling AddRange on " + targetType.FullName, ex);
                }
                return(collection);
            }
            else
            {
                // many ICollection types have an Add method
                // which adds items one at a time
                method     = targetType.GetMethod("Add");
                parameters = (method == null) ?
                             null : method.GetParameters();
                paramType = (parameters == null || parameters.Length != 1) ?
                            null : parameters[0].ParameterType;
                if (paramType != null)
                {
                    // loop through adding items to collection
                    foreach (object item in value)
                    {
                        try
                        {
                            // always try-catch Invoke() to expose real exception
                            method.Invoke(
                                collection,
                                new object[] {
                                this.CoerceType(paramType, item)
                            });
                        }
                        catch (TargetInvocationException ex)
                        {
                            if (ex.InnerException != null)
                            {
                                throw new JsonTypeCoercionException(ex.InnerException.Message, ex.InnerException);
                            }
                            throw new JsonTypeCoercionException("Error calling Add on " + targetType.FullName, ex);
                        }
                    }
                    return(collection);
                }
            }

            try
            {
                // fall back to basics
                return(Convert.ChangeType(value, targetType));
            }
            catch (Exception ex)
            {
                throw new JsonTypeCoercionException(String.Format("Error converting {0} to {1}", value.GetType().FullName, targetType.FullName), ex);
            }
        }
Ejemplo n.º 41
0
        /// <summary>
        /// 集合映射
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static IList <T> MapToList <T>(this IEnumerable <T> Obj)
        {
            IMapper mapper = new MapperConfiguration(t => t.CreateMap(Obj.GetType(), typeof(T))).CreateMapper();

            return(mapper.Map <List <T> >(Obj));
        }
Ejemplo n.º 42
0
        public async Task InsertAsync(IEnumerable <TEntity> entities)
        {
            await DbSet.AddRangeAsync(entities);

            if (!(await Context.SaveChangesAsync() > 0))
            {
                throw new CrudFailedException(CRUDErrorMessages.InsertFailed + Separators.Colon + entities.GetType().Name);
            }
        }
Ejemplo n.º 43
0
        private void WriteFeed(IEnumerable enumerable, IEdmTypeReference feedType, ODataDeltaWriter writer,
                               ODataSerializerContext writeContext)
        {
            Contract.Assert(writer != null);
            Contract.Assert(writeContext != null);
            Contract.Assert(enumerable != null);
            Contract.Assert(feedType != null);

            ODataDeltaFeed deltaFeed = CreateODataDeltaFeed(enumerable, feedType.AsCollection(), writeContext);

            if (deltaFeed == null)
            {
                throw new SerializationException(Error.Format(SRResources.CannotSerializerNull, DeltaFeed));
            }

            // save this for later to support JSON odata.streaming.
            Uri nextPageLink = deltaFeed.NextPageLink;

            deltaFeed.NextPageLink = null;

            //Start writing of the Delta Feed
            writer.WriteStart(deltaFeed);

            //Iterate over all the entries present and select the appropriate write method.
            //Write method creates ODataDeltaDeletedEntry / ODataDeltaDeletedLink / ODataDeltaLink or ODataEntry.
            foreach (object entry in enumerable)
            {
                if (entry == null)
                {
                    throw new SerializationException(SRResources.NullElementInCollection);
                }

                IEdmChangedObject edmChangedObject = entry as IEdmChangedObject;
                if (edmChangedObject == null)
                {
                    throw new SerializationException(Error.Format(SRResources.CannotWriteType, GetType().Name, enumerable.GetType().FullName));
                }

                switch (edmChangedObject.DeltaKind)
                {
                case EdmDeltaEntityKind.DeletedEntry:
                    WriteDeltaDeletedEntry(entry, writer, writeContext);
                    break;

                case EdmDeltaEntityKind.DeletedLinkEntry:
                    WriteDeltaDeletedLink(entry, writer, writeContext);
                    break;

                case EdmDeltaEntityKind.LinkEntry:
                    WriteDeltaLink(entry, writer, writeContext);
                    break;

                case EdmDeltaEntityKind.Entry:
                {
                    IEdmEntityTypeReference   elementType     = GetEntityType(feedType);
                    ODataEntityTypeSerializer entrySerializer = SerializerProvider.GetEdmTypeSerializer(elementType) as ODataEntityTypeSerializer;
                    if (entrySerializer == null)
                    {
                        throw new SerializationException(
                                  Error.Format(SRResources.TypeCannotBeSerialized, elementType.FullName(), typeof(ODataMediaTypeFormatter).Name));
                    }
                    entrySerializer.WriteDeltaObjectInline(entry, elementType, writer, writeContext);
                    break;
                }

                default:
                    break;
                }
            }

            // Subtle and surprising behavior: If the NextPageLink property is set before calling WriteStart(feed),
            // the next page link will be written early in a manner not compatible with odata.streaming=true. Instead, if
            // the next page link is not set when calling WriteStart(feed) but is instead set later on that feed
            // object before calling WriteEnd(), the next page link will be written at the end, as required for
            // odata.streaming=true support.
            if (nextPageLink != null)
            {
                deltaFeed.NextPageLink = nextPageLink;
            }

            //End Writing of the Delta Feed
            writer.WriteEnd();
        }
Ejemplo n.º 44
0
        private static SerializableStateElement[] GetChildren(IEnumerable values, ref Type collectionType,
                                                              bool isProperty)
        {
            if (values == null)
            {
                return(Enumerable.Empty <SerializableStateElement>().ToArray());
            }
            var isDictionary     = values is IDictionary && !values.GetType().IsArray;
            var stateElementList = new List <SerializableStateElement>();

            if (isDictionary)
            {
                var dictionary       = (IDictionary)values;
                var dictionaryValues = (from object value in dictionary.Values select value).ToArray();
                var dictionaryKeys   = (from object key in dictionary.Keys select $"{key}").ToArray();

                var index = 0;

                foreach (var value in dictionaryValues)
                {
                    if (dictionaryKeys.Length <= index)
                    {
                        break;
                    }
                    var key = dictionaryKeys[index];

                    if (index == 0)
                    {
                        collectionType = value.GetType();
                    }

                    var isValueType = collectionType.IsValueType || value is string || collectionType == typeof(string) || value is Type;
                    var isArray     = /*value.GetType().IsArray ||*/ value is IEnumerable;
                    if (value is string)
                    {
                        isArray = false;
                    }

                    if (isArray)
                    {
                        var childrenCollectionType = collectionType;
                        var children = GetChildren(value as IEnumerable, ref childrenCollectionType, isProperty);
                        stateElementList.Add(new SerializableStateElement
                        {
                            Name       = $"{key}",
                            Value      = $"{collectionType.Name}{(collectionType.IsArray ? "" : "[]")}",
                            Type       = collectionType,
                            ObjectType = ObjectType.Array,
                            Children   = children
                        });
                    }
                    else if (!isValueType)
                    {
                        stateElementList.Add(new SerializableStateElement
                        {
                            Name       = $"{key}",
                            Value      = "",
                            Type       = collectionType,
                            ObjectType = ObjectType.Object,
                            Children   = GetChildren(value, isProperty)
                        });
                    }
                    else
                    {
                        stateElementList.Add(new SerializableStateElement
                        {
                            Name       = $"{key}",
                            Value      = value,
                            Type       = collectionType,
                            ObjectType = ObjectType.Value,
                            Children   = Enumerable.Empty <SerializableStateElement>().ToArray()
                        });
                    }
                    index++;
                }
            }
            else
            {
                var index = 0;
                foreach (var value in values)
                {
                    if (index == 0)
                    {
                        collectionType = value.GetType();
                    }

                    var isValueType = collectionType.IsValueType || value is string || collectionType == typeof(string) || value is Type;
                    var isArray     = /*value.GetType().IsArray ||*/ value is IEnumerable;
                    if (value is string)
                    {
                        isArray = false;
                    }

                    if (isArray)
                    {
                        var childrenCollectionType = collectionType;
                        var children = GetChildren(value as IEnumerable, ref childrenCollectionType, isProperty);
                        stateElementList.Add(new SerializableStateElement
                        {
                            Name       = $"{index}",
                            Value      = $"{collectionType.Name}{(collectionType.IsArray ? "" : "[]")}",
                            Type       = collectionType,
                            ObjectType = ObjectType.Array,
                            Children   = children
                        });
                    }
                    else if (!isValueType)
                    {
                        stateElementList.Add(new SerializableStateElement
                        {
                            Name       = $"{index}",
                            Value      = "",
                            Type       = collectionType,
                            ObjectType = ObjectType.Object,
                            Children   = GetChildren(value, isProperty)
                        });
                    }
                    else
                    {
                        stateElementList.Add(new SerializableStateElement
                        {
                            Name       = $"{index}",
                            Value      = value,
                            Type       = collectionType,
                            ObjectType = ObjectType.Value,
                            Children   = Enumerable.Empty <SerializableStateElement>().ToArray()
                        });
                    }
                    index++;
                }
            }
            return(stateElementList.ToArray());
        }
Ejemplo n.º 45
0
        public static bool DumpedCollection(
            this TextWriter writer,
            IEnumerable sequence,
            DumpAttribute dumpAttribute,
            Action <object> dumpObject,
            Action indent,
            Action unindent)
        {
            if (writer == null)
            {
                throw new ArgumentNullException(nameof(writer));
            }
            if (sequence == null)
            {
                throw new ArgumentNullException(nameof(sequence));
            }
            if (dumpAttribute == null)
            {
                throw new ArgumentNullException(nameof(dumpAttribute));
            }
            if (dumpObject == null)
            {
                throw new ArgumentNullException(nameof(dumpObject));
            }
            if (indent == null)
            {
                throw new ArgumentNullException(nameof(indent));
            }
            if (unindent == null)
            {
                throw new ArgumentNullException(nameof(unindent));
            }

            var sequenceType = sequence.GetType();
            var elementsType = sequenceType.IsArray
                                    ? new Type[] { sequenceType.GetElementType() }
                                    : sequenceType.IsGenericType
                                        ? sequenceType.GetGenericArguments()
                                        : new Type[] { typeof(object) };
            int count = 0;

            if (sequenceType.IsArray)
            {
                var piLength = sequenceType.GetProperty(nameof(Array.Length), BindingFlags.Instance | BindingFlags.Public);

                count = (int)piLength.GetValue(sequence);
            }
            else
            {
                var piCount = sequenceType.GetProperty(nameof(ICollection.Count), BindingFlags.Instance | BindingFlags.Public);

                if (piCount != null)
                {
                    count = (int)piCount.GetValue(sequence);
                }
                else
                {
                    count = int.MaxValue;
                }
            }

            // how many items to dump max?
            var max = dumpAttribute.GetMaxToDump(count);

            writer.Write(
                DumpFormat.SequenceTypeName,
                sequenceType.IsArray
                        ? elementsType[0].GetTypeName()
                        : sequenceType.GetTypeName(),
                count > 0 &&
                count < int.MaxValue
                        ? count.ToString(CultureInfo.InvariantCulture)
                        : string.Empty);

            if (sequence is byte[] bytes)
            {
                // dump no more than max elements from the sequence:
                writer.Write(BitConverter.ToString(bytes, 0, max));
                if (max < bytes.Length)
                {
                    writer.Write(DumpFormat.SequenceDumpTruncated, max, count);
                }

                return(true);
            }

            writer.Write(
                DumpFormat.SequenceType,
                sequenceType.GetTypeName(),
                sequenceType.Namespace,
                sequenceType.AssemblyQualifiedName);

            // stop the recursion if dump.Recurse is false
            if (dumpAttribute.RecurseDump != ShouldDump.Skip)
            {
                var n = 0;

                indent();

                foreach (var item in sequence)
                {
                    writer.WriteLine();
                    if (n++ >= max)
                    {
                        writer.Write(DumpFormat.SequenceDumpTruncated, max, count);
                        break;
                    }
                    dumpObject(item);
                }

                unindent();
            }

            return(true);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="Model"></param>
        /// <returns></returns>
        public static string GetLabel(this IEnumerable Model)
        {
            var elementType = Model.GetType().GetElementType() ?? Model.GetType().GetGenericArguments()[0];

            return(LabelFromType(elementType));
        }
Ejemplo n.º 47
0
 /// <summary>
 /// Forces the evaluation of a sequence if required, this is detected by the run time type of the sequence.
 /// Hot IEnumerables will always bypass evaluation.
 /// </summary>
 public static IEnumerable <T> Cache <T>(this IEnumerable <T> input)
 {
     return(TypeIsHotIEnumerable <T>(input.GetType())
         ? input
         : input.ToList());
 }
        private async Task WriteFeedAsync(IEnumerable enumerable, IEdmTypeReference feedType, ODataWriter writer,
                                          ODataSerializerContext writeContext)
        {
            Contract.Assert(writer != null);
            Contract.Assert(writeContext != null);
            Contract.Assert(enumerable != null);
            Contract.Assert(feedType != null);

            IEdmStructuredTypeReference elementType = GetResourceType(feedType);

            if (elementType.IsComplex())
            {
                ODataResourceSet resourceSet = new ODataResourceSet()
                {
                    TypeName = feedType.FullName()
                };

                await writer.WriteStartAsync(resourceSet).ConfigureAwait(false);

                ODataResourceSerializer entrySerializer = SerializerProvider.GetEdmTypeSerializer(elementType) as ODataResourceSerializer;
                if (entrySerializer == null)
                {
                    throw new SerializationException(
                              Error.Format(SRResources.TypeCannotBeSerialized, elementType.FullName()));
                }

                foreach (object entry in enumerable)
                {
                    await entrySerializer.WriteDeltaObjectInlineAsync(entry, elementType, writer, writeContext).ConfigureAwait(false);
                }
            }
            else
            {
                ODataDeltaResourceSet deltaFeed = CreateODataDeltaFeed(enumerable, feedType.AsCollection(), writeContext);
                if (deltaFeed == null)
                {
                    throw new SerializationException(Error.Format(SRResources.CannotSerializerNull, DeltaFeed));
                }

                // save the next page link for later to support JSON odata.streaming.
                Func <object, Uri> nextLinkGenerator = GetNextLinkGenerator(deltaFeed, enumerable, writeContext);
                deltaFeed.NextPageLink = null;

                //Start writing of the Delta Feed
                await writer.WriteStartAsync(deltaFeed).ConfigureAwait(false);

                object lastResource = null;
                //Iterate over all the entries present and select the appropriate write method.
                //Write method creates ODataDeltaDeletedEntry / ODataDeltaDeletedLink / ODataDeltaLink or ODataEntry.
                foreach (object entry in enumerable)
                {
                    if (entry == null)
                    {
                        throw new SerializationException(SRResources.NullElementInCollection);
                    }

                    lastResource = entry;
                    IEdmChangedObject edmChangedObject = entry as IEdmChangedObject;
                    if (edmChangedObject == null)
                    {
                        throw new SerializationException(Error.Format(
                                                             SRResources.CannotWriteType, GetType().Name, enumerable.GetType().FullName));
                    }

                    switch (edmChangedObject.DeltaKind)
                    {
                    case EdmDeltaEntityKind.DeletedEntry:
                        await WriteDeltaDeletedEntryAsync(entry, writer, writeContext).ConfigureAwait(false);

                        break;

                    case EdmDeltaEntityKind.DeletedLinkEntry:
                        await WriteDeltaDeletedLinkAsync(entry, writer, writeContext).ConfigureAwait(false);

                        break;

                    case EdmDeltaEntityKind.LinkEntry:
                        await WriteDeltaLinkAsync(entry, writer, writeContext).ConfigureAwait(false);

                        break;

                    case EdmDeltaEntityKind.Entry:
                    {
                        ODataResourceSerializer entrySerializer = SerializerProvider.GetEdmTypeSerializer(elementType) as ODataResourceSerializer;
                        if (entrySerializer == null)
                        {
                            throw new SerializationException(
                                      Error.Format(SRResources.TypeCannotBeSerialized, elementType.FullName()));
                        }
                        await entrySerializer.WriteDeltaObjectInlineAsync(entry, elementType, writer, writeContext)
                        .ConfigureAwait(false);

                        break;
                    }

                    default:
                        break;
                    }
                }

                // Subtle and surprising behavior: If the NextPageLink property is set before calling WriteStart(feed),
                // the next page link will be written early in a manner not compatible with odata.streaming=true. Instead, if
                // the next page link is not set when calling WriteStart(feed) but is instead set later on that feed
                // object before calling WriteEnd(), the next page link will be written at the end, as required for
                // odata.streaming=true support.

                deltaFeed.NextPageLink = nextLinkGenerator(lastResource);
            }

            //End Writing of the Delta Feed
            await writer.WriteEndAsync().ConfigureAwait(false);
        }
Ejemplo n.º 49
0
            private string Format <T>(IEnumerable <T> enumerable)
            {
                string ret = _astFormatter.Format(enumerable);

                return(string.IsNullOrWhiteSpace(ret) ? enumerable.GetType().Name : ret);
            }
Ejemplo n.º 50
0
        protected virtual void WriteDictionary(IEnumerable value)
        {
            IDictionaryEnumerator enumerator = value.GetEnumerator() as IDictionaryEnumerator;

            if (enumerator == null)
            {
                throw new JsonSerializationException(String.Format(JsonWriter.ErrorIDictionaryEnumerator, value.GetType()));
            }

            bool appendDelim = false;

            if (settings.HandleCyclicReferences)
            {
                int prevIndex = 0;
                if (this.previouslySerializedObjects.TryGetValue(value, out prevIndex))
                {
                    this.Writer.Write(JsonReader.OperatorObjectStart);
                    this.WriteObjectProperty("@ref", prevIndex);
                    this.WriteLine();
                    this.Writer.Write(JsonReader.OperatorObjectEnd);
                    return;
                }
                else
                {
                    this.previouslySerializedObjects.Add(value, this.previouslySerializedObjects.Count);
                }
            }

            this.Writer.Write(JsonReader.OperatorObjectStart);

            this.depth++;
            if (this.depth > this.settings.MaxDepth)
            {
                throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth));
            }

            try
            {
                while (enumerator.MoveNext())
                {
                    if (appendDelim)
                    {
                        this.WriteObjectPropertyDelim();
                    }
                    else
                    {
                        appendDelim = true;
                    }

                    this.WriteObjectProperty(Convert.ToString(enumerator.Entry.Key), enumerator.Entry.Value);
                }
            }
            finally
            {
                this.depth--;
            }

            if (appendDelim)
            {
                this.WriteLine();
            }
            this.Writer.Write(JsonReader.OperatorObjectEnd);
        }
Ejemplo n.º 51
0
            internal void WriteSpecificProperties(BinaryWriter bw, [NoEnumeration] IEnumerable collection, SerializationManager manager)
            {
                if (IsSingleElement)
                {
                    return;
                }

                // 1.) Count
                Write7BitInt(bw, collection.Count());

                // 2.) Capacity - public property in all cases
                if (HasCapacity)
                {
                    Write7BitInt(bw, collection.Capacity());
                }

                // 3.) Case sensitivity - only HybridDictionary
                if (HasCaseInsensitivity)
                {
                    bw.Write(collection.IsCaseInsensitive());
                }

                // 4.) ReadOnly
                if (HasReadOnly)
                {
                    switch (collection)
                    {
                    case IList list:
                        bw.Write(list.IsReadOnly);
                        break;

                    case IDictionary dictionary:
                        bw.Write(dictionary.IsReadOnly);
                        break;

                    default:
                        // should never occur for supported collections
                        bw.Write(false);
                        Debug.Fail("Could not write IsReadOnly state of collection " + collection.GetType());
                        break;
                    }
                }

                // 5.) Comparer
                if (HasAnyComparer)
                {
                    object comparer          = collection.GetComparer();
                    bool   isDefaultComparer = comparer == null || IsDefaultComparer(collection, comparer);
                    bw.Write(isDefaultComparer);
                    if (!isDefaultComparer)
                    {
                        manager.WriteNonRoot(bw, comparer);
                    }
                }
            }
Ejemplo n.º 52
0
        //public static string StringJoin(this ICollection icollection, string separator = ", ") =>
        //string.Join(separator, icollection.Cast<object>());

        public static string StringInfo <T>(this IEnumerable <T> items, string separator = ", ")
        => $"{items.GetType().Name}<{typeof(T).Name}>({items.Count()}) {StringJoin(items, separator)}";
Ejemplo n.º 53
0
        /// <summary>
        /// Filter the elements of an array by a given condition
        /// {% assign sorted = pages | where:"propName","==","value" %}
        /// </summary>
        /// <param name="input"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        public static object Where(object input, string propName, string op, string value)
        {
            var         retVal     = input;
            IEnumerable enumerable = retVal as IEnumerable;

            if (enumerable != null)
            {
                var queryable   = enumerable.AsQueryable();
                var elementType = enumerable.GetType().GetEnumerableType();

                ParameterExpression paramX = Expression.Parameter(elementType, "x");
                var propInfo = elementType.GetProperty(propName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
                var left     = Expression.Property(paramX, propInfo);
                var objValue = ParseString(value);
                var right    = Expression.Constant(objValue);
                BinaryExpression binaryOp;

                if (op.EqualsInvariant("=="))
                {
                    binaryOp = Expression.Equal(left, right);
                }
                else if (op.EqualsInvariant("!="))
                {
                    binaryOp = Expression.NotEqual(left, right);
                }
                else if (op.EqualsInvariant(">"))
                {
                    binaryOp = Expression.GreaterThan(left, right);
                }
                else if (op.EqualsInvariant(">="))
                {
                    binaryOp = Expression.GreaterThanOrEqual(left, right);
                }
                else if (op.EqualsInvariant("=<"))
                {
                    binaryOp = Expression.LessThan(left, right);
                }
                else if (op.EqualsInvariant("contains"))
                {
                    Expression expr = null;
                    if (propInfo.PropertyType == typeof(string))
                    {
                        var containsMethod = typeof(string).GetMethods().Where(x => x.Name == "Contains").First();
                        expr = Expression.Call(left, containsMethod, right);
                    }
                    else
                    {
                        var containsMethod = typeof(Enumerable).GetMethods().Where(x => x.Name == "Contains" && x.GetParameters().Count() == 2).First().MakeGenericMethod(new Type[] { objValue.GetType() });
                        expr = Expression.Call(containsMethod, left, right);
                    }

                    //where(x=> x.Tags.Contains(y))
                    binaryOp = Expression.Equal(expr, Expression.Constant(true));
                }
                else
                {
                    binaryOp = Expression.LessThanOrEqual(left, right);
                }

                Type delegateType = typeof(Func <,>).MakeGenericType(elementType, typeof(bool));

                //Construct Func<T, bool> = (x) => x.propName == value expression
                LambdaExpression lambda = Expression.Lambda(delegateType, binaryOp, paramX);

                //Find Queryable.Where(Expression<Func<TSource, bool>>) method
                var whereMethod = typeof(Queryable).GetMethods()
                                  .Where(x => x.Name == "Where")
                                  .Select(x => new { M = x, P = x.GetParameters() })
                                  .Where(x => x.P.Length == 2 &&
                                         x.P[0].ParameterType.IsGenericType &&
                                         x.P[0].ParameterType.GetGenericTypeDefinition() == typeof(IQueryable <>) &&
                                         x.P[1].ParameterType.IsGenericType &&
                                         x.P[1].ParameterType.GetGenericTypeDefinition() == typeof(Expression <>))
                                  .Select(x => new { x.M, A = x.P[1].ParameterType.GetGenericArguments() })
                                  .Where(x => x.A[0].IsGenericType &&
                                         x.A[0].GetGenericTypeDefinition() == typeof(Func <,>))
                                  .Select(x => new { x.M, A = x.A[0].GetGenericArguments() })
                                  .Where(x => x.A[0].IsGenericParameter &&
                                         x.A[1] == typeof(bool))
                                  .Select(x => x.M)
                                  .SingleOrDefault();

                retVal = whereMethod.MakeGenericMethod(elementType).Invoke(null, new object[] { queryable, lambda });
            }

            return(retVal);
        }
Ejemplo n.º 54
0
        static void asStringRec(
            IEnumerable enumerable, StringBuilder sb,
            bool newlines, bool fullClasses, int indent = 0
            )
        {
            var type = enumerable.GetType();

            sb.Append(fullClasses ? type.FullName : type.Name);
            sb.Append('[');

            var first = true;

            foreach (var item in enumerable)
            {
                if (!first)
                {
                    sb.Append(',');
                }
                if (newlines)
                {
                    sb.Append('\n');
                    for (var idx = 0; idx < indent; idx++)
                    {
                        sb.Append("  ");
                    }
                }
                else if (!first)
                {
                    sb.Append(' ');
                }

                var str = item as string; // String is IEnumerable as well
                if (str != null)
                {
                    sb.Append(str);
                }
                else
                {
                    var enumItem = item as IEnumerable;
                    if (enumItem != null)
                    {
                        asStringRec(enumItem, sb, newlines, fullClasses, indent + 1);
                    }
                    else
                    {
                        sb.Append(item);
                    }
                }
                first = false;
            }

            if (newlines)
            {
                sb.Append('\n');
                for (var idx = 0; idx < indent - 1; idx++)
                {
                    sb.Append("  ");
                }
            }
            sb.Append(']');
        }
Ejemplo n.º 55
0
        protected virtual void WriteDictionary(IEnumerable value)
        {
            IDictionaryEnumerator enumerator = value.GetEnumerator() as IDictionaryEnumerator;

            if (enumerator == null)
            {
                throw new JsonSerializationException(String.Format(JsonWriter.ErrorIDictionaryEnumerator, value.GetType()));
            }

            bool appendDelim = false;

            this.Writer.Write(JsonReader.OperatorObjectStart);

            this.depth++;
            if (this.depth > this.settings.MaxDepth)
            {
                throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth));
            }

            try
            {
                while (enumerator.MoveNext())
                {
                    if (appendDelim)
                    {
                        this.WriteObjectPropertyDelim();
                    }
                    else
                    {
                        appendDelim = true;
                    }

                    this.WriteObjectProperty(Convert.ToString(enumerator.Entry.Key), enumerator.Entry.Value);
                }
            }
            finally
            {
                this.depth--;
            }

            if (appendDelim)
            {
                this.WriteLine();
            }
            this.Writer.Write(JsonReader.OperatorObjectEnd);
        }
Ejemplo n.º 56
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StreamedSequence"/> class, setting the <see cref="Sequence"/> and
        /// <see cref="DataInfo"/> properties.
        /// </summary>
        /// <param name="sequence">The sequence.</param>
        /// <param name="streamedSequenceInfo">An instance of <see cref="StreamedSequenceInfo"/> describing the sequence.</param>
        public StreamedSequence(IEnumerable sequence, StreamedSequenceInfo streamedSequenceInfo)
        {
            ArgumentUtility.CheckNotNull("sequence", sequence);
            ArgumentUtility.CheckNotNull("streamedSequenceInfo", streamedSequenceInfo);
            if (!streamedSequenceInfo.DataType.IsInstanceOfType(sequence))
            {
                throw new ArgumentTypeException("sequence", streamedSequenceInfo.DataType, sequence.GetType());
            }

            DataInfo = streamedSequenceInfo;
            Sequence = sequence;
        }
Ejemplo n.º 57
0
 public void PublishAll(IEnumerable <object> requestDtos)
 {
     GetGateway(requestDtos.GetType().GetCollectionType()).PublishAll(requestDtos);
 }
Ejemplo n.º 58
0
        ///<summary>
        /// Gets the Type of a list item.
        ///</summary>
        /// <param name="list">A <see cref="System.Object"/> instance. </param>
        ///<returns>The Type instance that represents the exact runtime type of a list item.</returns>
        public static Type GetListItemType(this IEnumerable list)
        {
            var typeOfObject = typeof(object);

            if (list == null)
            {
                return(typeOfObject);
            }

            if (list is Array)
            {
                return(list.GetType().GetElementType());
            }

            var type = list.GetType();

            if (list is IList
#if !SILVERLIGHT && !NETFX_CORE
                || list is ITypedList || list is IListSource
#endif
                )
            {
                PropertyInfo last = null;

                foreach (var pi in type.GetPropertiesEx())
                {
                    if (pi.GetIndexParameters().Length > 0 && pi.PropertyType != typeOfObject)
                    {
                        if (pi.Name == "Item")
                        {
                            return(pi.PropertyType);
                        }

                        last = pi;
                    }
                }

                if (last != null)
                {
                    return(last.PropertyType);
                }
            }

            if (list is IList)
            {
                foreach (var o in (IList)list)
                {
                    if (o != null && o.GetType() != typeOfObject)
                    {
                        return(o.GetType());
                    }
                }
            }
            else
            {
                foreach (var o in list)
                {
                    if (o != null && o.GetType() != typeOfObject)
                    {
                        return(o.GetType());
                    }
                }
            }

            return(typeOfObject);
        }
Ejemplo n.º 59
0
 public List <TResponse> SendAll <TResponse>(IEnumerable <object> requestDtos)
 {
     return(GetGateway(requestDtos.GetType().GetCollectionType()).SendAll <TResponse>(requestDtos));
 }
Ejemplo n.º 60
0
        public IEnumerable CollectChildRecords(IEnumerable datasource, DataManagerRequest dm)
        {
            IEnumerable enumerable1 = (IEnumerable)SfBaseUtils.ChangeType((object)datasource, datasource.GetType());
            string      idMapping   = dm.IdMapping;

            object[] objArray = new object[0];
            if (enumerable1.GetType() == typeof(List <ExpandoObject>) || enumerable1.GetElementType() == typeof(ExpandoObject))
            {
                foreach (IDictionary <string, object> dictionary in datasource.Cast <ExpandoObject>().ToList <ExpandoObject>())
                {
                    object obj = dictionary[idMapping];
                    objArray = ((IEnumerable <object>)objArray).Concat <object>((IEnumerable <object>) new object[1]
                    {
                        obj
                    }).ToArray <object>();
                }
            }
            else
            {
                foreach (object obj1 in datasource)
                {
                    object obj2 = obj1.GetType().GetProperty(idMapping).GetValue(obj1);
                    objArray = ((IEnumerable <object>)objArray).Concat <object>((IEnumerable <object>) new object[1]
                    {
                        obj2
                    }).ToArray <object>();
                }
            }
            IEnumerable enumerable2 = (IEnumerable)null;

            foreach (object obj in objArray)
            {
                dm.Where[0].value = obj;
                IEnumerable enumerable3 = enumerable1.GetType() == typeof(List <ExpandoObject>) || enumerable1.GetElementType() == typeof(ExpandoObject) ? (IEnumerable)DynamicObjectOperation.PerformFiltering(enumerable1, dm.Where, dm.Where[0].Operator) : DataOperations.PerformFiltering(enumerable1, dm.Where, dm.Where[0].Operator);
                enumerable2 = enumerable2 == null || enumerable2.AsQueryable().Count() == 0 ? enumerable3 : (IEnumerable)((IEnumerable <object>)enumerable2).Concat <object>((IEnumerable <object>)enumerable3);
            }
            if (enumerable2 != null)
            {
                IEnumerable enumerable3 = this.CollectChildRecords(enumerable2, dm);
                if (dm.Sorted != null && dm.Sorted.Count > 0)
                {
                    enumerable3 = enumerable1.GetType() == typeof(List <ExpandoObject>) || enumerable1.GetElementType() == typeof(ExpandoObject) ? (IEnumerable)DynamicObjectOperation.PerformSorting(enumerable3.AsQueryable(), dm.Sorted) : DataOperations.PerformSorting(enumerable3, dm.Sorted);
                }
                datasource = (IEnumerable)((IEnumerable <object>)datasource).Concat <object>((IEnumerable <object>)enumerable3);
            }
            return(datasource);
        }