System.Type.MakeGenericType(params System.Type[])

Here are the examples of the csharp api System.Type.MakeGenericType(params System.Type[]) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

3883 Examples 7

19 View Source File : ForEachExpression.cs
License : MIT License
Project Creator : 71

private void ResolveEnumerationMembers (
			out MethodInfo get_enumerator,
			out MethodInfo get_current)
		{
			Type item_type;
			Type enumerable_type;
			Type enumerator_type;

			if (TryGetGenericEnumerableArgument(out item_type))
            {
				enumerable_type = typeof(IEnumerable<>).MakeGenericType(item_type);
				enumerator_type = typeof(IEnumerator<>).MakeGenericType(item_type);
			}
            else
            {
				enumerable_type = typeof(IEnumerable);
				enumerator_type = typeof(IEnumerator);
			}

			get_current = enumerator_type.GetRuntimeProperty(nameof(IEnumerator<object>.Current)).GetMethod;
			get_enumerator = Enumerable.Type.GetRuntimeMethod("GetEnumerator", Type.EmptyTypes);

			if (get_enumerator == null || !enumerator_type.GetTypeInfo().IsreplacedignableFrom(get_enumerator.ReturnType.GetTypeInfo()))
                get_enumerator = enumerable_type.GetRuntimeMethod("GetEnumerator", Type.EmptyTypes);
		}

19 View Source File : AutofacBootstrapper.cs
License : Microsoft Public License
Project Creator : achimismaili

protected override System.Collections.Generic.IEnumerable<object> GetAllInstances(System.Type service)
        {
            return Container.Resolve(typeof(IEnumerable<>).MakeGenericType(service)) as IEnumerable<object>;
        }

19 View Source File : IDictionaryResolver.cs
License : MIT License
Project Creator : 1996v

public static void GenerateDeserializeWithIDictionaryEmptyCtor()
        {
            /*
              var map = MapFormatterHelper.Deserialize(ref reader,ref context);
              if (map == null)
                  return null;
              context.option.Security.DepthStep(ref reader);
              T t = new T();
              Deserialize(IEnumerable<KeyValuePair<TKey, TValue>> pair,(ICollection<KeyValuePair<TKey, TValue>>)t);
              reader = map.Reader; context = map.Context; 
              reader.Seek(map.EndPos);
              context.Depth--;
              return t;  
           */

            ArrayPack<Expression> ary = new ArrayPack<Expression>(10);
            Type t = typeof(T);
            LabelTarget returnTarget = Expression.Label(t, "returnLable");
            ParameterExpression map = Expression.Variable(typeof(IMapDataSource<,>).MakeGenericType(typeof(object), typeof(object)));
            //map = MapFormatterHelper.Deserialize(ref reader,ref context);
            ary.Add(Expression.replacedign(map, CommonExpressionMeta.Call_MapFormatterHelper_Deserialize(typeof(object), typeof(object))));
            //if (map == null)
            //      goto label;
            ary.Add(Expression.IfThen(Expression.Equal(map, Expression.Constant(null, map.Type)), Expression.Return(returnTarget, Expression.Default(t))));
            //context.option.Security.DepthStep(ref reader);
            ary.Add(CommonExpressionMeta.Call_DeserializeContext_Option_Security_DepthStep);
            //T t = new T();
            ParameterExpression instance = Expression.Variable(t);
            ary.Add(Expression.replacedign(instance, Expression.New(t)));
            //MapFormatterHelper.FillData(map,(IDictionary)t)
            ary.Add(Expression.Call(null, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.FillIDictionaryData), BindingFlags.Public | BindingFlags.Static), map, Expression.Convert(instance, typeof(IDictionary))));

            //reader = map.Reader; context = map.Context; 
            ary.Add(CommonExpressionMeta.Block_MapReaderAndContextreplacedignLocalReaderAndContext(map));
            //reader.Seek(map.EndPos);
            ary.Add(CommonExpressionMeta.Call_Reader_BufferSeek(Expression.Property(map, nameof(IMapDataSource<int, int>.EndPosition))));
            //context.Depth--;
            ary.Add(CommonExpressionMeta.Call_DeserializeContext_Depth_Decrementreplacedign);
            //return t;
            ary.Add(Expression.Return(returnTarget, instance));
            //label default(T)
            ary.Add(Expression.Label(returnTarget, instance));

            BlockExpression block = Expression.Block(new ParameterExpression[] { map, instance }, ary.GetArray());
            Deserialize = Expression.Lambda<Deserialize<T>>(block, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext).Compile();
        }

19 View Source File : ImmutableCollectionDecorator.cs
License : MIT License
Project Creator : 404Lcc

internal static bool IdentifyImmutable(TypeModel model, Type declaredType, out MethodInfo builderFactory, out MethodInfo add, out MethodInfo addRange, out MethodInfo finish)
        {
            builderFactory = add = addRange = finish = null;
            if (model == null || declaredType == null) return false;
#if WINRT || COREFX || PROFILE259
			TypeInfo declaredTypeInfo = declaredType.GetTypeInfo();
#else
            Type declaredTypeInfo = declaredType;
#endif

            // try to detect immutable collections; firstly, they are all generic, and all implement IReadOnlyCollection<T> for some T
            if(!declaredTypeInfo.IsGenericType) return false;

#if WINRT || COREFX || PROFILE259
			Type[] typeArgs = declaredTypeInfo.GenericTypeArguments, effectiveType;
#else
            Type[] typeArgs = declaredTypeInfo.GetGenericArguments(), effectiveType;
#endif
            switch (typeArgs.Length)
            {
                case 1:
                    effectiveType = typeArgs;
                    break; // fine
                case 2:
                    Type kvp = model.MapType(typeof(System.Collections.Generic.KeyValuePair<,>));
                    if (kvp == null) return false;
                    kvp = kvp.MakeGenericType(typeArgs);
                    effectiveType = new Type[] { kvp };
                    break;
                default:
                    return false; // no clue!
            }

            if (ResolveIReadOnlyCollection(declaredType, null) == null) return false; // no IReadOnlyCollection<T> found

            // and we want to use the builder API, so for generic Foo<T> or IFoo<T> we want to use Foo.CreateBuilder<T>
            string name = declaredType.Name;
            int i = name.IndexOf('`');
            if (i <= 0) return false;
            name = declaredTypeInfo.IsInterface ? name.Substring(1, i - 1) : name.Substring(0, i);

            Type outerType = model.GetType(declaredType.Namespace + "." + name, declaredTypeInfo.replacedembly);
            // I hate special-cases...
            if (outerType == null && name == "ImmutableSet")
            {
                outerType = model.GetType(declaredType.Namespace + ".ImmutableHashSet", declaredTypeInfo.replacedembly);
            }
            if (outerType == null) return false;

#if WINRT || PROFILE259
			foreach (MethodInfo method in outerType.GetTypeInfo().DeclaredMethods)
#else
            foreach (MethodInfo method in outerType.GetMethods())
#endif
            {
                if (!method.IsStatic || method.Name != "CreateBuilder" || !method.IsGenericMethodDefinition || method.GetParameters().Length != 0
                    || method.GetGenericArguments().Length != typeArgs.Length) continue;

                builderFactory = method.MakeGenericMethod(typeArgs);
                break;
            }
            Type voidType = model.MapType(typeof(void));
            if (builderFactory == null || builderFactory.ReturnType == null || builderFactory.ReturnType == voidType) return false;


            add = Helpers.GetInstanceMethod(builderFactory.ReturnType, "Add", effectiveType);
            if (add == null) return false;

            finish = Helpers.GetInstanceMethod(builderFactory.ReturnType, "ToImmutable", Helpers.EmptyTypes);
            if (finish == null || finish.ReturnType == null || finish.ReturnType == voidType) return false;

            if (!(finish.ReturnType == declaredType || Helpers.IsreplacedignableFrom(declaredType, finish.ReturnType))) return false;

            addRange = Helpers.GetInstanceMethod(builderFactory.ReturnType, "AddRange", new Type[] { declaredType });
            if (addRange == null)
            {
                Type enumerable = model.MapType(typeof(System.Collections.Generic.IEnumerable<>), false);
                if (enumerable != null)
                {
                    addRange = Helpers.GetInstanceMethod(builderFactory.ReturnType, "AddRange", new Type[] { enumerable.MakeGenericType(effectiveType) });
                }
            }

            return true;
        }

19 View Source File : SagaMaster.cs
License : MIT License
Project Creator : 2881099

SagaMaster<TDBKey> Then(Type sagaUnitType, object state)
        {
            if (sagaUnitType == null) throw new ArgumentNullException(nameof(sagaUnitType));
            var unitTypeBase = typeof(SagaUnit<>);
            if (state == null && sagaUnitType.BaseType.GetGenericTypeDefinition() == typeof(SagaUnit<>)) unitTypeBase = unitTypeBase.MakeGenericType(sagaUnitType.BaseType.GetGenericArguments()[0]);
            else unitTypeBase = unitTypeBase.MakeGenericType(state.GetType());
            if (unitTypeBase.IsreplacedignableFrom(sagaUnitType) == false) throw new ArgumentException($"{sagaUnitType.DisplayCsharp(false)} 必须继承 {unitTypeBase.DisplayCsharp(false)}");
            var unitCtors = sagaUnitType.GetConstructors();
            if (unitCtors.Length != 1 && unitCtors[0].GetParameters().Length > 0) throw new ArgumentException($"{sagaUnitType.FullName} 不能使用构造函数");

            var unitTypeConved = Type.GetType(sagaUnitType.replacedemblyQualifiedName);
            if (unitTypeConved == null) throw new ArgumentException($"{sagaUnitType.FullName} 无效");
            var unit = unitTypeConved.CreateInstanceGetDefaultValue() as ISagaUnit;
            (unit as ISagaUnitSetter)?.SetState(state);
            _thenUnits.Add(unit);
            _thenUnitInfos.Add(new SagaUnitInfo
            {
                Description = unitTypeConved.GetDescription(),
                Index = _thenUnitInfos.Count + 1,
                Stage = SagaUnitStage.Commit,
                State = state == null ? null : Newtonsoft.Json.JsonConvert.SerializeObject(state),
                StateTypeName = state?.GetType().replacedemblyQualifiedName,
                Tid = _tid,
                TypeName = sagaUnitType.replacedemblyQualifiedName,
            });
            return this;
        }

19 View Source File : ICollectionResolver.cs
License : MIT License
Project Creator : 1996v

public static TypeInfo BuildICollectionInterfaceType(DynamicFormatterreplacedembly replacedembly, Type type, Type elementType)
        {
            TypeBuilder typeBuilder = replacedembly.DefineCollectionFormatterType(type, elementType);

            MethodBuilder serializeMethod = TypeBuildHelper.DefineSerializeMethod(typeBuilder, type);
            MethodBuilder deserializeMethod = TypeBuildHelper.DefineDeserializeMethod(typeBuilder, type);
            MethodBuilder sizeMethod = TypeBuildHelper.DefineSizeMethod(typeBuilder, type);

            if (type.IsGenericType == false)
            {
                DEBUG.replacedert(type == typeof(IEnumerable) || type == typeof(IList) || type == typeof(ICollection));
                //itemType is Object, Array2
                if (type == typeof(IList))
                {
                    TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeIList), BindingFlags.Public | BindingFlags.Static));
                }
                else
                {
                    TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeIEnumerable), BindingFlags.Public | BindingFlags.Static));
                }

                TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.DeserializeList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(typeof(object)));

                TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SizeIEnumerable), BindingFlags.Public | BindingFlags.Static));
            }
            else
            {
                Type genericTypeDefine = type.GetGenericTypeDefinition();
                DEBUG.replacedert(genericTypeDefine == typeof(IEnumerable<>) || genericTypeDefine == typeof(IList<>) || genericTypeDefine == typeof(ICollection<>) || genericTypeDefine == typeof(ISet<>) || genericTypeDefine == typeof(IReadOnlyList<>) || genericTypeDefine == typeof(IReadOnlyCollection<>));

                if (Array1FormatterHelper.IsArray1Type(elementType))
                {
                    //Array1
                    TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array1FormatterHelper).GetMethod(nameof(Array1FormatterHelper.SerializeIEnumerable), new Type[] { typeof(BssomWriter).MakeByRefType(), typeof(BssomSerializeContext).MakeByRefType(), typeof(IEnumerable<>).MakeGenericType(elementType) }));

                    if (genericTypeDefine == typeof(ISet<>))
                    {
                        TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, typeof(Array1FormatterHelper).GetMethod(Array1FormatterHelper.DeserializeSetPrefix + elementType.Name, BindingFlags.Public | BindingFlags.Static));
                    }
                    else
                    {
                        Type listFormatterType = Array1ResolverGetFormatterHelper.GetListFormatterType(elementType);
                        FieldInfo field = listFormatterType.GetField(nameof(DateTimeListFormatter.Instance), BindingFlags.Static | BindingFlags.Public);
                        MethodInfo method = listFormatterType.GetMethod(nameof(DateTimeListFormatter.Deserialize));
                        TypeBuildHelper.CallOneStaticFieldMethodInDeserialize(deserializeMethod, field, method);
                    }

                    TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array1FormatterHelper).GetMethod(nameof(Array1FormatterHelper.SizeIEnumerable), new Type[] { typeof(BssomSizeContext).MakeByRefType(), typeof(IEnumerable<>).MakeGenericType(elementType) }));
                }
                else
                {
                    if (genericTypeDefine == typeof(IList<>) || genericTypeDefine == typeof(IReadOnlyList<>))
                    {
                        TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeGenerIList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
                    }
                    else
                    {
                        TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeGenericIEnumerable), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
                    }

                    if (genericTypeDefine == typeof(ISet<>))
                    {
                        TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.DeserializeSet), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
                    }
                    else
                    {
                        TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.DeserializeList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
                    }

                    TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SizeGenericIEnumerable), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
                }
            }

            return typeBuilder.CreateTypeInfo();
        }

19 View Source File : Amf3Reader.cs
License : MIT License
Project Creator : a1q123456

public bool TryGetVectorObject(Span<byte> buffer, out object value, out int consumed)
        {
            value = default;
            consumed = default;

            if (!DataIsType(buffer, Amf3Type.VectorObject))
            {
                return false;
            }

            buffer = buffer.Slice(Amf3CommonValues.MARKER_LENGTH);

            int arrayConsumed = 0;

            if (!ReadVectorHeader(ref buffer, ref value, ref arrayConsumed, out var itemCount, out var isFixedSize, out var isRef))
            {
                return false;
            }

            if (isRef)
            {
                consumed = arrayConsumed;
                return true;
            }

            if (!ReadVectorTypeName(ref buffer, out var typeName, out var typeNameConsumed))
            {
                return false;
            }

            var arrayBodyBuffer = buffer;

            object resultVector = null;
            Type elementType = null;
            Action<object> addAction = null;
            if (typeName == "*")
            {
                elementType = typeof(object);
                var v = new Vector<object>();
                _objectReferenceTable.Add(v);
                v.IsFixedSize = isFixedSize;
                resultVector = v;
                addAction = v.Add;
            }
            else
            {
                if (!_registeredTypedObejectStates.TryGetValue(typeName, out var state))
                {
                    return false;
                }
                elementType = state.Type;

                var vectorType = typeof(Vector<>).MakeGenericType(elementType);
                resultVector = Activator.CreateInstance(vectorType);
                _objectReferenceTable.Add(resultVector);
                vectorType.GetProperty("IsFixedSize").SetValue(resultVector, isFixedSize);
                var addMethod = vectorType.GetMethod("Add");
                addAction = o => addMethod.Invoke(resultVector, new object[] { o });
            }
            for (int i = 0; i < itemCount; i++)
            {
                if (!TryGetValue(arrayBodyBuffer, out var item, out var itemConsumed))
                {
                    return false;
                }
                addAction(item);

                arrayBodyBuffer = arrayBodyBuffer.Slice(itemConsumed);
                arrayConsumed += itemConsumed;
            }
            value = resultVector;
            consumed = typeNameConsumed + arrayConsumed;
            return true;
        }

19 View Source File : DynamicAssembly.cs
License : MIT License
Project Creator : 1996v

public TypeBuilder DefineCollectionFormatterType(Type type, Type elementType)
        {
            VerifyTypeIsPublic(type);

            string pre = "Array2.";
            if (Array1FormatterHelper.IsArray1Type(elementType))
            {
                pre = "Array1.";
            }

            Type formatterType = typeof(IBssomFormatter<>).MakeGenericType(type);
            TypeBuilder typeBuilder = DefineType("Bssom.Formatters." + pre + SubtractFullNameRegex.Replace(type.FullName, string.Empty).Replace(".", "_") + "Formatter" + Interlocked.Increment(ref nameSequence), TypeAttributes.NotPublic | TypeAttributes.Sealed, null, new[] { formatterType });
            return typeBuilder;
        }

19 View Source File : Serializer.cs
License : GNU General Public License v3.0
Project Creator : Adam-Wilkinson

public object TryDeserializeObject(object serialized, Type requestedType, object deserializationContext)
        {
            if (requestedType is not null)
            {
                if (requestedType.IsEnum)
                {
                    return Enum.ToObject(requestedType, serialized);
                }
            }

            Type deserializedType = serialized.GetType().GetInterfaces().Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(ISerializedObject<>)).FirstOrDefault()?.GetGenericArguments()[0];
            if (deserializedType is not null && Serializers.TryGetValue(deserializedType, out object serializer))
            {
                return typeof(IObjectSerializer<>).MakeGenericType(deserializedType).GetMethod(nameof(IObjectSerializer<object>.DeSerialize)).Invoke(serializer, new object[] { serialized, this, deserializationContext });
            }


            if (requestedType is not null)
            {
            }

            return serialized;
        }

19 View Source File : TypeBuildHelper.cs
License : MIT License
Project Creator : 1996v

public static void CallSerializeDelegate(MethodBuilder serializeMethod, Type genericType, FieldInfo fieldInfo)
        {
            ILGenerator il = serializeMethod.GetILGenerator();
            il.Emit(OpCodes.Ldsfld, fieldInfo);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Ldarg_2);
            il.Emit(OpCodes.Ldarg_3);
            il.Emit(OpCodes.Call, typeof(Serialize<>).MakeGenericType(genericType).GetMethod(nameof(Serialize<int>.Invoke)));
            il.Emit(OpCodes.Ret);
        }

19 View Source File : Admin.cs
License : MIT License
Project Creator : 2881099

async public static Task<bool> Use(HttpContext context, IFreeSql fsql, string requestPathBase, Dictionary<string, Type> dicEnreplacedyTypes) {
			HttpRequest req = context.Request;
			HttpResponse res = context.Response;

			var remUrl = req.Path.ToString().Substring(requestPathBase.Length).Trim(' ', '/').Split('/');
			var enreplacedyName = remUrl.FirstOrDefault();

			if (!string.IsNullOrEmpty(enreplacedyName)) {

				if (dicEnreplacedyTypes.TryGetValue(enreplacedyName, out var enreplacedyType) == false) throw new Exception($"UseFreeAdminLtePreview 错误,找不到实体类型:{enreplacedyName}");

				var tb = fsql.CodeFirst.GetTableByEnreplacedy(enreplacedyType);
				if (tb == null) throw new Exception($"UseFreeAdminLtePreview 错误,实体类型无法映射:{enreplacedyType.FullName}");

				var tpl = _tpl.Value;

				switch (remUrl.ElementAtOrDefault(1)?.ToLower()) {
					case null:
						//首页
						if (true) {
							MakeTemplateFile($"{enreplacedyName}-list.html", Views.List);

							//ManyToOne/OneToOne
							var getlistFilter = new List<(TableRef, string, string, Dictionary<string, object>, List<Dictionary<string, object>>)>();
							foreach (var prop in tb.Properties) {
								if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
								var tbref = tb.GetTableRef(prop.Key, false);
								if (tbref == null) continue;
								switch (tbref.RefType) {
									case TableRefType.OneToMany: continue;
									case TableRefType.ManyToOne:
										getlistFilter.Add(await Utils.GetTableRefData(fsql, tbref));
										continue;
									case TableRefType.OneToOne:
										continue;
									case TableRefType.ManyToMany:
										getlistFilter.Add(await Utils.GetTableRefData(fsql, tbref));
										continue;
								}
							}

							int.TryParse(req.Query["page"].FirstOrDefault(), out var getpage);
							int.TryParse(req.Query["limit"].FirstOrDefault(), out var getlimit);
							if (getpage <= 0) getpage = 1;
							if (getlimit <= 0) getlimit = 20;

							var getselect = fsql.Select<object>().AsType(enreplacedyType);
							foreach (var getlistF in getlistFilter) {
								var qv = req.Query[getlistF.Item3].ToArray();
								if (qv.Any()) {
									switch (getlistF.Item1.RefType) {
										case TableRefType.OneToMany: continue;
										case TableRefType.ManyToOne:
											getselect.Where(Utils.GetObjectWhereExpressionContains(tb, enreplacedyType, getlistF.Item1.Columns[0].CsName, qv));
											continue;
										case TableRefType.OneToOne:
											continue;
										case TableRefType.ManyToMany:
											if (true) {
												var midType = getlistF.Item1.RefMiddleEnreplacedyType;
												var midTb = fsql.CodeFirst.GetTableByEnreplacedy(midType);
												var midISelect = typeof(ISelect<>).MakeGenericType(midType);

												var funcType = typeof(Func<,>).MakeGenericType(typeof(object), typeof(bool));
												var expParam = Expression.Parameter(typeof(object), "a");
												var midParam = Expression.Parameter(midType, "mdtp");

												var anyMethod = midISelect.GetMethod("Any");
												var selectExp = qv.Select(c => Expression.Convert(Expression.Constant(FreeSql.Internal.Utils.GetDataReaderValue(getlistF.Item1.MiddleColumns[1].CsType, c)), getlistF.Item1.MiddleColumns[1].CsType)).ToArray();
												var expLambad = Expression.Lambda<Func<object, bool>>(
													Expression.Call(
														Expression.Call(
															Expression.Call(
																Expression.Constant(fsql),
																typeof(IFreeSql).GetMethod("Select", new Type[0]).MakeGenericMethod(midType)
															),
															midISelect.GetMethod("Where", new[] { typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(midType, typeof(bool))) }),
															Expression.Lambda(
																typeof(Func<,>).MakeGenericType(midType, typeof(bool)),
																Expression.AndAlso(
																	Expression.Equal(
																		Expression.MakeMemberAccess(Expression.TypeAs(expParam, enreplacedyType), tb.Properties[getlistF.Item1.Columns[0].CsName]),
																		Expression.MakeMemberAccess(midParam, midTb.Properties[getlistF.Item1.MiddleColumns[0].CsName])
																	),
																	Expression.Call(
																		Utils.GetLinqContains(getlistF.Item1.MiddleColumns[1].CsType),
																		Expression.NewArrayInit(
																			getlistF.Item1.MiddleColumns[1].CsType,
																			selectExp
																		),
																		Expression.MakeMemberAccess(midParam, midTb.Properties[getlistF.Item1.MiddleColumns[1].CsName])
																	)
																),
																midParam
															)
														),
														anyMethod,
														Expression.Default(anyMethod.GetParameters().FirstOrDefault().ParameterType)
													),
													expParam);

												getselect.Where(expLambad);
											}
											continue;
									}
								}
							}

							var getlistTotal = await getselect.CountAsync();
							var getlist = await getselect.Page(getpage, getlimit).ToListAsync();
							var gethashlists = new Dictionary<string, object>[getlist.Count];
							var gethashlistsIndex = 0;
							foreach (var getlisreplacedem in getlist) {
								var gethashlist = new Dictionary<string, object>();
								foreach (var getcol in tb.ColumnsByCs) {
									gethashlist.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(getlisreplacedem));
								}
								gethashlists[gethashlistsIndex++] = gethashlist;
							}

							var options = new Dictionary<string, object>();
							options["tb"] = tb;
							options["getlist"] = gethashlists;
							options["getlistTotal"] = getlistTotal;
							options["getlistFilter"] = getlistFilter;
							var str = _tpl.Value.RenderFile($"{enreplacedyName}-list.html", options);
							await res.WriteAsync(str);
						}
						return true;
					case "add":
					case "edit":
						//编辑页
						object gereplacedem = null;
						Dictionary<string, object> gethash = null;
						if (req.Query.Any()) {
							gereplacedem = Activator.CreateInstance(enreplacedyType);
							foreach (var getpk in tb.Primarys) {
								var reqv = req.Query[getpk.CsName].ToArray();
								if (reqv.Any())
									fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getpk.CsName, reqv.Length == 1 ? (object)reqv.FirstOrDefault() : reqv);
							}
							gereplacedem = await fsql.Select<object>().AsType(enreplacedyType).WhereDynamic(gereplacedem).FirstAsync();
							if (gereplacedem != null) {
								gethash = new Dictionary<string, object>();
								foreach (var getcol in tb.ColumnsByCs) {
									gethash.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(gereplacedem));
								}
							}
						}

						if (req.Method.ToLower() == "get") {
							MakeTemplateFile($"{enreplacedyName}-edit.html", Views.Edit);

							//ManyToOne/OneToOne
							var getlistFilter = new Dictionary<string, (TableRef, string, string, Dictionary<string, object>, List<Dictionary<string, object>>)>();
							var getlistManyed = new Dictionary<string, IEnumerable<string>>();
							foreach (var prop in tb.Properties) {
								if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
								var tbref = tb.GetTableRef(prop.Key, false);
								if (tbref == null) continue;
								switch (tbref.RefType) {
									case TableRefType.OneToMany: continue;
									case TableRefType.ManyToOne:
										getlistFilter.Add(prop.Key, await Utils.GetTableRefData(fsql, tbref));
										continue;
									case TableRefType.OneToOne:
										continue;
									case TableRefType.ManyToMany:
										getlistFilter.Add(prop.Key, await Utils.GetTableRefData(fsql, tbref));

										if (gereplacedem != null) {
											var midType = tbref.RefMiddleEnreplacedyType;
											var midTb = fsql.CodeFirst.GetTableByEnreplacedy(midType);
											var manyed = await fsql.Select<object>().AsType(midType)
												.Where(Utils.GetObjectWhereExpression(midTb, midType, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]))
												.ToListAsync();
											getlistManyed.Add(prop.Key, manyed.Select(a => fsql.GetEnreplacedyValueWithPropertyName(midType, a, tbref.MiddleColumns[1].CsName).ToString()));
										}
										continue;
								}
							}

							var options = new Dictionary<string, object>();
							options["tb"] = tb;
							options["gethash"] = gethash;
							options["getlistFilter"] = getlistFilter;
							options["getlistManyed"] = getlistManyed;
							options["postaction"] = $"{requestPathBase}restful-api/{enreplacedyName}";
							var str = _tpl.Value.RenderFile($"{enreplacedyName}-edit.html", options);
							await res.WriteAsync(str);

						} else {
							if (gereplacedem == null) {
								gereplacedem = Activator.CreateInstance(enreplacedyType);
								foreach(var getcol in tb.Columns.Values) {
									if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "create_time", "createtime" }.Contains(getcol.CsName.ToLower()))
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, DateTime.Now);
								}
							}
							var manySave = new List<(TableRef, object[], List<object>)>();
							if (req.Form.Any()) {
								foreach(var getcol in tb.Columns.Values) {
									if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "update_time", "updatetime" }.Contains(getcol.CsName.ToLower()))
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, DateTime.Now);

									var reqv = req.Form[getcol.CsName].ToArray();
									if (reqv.Any())
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, reqv.Length == 1 ? (object)reqv.FirstOrDefault() : reqv);
								}
								//ManyToMany
								foreach (var prop in tb.Properties) {
									if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
									var tbref = tb.GetTableRef(prop.Key, false);
									if (tbref == null) continue;
									switch (tbref.RefType) {
										case TableRefType.OneToMany: continue;
										case TableRefType.ManyToOne:
											continue;
										case TableRefType.OneToOne:
											continue;
										case TableRefType.ManyToMany:
											var midType = tbref.RefMiddleEnreplacedyType;
											var mtb = fsql.CodeFirst.GetTableByEnreplacedy(midType);

											var reqv = req.Form[$"mn_{prop.Key}"].ToArray();
											var reqvIndex = 0;
											var manyVals = new object[reqv.Length];
											foreach (var rv in reqv) {
												var miditem = Activator.CreateInstance(midType);
												foreach (var getcol in tb.Columns.Values) {
													if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "create_time", "createtime" }.Contains(getcol.CsName.ToLower()))
														fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, getcol.CsName, DateTime.Now);

													if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "update_time", "updatetime" }.Contains(getcol.CsName.ToLower()))
														fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, getcol.CsName, DateTime.Now);
												}
												//fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]);
												fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, tbref.MiddleColumns[1].CsName, rv);
												manyVals[reqvIndex++] = miditem;
											}
											var molds = await fsql.Select<object>().AsType(midType).Where(Utils.GetObjectWhereExpression(mtb, midType, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0])).ToListAsync();
											manySave.Add((tbref, manyVals, molds));
											continue;
									}
								}
							}


							using (var db = fsql.CreateDbContext()) {

								var dbset = db.Set<object>();
								dbset.AsType(enreplacedyType);

								await dbset.AddOrUpdateAsync(gereplacedem);

								foreach (var ms in manySave) {
									var midType = ms.Item1.RefMiddleEnreplacedyType;
									var moldsDic = ms.Item3.ToDictionary(a => fsql.GetEnreplacedyKeyString(midType, a, true));

									var manyset = db.Set<object>();
									manyset.AsType(midType);
									
									foreach (var msVal in ms.Item2) {
										fsql.SetEnreplacedyValueWithPropertyName(midType, msVal, ms.Item1.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]);
										await manyset.AddOrUpdateAsync(msVal);
										moldsDic.Remove(fsql.GetEnreplacedyKeyString(midType, msVal, true));
									}
									manyset.RemoveRange(moldsDic.Values);
								}

								await db.SaveChangesAsync();
							}
							gethash = new Dictionary<string, object>();
							foreach (var getcol in tb.ColumnsByCs) {
								gethash.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(gereplacedem));
							}

							await Utils.Jsonp(context, new { code = 0, success = true, message = "Success", data = gethash });
						}
						return true;
					case "del":
						if (req.Method.ToLower() == "post") {

							var delitems = new List<object>();
							var reqv = new List<string[]>();
							foreach(var delpk in tb.Primarys) {
								var reqvs = req.Form[delpk.CsName].ToArray();
								if (reqv.Count > 0 && reqvs.Length != reqv[0].Length) throw new Exception("删除失败,联合主键参数传递不对等");
								reqv.Add(reqvs);
							}
							if (reqv[0].Length == 0) return true;

							using (var ctx = fsql.CreateDbContext()) {
								var dbset = ctx.Set<object>();
								dbset.AsType(enreplacedyType);

								for (var a = 0; a < reqv[0].Length; a++) {
									object delitem = Activator.CreateInstance(enreplacedyType);
									var delpkindex = 0;
									foreach (var delpk in tb.Primarys)
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, delitem, delpk.CsName, reqv[delpkindex++][a]);
									dbset.Remove(delitem);
								}
								await ctx.SaveChangesAsync();
							}

							await Utils.Jsonp(context, new { code = 0, success = true, message = "Success" });
							return true;
						}
						break;
				}
			}
			return false;
		}

19 View Source File : RepositoryDbContext.cs
License : MIT License
Project Creator : 2881099

public override IDbSet Set(Type enreplacedyType) {
			if (_dicSet.ContainsKey(enreplacedyType)) return _dicSet[enreplacedyType];

			var tb = _orm.CodeFirst.GetTableByEnreplacedy(enreplacedyType);
			if (tb == null) return null;

			object repos = _repos;
			if (enreplacedyType != _repos.EnreplacedyType) {
				repos = Activator.CreateInstance(typeof(DefaultRepository<,>).MakeGenericType(enreplacedyType, typeof(int)), _repos.Orm);
				(repos as IBaseRepository).UnitOfWork = _repos.UnitOfWork;
				GetRepositoryDbField(enreplacedyType).SetValue(repos, this);

				typeof(RepositoryDbContext).GetMethod("SetRepositoryDataFilter").MakeGenericMethod(_repos.EnreplacedyType)
					.Invoke(null, new object[] { repos, _repos });
			}

			var sd = Activator.CreateInstance(typeof(RepositoryDbSet<>).MakeGenericType(enreplacedyType), repos) as IDbSet;
			if (enreplacedyType != typeof(object)) _dicSet.Add(enreplacedyType, sd);
			return sd;
		}

19 View Source File : ICollectionResolver.cs
License : MIT License
Project Creator : 1996v

public static TypeInfo BuildICollectionImplementationType(DynamicFormatterreplacedembly replacedembly, Type type, ConstructorInfo constructor,
                     Type itemType,
                     bool isImplGenerIList, bool IsImplIList, bool isImplGenerICollec, bool isImplIReadOnlyList)
        {
            TypeBuilder typeBuilder = replacedembly.DefineFormatterType(type);

            MethodBuilder sizeMethod = TypeBuildHelper.DefineSizeMethod(typeBuilder, type);
            MethodBuilder serializeMethod = TypeBuildHelper.DefineSerializeMethod(typeBuilder, type);
            if (itemType == typeof(object))
            {
                //itemType is Object, Array2
                if (IsImplIList)
                {
                    TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeIList), BindingFlags.Public | BindingFlags.Static));
                }
                else
                {
                    TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeIEnumerable), BindingFlags.Public | BindingFlags.Static));
                }

                TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SizeIEnumerable), BindingFlags.Public | BindingFlags.Static));
            }
            else
            {
                if (Array1FormatterHelper.IsArray1Type(itemType))
                {
                    //Array1
                    TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array1FormatterHelper).GetMethod(nameof(Array1FormatterHelper.SerializeIEnumerable), new Type[] { typeof(BssomWriter).MakeByRefType(), typeof(BssomSerializeContext).MakeByRefType(), typeof(IEnumerable<>).MakeGenericType(itemType) }));

                    TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array1FormatterHelper).GetMethod(nameof(Array1FormatterHelper.SizeIEnumerable), new Type[] { typeof(BssomSizeContext).MakeByRefType(), typeof(IEnumerable<>).MakeGenericType(itemType) }));
                }
                else
                {
                    if (isImplGenerIList || isImplIReadOnlyList)
                    {
                        TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeGenerIList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(itemType));
                    }
                    else
                    {
                        TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeGenericIEnumerable), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(itemType));
                    }

                    TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SizeGenericIEnumerable), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(itemType));
                }
            }

            MethodBuilder deserializeMethod = TypeBuildHelper.DefineDeserializeMethod(typeBuilder, type);
            ParameterInfo[] args = constructor.GetParameters();
            if (args.Length == 1 && args[0].ParameterType != typeof(int))
            {
                //new T(IEnumerable t)
                Type dynamicCacheType = typeof(CollectionDynamicDelegateCache<>).MakeGenericType(type);
                MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(CollectionDynamicDelegateCache<int>.GenerateInjectCtor));
                methodinfo.Invoke(null, new object[] { constructor, args[0].ParameterType });
                TypeBuildHelper.CallDeserializeDelegate(deserializeMethod, type, dynamicCacheType.GetField(nameof(CollectionDynamicDelegateCache<int>.Deserialize), BindingFlags.Public | BindingFlags.Static));
            }
            else
            {
                if (itemType == typeof(DateTime))//DateTime需要特殊处理,因为要处理Standrand和Native
                {
                    Type dtCollBuilder = typeof(DateTimeCollectionDeserializeBuilder<>).MakeGenericType(type);
                    MethodInfo methodinfo = dtCollBuilder.GetMethod(nameof(DateTimeCollectionDeserializeBuilder<ICollection<DateTime>>.ConstructorInit));
                    methodinfo.Invoke(null, new object[] { constructor });

                    TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, dtCollBuilder.GetMethod(nameof(DateTimeCollectionDeserializeBuilder<ICollection<DateTime>>.Deserialize)));
                }
                else
                {
                    Type dynamicCacheType = typeof(CollectionDynamicDelegateCache<>).MakeGenericType(type);
                    if (args.Length == 0)
                    {
                        MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(CollectionDynamicDelegateCache<int>.GenerateDeserializeWithEmptyCtor));
                        methodinfo.Invoke(null, new object[] { constructor, isImplGenerICollec, itemType });
                    }
                    else
                    {
                        DEBUG.replacedert(args.Length == 1 && args[0].ParameterType == typeof(int));

                        MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(CollectionDynamicDelegateCache<int>.GenerateDeserializeWithCapacityCtor));
                        methodinfo.Invoke(null, new object[] { constructor, isImplGenerICollec, itemType });
                    }
                    TypeBuildHelper.CallDeserializeDelegate(deserializeMethod, type, dynamicCacheType.GetField(nameof(CollectionDynamicDelegateCache<int>.Deserialize), BindingFlags.Public | BindingFlags.Static));
                }
            }
            return typeBuilder.CreateTypeInfo();
        }

19 View Source File : ListDecorator.cs
License : MIT License
Project Creator : 404Lcc

internal static MethodInfo GetEnumeratorInfo(TypeModel model, Type expectedType, Type itemType, out MethodInfo moveNext, out MethodInfo current)
        {

#if WINRT || COREFX
            TypeInfo enumeratorType = null, iteratorType;
#else
            Type enumeratorType = null, iteratorType;
#endif

            // try a custom enumerator
            MethodInfo getEnumerator = Helpers.GetInstanceMethod(expectedType, "GetEnumerator", null);

            Type getReturnType = null;
            if (getEnumerator != null)
            {
                getReturnType = getEnumerator.ReturnType;
                iteratorType = getReturnType
#if WINRT || COREFX || COREFX
                    .GetTypeInfo()
#endif
                    ;
                moveNext = Helpers.GetInstanceMethod(iteratorType, "MoveNext", null);
                PropertyInfo prop = Helpers.GetProperty(iteratorType, "Current", false);
                current = prop == null ? null : Helpers.GetGetMethod(prop, false, false);
#if PROFILE259
				if (moveNext == null && (model.MapType(ienumeratorType).GetTypeInfo().IsreplacedignableFrom(iteratorType.GetTypeInfo())))
#else
				if (moveNext == null && (model.MapType(ienumeratorType).IsreplacedignableFrom(iteratorType)))
#endif
				{
					moveNext = Helpers.GetInstanceMethod(model.MapType(ienumeratorType), "MoveNext", null);
                }
                // fully typed
                if (moveNext != null && moveNext.ReturnType == model.MapType(typeof(bool))
                    && current != null && current.ReturnType == itemType)
                {
                    return getEnumerator;
                }
                moveNext = current = getEnumerator = null;
            }
            
#if !NO_GENERICS
            // try IEnumerable<T>
            Type tmp = model.MapType(typeof(System.Collections.Generic.IEnumerable<>), false);
            
            if (tmp != null)
            {
                tmp = tmp.MakeGenericType(itemType);

#if WINRT || COREFX
                enumeratorType = tmp.GetTypeInfo();
#else
                enumeratorType = tmp;
#endif
            }
;
#if PROFILE259
			if (enumeratorType != null && enumeratorType.GetTypeInfo().IsreplacedignableFrom(expectedType
#else
			if (enumeratorType != null && enumeratorType.IsreplacedignableFrom(expectedType
#endif
#if WINRT || COREFX || PROFILE259
                .GetTypeInfo()
#endif
				))
            {
                getEnumerator = Helpers.GetInstanceMethod(enumeratorType, "GetEnumerator");
                getReturnType = getEnumerator.ReturnType;

#if WINRT || COREFX
                iteratorType = getReturnType.GetTypeInfo();
#else
                iteratorType = getReturnType;
#endif

                moveNext = Helpers.GetInstanceMethod(model.MapType(ienumeratorType), "MoveNext");
                current = Helpers.GetGetMethod(Helpers.GetProperty(iteratorType, "Current", false), false, false);
                return getEnumerator;
            }
#endif
			// give up and fall-back to non-generic IEnumerable
			enumeratorType = model.MapType(ienumerableType);
            getEnumerator = Helpers.GetInstanceMethod(enumeratorType, "GetEnumerator");
            getReturnType = getEnumerator.ReturnType;
            iteratorType = getReturnType
#if WINRT || COREFX
                .GetTypeInfo()
#endif
                ;
            moveNext = Helpers.GetInstanceMethod(iteratorType, "MoveNext");
            current = Helpers.GetGetMethod(Helpers.GetProperty(iteratorType,"Current", false), false, false);
            return getEnumerator;
        }

19 View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v

public static Expression Call_SerializeContextOptionResolver_GetFormatterWithVerify_Serialize(Expression value)
        {
            return Expression.Call(Call_GetFormatterWithVerify(SerializeContextOptionResolver, value.Type), typeof(IBssomFormatter<>).MakeGenericType(value.Type).GetMethod(nameof(IBssomFormatter<int>.Serialize)), Par_Writer, Par_SerializeContext, value);
        }

19 View Source File : QueryClause.cs
License : MIT License
Project Creator : 71

internal static Type EnumerableType(Type type) => typeof(IEnumerable<>).MakeGenericType(type);

19 View Source File : IDictionaryResolver.cs
License : MIT License
Project Creator : 1996v

public static TypeInfo BuildIDictionaryImplementationType(DynamicFormatterreplacedembly replacedembly, ConstructorInfo constructor, Type type)
        {
            TypeBuilder typeBuilder = replacedembly.DefineFormatterType(type);

            MethodBuilder serializeMethod = TypeBuildHelper.DefineSerializeMethod(typeBuilder, type);
            TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.SerializeIDictionary), BindingFlags.Public | BindingFlags.Static));

            MethodBuilder deserializeMethod = TypeBuildHelper.DefineDeserializeMethod(typeBuilder, type);
            ParameterInfo[] args = constructor.GetParameters();
            Type dynamicCacheType = typeof(IDictionaryDynamicDelegateCache<>).MakeGenericType(type);

            if (args.Length == 1)
            {
                DEBUG.replacedert(args[0].ParameterType == typeof(IDictionary));

                //return new T(IDictionaryFormatter.Deserialize)
                MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(IDictionaryDynamicDelegateCache<int>.GenerateInjectCtor));
                methodinfo.Invoke(null, new object[] { constructor, args[0].ParameterType });
            }
            else
            {
                MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(IDictionaryDynamicDelegateCache<int>.GenerateDeserializeWithIDictionaryEmptyCtor));
                methodinfo.Invoke(null, new object[] { });
            }
            TypeBuildHelper.CallDeserializeDelegate(deserializeMethod, type, dynamicCacheType.GetField(nameof(IDictionaryDynamicDelegateCache<int>.Deserialize), BindingFlags.Public | BindingFlags.Static));

            MethodBuilder sizeMethod = TypeBuildHelper.DefineSizeMethod(typeBuilder, type);
            TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.SizeIDictionary), BindingFlags.Public | BindingFlags.Static));

            return typeBuilder.CreateTypeInfo();
        }

19 View Source File : FdbTuplePackers.cs
License : MIT License
Project Creator : abdullin

private static Delegate GetSerializerFor([NotNull] Type type)
		{
			if (type == null) throw new ArgumentNullException("type");

			if (type == typeof(object))
			{ // return a generic serializer that will inspect the runtime type of the object
				return new Encoder<object>(FdbTuplePackers.SerializeObjectTo);
			}

			var typeArgs = new[] { typeof(TupleWriter).MakeByRefType(), type };
			var method = typeof(FdbTuplePackers).GetMethod("SerializeTo", BindingFlags.Static | BindingFlags.Public, null, typeArgs, null);
			if (method != null)
			{ // we have a direct serializer
				return method.CreateDelegate(typeof(Encoder<>).MakeGenericType(type));
			}

			// maybe if it is a tuple ?
			if (typeof(IFdbTuple).IsreplacedignableFrom(type))
			{
				method = typeof(FdbTuplePackers).GetMethod("SerializeTupleTo", BindingFlags.Static | BindingFlags.Public);
				if (method != null)
				{
					return method.MakeGenericMethod(type).CreateDelegate(typeof(Encoder<>).MakeGenericType(type));
				}
			}

			if (typeof(ITupleFormattable).IsreplacedignableFrom(type))
			{
				method = typeof(FdbTuplePackers).GetMethod("SerializeFormattableTo", BindingFlags.Static | BindingFlags.Public);
				if (method != null)
				{
					return method.CreateDelegate(typeof(Encoder<>).MakeGenericType(type));
				}
			}

			if (typeof(IFdbKey).IsreplacedignableFrom(type))
			{
				method = typeof(FdbTuplePackers).GetMethod("SerializeFdbKeyTo", BindingFlags.Static | BindingFlags.Public);
				if (method != null)
				{
					return method.CreateDelegate(typeof(Encoder<>).MakeGenericType(type));
				}
			}

			var nullableType = Nullable.GetUnderlyingType(type);
			if (nullableType != null)
			{ // nullable types can reuse the underlying type serializer
				method = typeof(FdbTuplePackers).GetMethod("SerializeNullableTo", BindingFlags.Static | BindingFlags.Public);
				if (method != null)
				{
					return method.MakeGenericMethod(nullableType).CreateDelegate(typeof(Encoder<>).MakeGenericType(type));
				}
			}

			// TODO: look for a static SerializeTo(BWB, T) method on the type itself ?

			// no luck..
			return null;
		}

19 View Source File : ObjectFormatter.cs
License : MIT License
Project Creator : 1996v

public void Serialize(ref BssomWriter writer, ref BssomSerializeContext context, object value)
        {
            if (value == null)
            {
                writer.WriteNull();
                return;
            }

            Type realType = value.GetType();
            if (realType == typeof(object))
            {
                writer.WriteArray1BuildInType(BssomType.Map2);
                BssMapObjMarshal.WriteEmptyMapObject(ref writer);
                return;
            }

            object formatter = context.Option.FormatterResolver.GetFormatterWithVerify(realType);

            if (!SerializerDelegates.TryGetValue(realType, out SerializeMethod serializerDelegate))
            {
                Type formatterType = typeof(IBssomFormatter<>).MakeGenericType(realType);
                ParameterExpression param0 = Expression.Parameter(typeof(object), "formatter");
                ParameterExpression param1 = Expression.Parameter(typeof(BssomWriter).MakeByRefType(), "writer");
                ParameterExpression param2 = Expression.Parameter(typeof(BssomSerializeContext).MakeByRefType(), "context");
                ParameterExpression param3 = Expression.Parameter(typeof(object), "value");

                MethodInfo serializeMethod = formatterType.GetRuntimeMethod(nameof(Serialize), new[] { typeof(BssomWriter).MakeByRefType(), typeof(BssomSerializeContext).MakeByRefType(), realType });

                MethodCallExpression body = Expression.Call(
                    Expression.Convert(param0, formatterType),
                    serializeMethod,
                    param1, param2,
                    realType.IsValueType ? Expression.Unbox(param3, realType) : Expression.Convert(param3, realType)
                    );

                serializerDelegate = Expression.Lambda<SerializeMethod>(body, param0, param1, param2, param3).Compile();
                SerializerDelegates.TryAdd(realType, serializerDelegate);
            }

            serializerDelegate(formatter, ref writer, ref context, value);

        }

19 View Source File : Serializer.cs
License : GNU General Public License v3.0
Project Creator : Adam-Wilkinson

public object TrySerializeObject(object toSerialize)
        {
            if (Serializers.TryGetValue(toSerialize.GetType(), out object serializer))
            {
                return typeof(IObjectSerializer<>).MakeGenericType(toSerialize.GetType()).GetMethod(nameof(IObjectSerializer<object>.Serialize)).Invoke(serializer, new object[] { toSerialize, this });
            }

            return toSerialize;
        }

19 View Source File : Admin.cs
License : MIT License
Project Creator : 2881099

async public static Task<bool> Use(HttpContext context, IFreeSql fsql, string requestPathBase, Dictionary<string, Type> dicEnreplacedyTypes) {
			HttpRequest req = context.Request;
			HttpResponse res = context.Response;

			var remUrl = req.Path.ToString().Substring(requestPathBase.Length).Trim(' ', '/').Split('/');
			var enreplacedyName = remUrl.FirstOrDefault();

			if (!string.IsNullOrEmpty(enreplacedyName)) {

				if (dicEnreplacedyTypes.TryGetValue(enreplacedyName, out var enreplacedyType) == false) throw new Exception($"UseFreeAdminLtePreview 错误,找不到实体类型:{enreplacedyName}");

				var tb = fsql.CodeFirst.GetTableByEnreplacedy(enreplacedyType);
				if (tb == null) throw new Exception($"UseFreeAdminLtePreview 错误,实体类型无法映射:{enreplacedyType.FullName}");

				var tpl = _tpl.Value;

				switch (remUrl.ElementAtOrDefault(1)?.ToLower()) {
					case null:
						//首页
						if (true) {
							MakeTemplateFile($"{enreplacedyName}-list.html", Views.List);

							//ManyToOne/OneToOne
							var getlistFilter = new List<(TableRef, string, string, Dictionary<string, object>, List<Dictionary<string, object>>)>();
							foreach (var prop in tb.Properties) {
								if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
								var tbref = tb.GetTableRef(prop.Key, false);
								if (tbref == null) continue;
								switch (tbref.RefType) {
									case TableRefType.OneToMany: continue;
									case TableRefType.ManyToOne:
										getlistFilter.Add(await Utils.GetTableRefData(fsql, tbref));
										continue;
									case TableRefType.OneToOne:
										continue;
									case TableRefType.ManyToMany:
										getlistFilter.Add(await Utils.GetTableRefData(fsql, tbref));
										continue;
								}
							}

							int.TryParse(req.Query["page"].FirstOrDefault(), out var getpage);
							int.TryParse(req.Query["limit"].FirstOrDefault(), out var getlimit);
							if (getpage <= 0) getpage = 1;
							if (getlimit <= 0) getlimit = 20;

							var getselect = fsql.Select<object>().AsType(enreplacedyType);
							foreach (var getlistF in getlistFilter) {
								var qv = req.Query[getlistF.Item3].ToArray();
								if (qv.Any()) {
									switch (getlistF.Item1.RefType) {
										case TableRefType.OneToMany: continue;
										case TableRefType.ManyToOne:
											getselect.Where(Utils.GetObjectWhereExpressionContains(tb, enreplacedyType, getlistF.Item1.Columns[0].CsName, qv));
											continue;
										case TableRefType.OneToOne:
											continue;
										case TableRefType.ManyToMany:
											if (true) {
												var midType = getlistF.Item1.RefMiddleEnreplacedyType;
												var midTb = fsql.CodeFirst.GetTableByEnreplacedy(midType);
												var midISelect = typeof(ISelect<>).MakeGenericType(midType);

												var funcType = typeof(Func<,>).MakeGenericType(typeof(object), typeof(bool));
												var expParam = Expression.Parameter(typeof(object), "a");
												var midParam = Expression.Parameter(midType, "mdtp");

												var anyMethod = midISelect.GetMethod("Any");
												var selectExp = qv.Select(c => Expression.Convert(Expression.Constant(FreeSql.Internal.Utils.GetDataReaderValue(getlistF.Item1.MiddleColumns[1].CsType, c)), getlistF.Item1.MiddleColumns[1].CsType)).ToArray();
												var expLambad = Expression.Lambda<Func<object, bool>>(
													Expression.Call(
														Expression.Call(
															Expression.Call(
																Expression.Constant(fsql),
																typeof(IFreeSql).GetMethod("Select", new Type[0]).MakeGenericMethod(midType)
															),
															midISelect.GetMethod("Where", new[] { typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(midType, typeof(bool))) }),
															Expression.Lambda(
																typeof(Func<,>).MakeGenericType(midType, typeof(bool)),
																Expression.AndAlso(
																	Expression.Equal(
																		Expression.MakeMemberAccess(Expression.TypeAs(expParam, enreplacedyType), tb.Properties[getlistF.Item1.Columns[0].CsName]),
																		Expression.MakeMemberAccess(midParam, midTb.Properties[getlistF.Item1.MiddleColumns[0].CsName])
																	),
																	Expression.Call(
																		Utils.GetLinqContains(getlistF.Item1.MiddleColumns[1].CsType),
																		Expression.NewArrayInit(
																			getlistF.Item1.MiddleColumns[1].CsType,
																			selectExp
																		),
																		Expression.MakeMemberAccess(midParam, midTb.Properties[getlistF.Item1.MiddleColumns[1].CsName])
																	)
																),
																midParam
															)
														),
														anyMethod,
														Expression.Default(anyMethod.GetParameters().FirstOrDefault().ParameterType)
													),
													expParam);

												getselect.Where(expLambad);
											}
											continue;
									}
								}
							}

							var getlistTotal = await getselect.CountAsync();
							var getlist = await getselect.Page(getpage, getlimit).ToListAsync();
							var gethashlists = new Dictionary<string, object>[getlist.Count];
							var gethashlistsIndex = 0;
							foreach (var getlisreplacedem in getlist) {
								var gethashlist = new Dictionary<string, object>();
								foreach (var getcol in tb.ColumnsByCs) {
									gethashlist.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(getlisreplacedem));
								}
								gethashlists[gethashlistsIndex++] = gethashlist;
							}

							var options = new Dictionary<string, object>();
							options["tb"] = tb;
							options["getlist"] = gethashlists;
							options["getlistTotal"] = getlistTotal;
							options["getlistFilter"] = getlistFilter;
							var str = _tpl.Value.RenderFile($"{enreplacedyName}-list.html", options);
							await res.WriteAsync(str);
						}
						return true;
					case "add":
					case "edit":
						//编辑页
						object gereplacedem = null;
						Dictionary<string, object> gethash = null;
						if (req.Query.Any()) {
							gereplacedem = Activator.CreateInstance(enreplacedyType);
							foreach (var getpk in tb.Primarys) {
								var reqv = req.Query[getpk.CsName].ToArray();
								if (reqv.Any())
									fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getpk.CsName, reqv.Length == 1 ? (object)reqv.FirstOrDefault() : reqv);
							}
							gereplacedem = await fsql.Select<object>().AsType(enreplacedyType).WhereDynamic(gereplacedem).FirstAsync();
							if (gereplacedem != null) {
								gethash = new Dictionary<string, object>();
								foreach (var getcol in tb.ColumnsByCs) {
									gethash.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(gereplacedem));
								}
							}
						}

						if (req.Method.ToLower() == "get") {
							MakeTemplateFile($"{enreplacedyName}-edit.html", Views.Edit);

							//ManyToOne/OneToOne
							var getlistFilter = new Dictionary<string, (TableRef, string, string, Dictionary<string, object>, List<Dictionary<string, object>>)>();
							var getlistManyed = new Dictionary<string, IEnumerable<string>>();
							foreach (var prop in tb.Properties) {
								if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
								var tbref = tb.GetTableRef(prop.Key, false);
								if (tbref == null) continue;
								switch (tbref.RefType) {
									case TableRefType.OneToMany: continue;
									case TableRefType.ManyToOne:
										getlistFilter.Add(prop.Key, await Utils.GetTableRefData(fsql, tbref));
										continue;
									case TableRefType.OneToOne:
										continue;
									case TableRefType.ManyToMany:
										getlistFilter.Add(prop.Key, await Utils.GetTableRefData(fsql, tbref));

										if (gereplacedem != null) {
											var midType = tbref.RefMiddleEnreplacedyType;
											var midTb = fsql.CodeFirst.GetTableByEnreplacedy(midType);
											var manyed = await fsql.Select<object>().AsType(midType)
												.Where(Utils.GetObjectWhereExpression(midTb, midType, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]))
												.ToListAsync();
											getlistManyed.Add(prop.Key, manyed.Select(a => fsql.GetEnreplacedyValueWithPropertyName(midType, a, tbref.MiddleColumns[1].CsName).ToString()));
										}
										continue;
								}
							}

							var options = new Dictionary<string, object>();
							options["tb"] = tb;
							options["gethash"] = gethash;
							options["getlistFilter"] = getlistFilter;
							options["getlistManyed"] = getlistManyed;
							options["postaction"] = $"{requestPathBase}restful-api/{enreplacedyName}";
							var str = _tpl.Value.RenderFile($"{enreplacedyName}-edit.html", options);
							await res.WriteAsync(str);

						} else {
							if (gereplacedem == null) {
								gereplacedem = Activator.CreateInstance(enreplacedyType);
								foreach(var getcol in tb.Columns.Values) {
									if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "create_time", "createtime" }.Contains(getcol.CsName.ToLower()))
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, DateTime.Now);
								}
							}
							var manySave = new List<(TableRef, object[], List<object>)>();
							if (req.Form.Any()) {
								foreach(var getcol in tb.Columns.Values) {
									if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "update_time", "updatetime" }.Contains(getcol.CsName.ToLower()))
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, DateTime.Now);

									var reqv = req.Form[getcol.CsName].ToArray();
									if (reqv.Any())
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, reqv.Length == 1 ? (object)reqv.FirstOrDefault() : reqv);
								}
								//ManyToMany
								foreach (var prop in tb.Properties) {
									if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
									var tbref = tb.GetTableRef(prop.Key, false);
									if (tbref == null) continue;
									switch (tbref.RefType) {
										case TableRefType.OneToMany: continue;
										case TableRefType.ManyToOne:
											continue;
										case TableRefType.OneToOne:
											continue;
										case TableRefType.ManyToMany:
											var midType = tbref.RefMiddleEnreplacedyType;
											var mtb = fsql.CodeFirst.GetTableByEnreplacedy(midType);

											var reqv = req.Form[$"mn_{prop.Key}"].ToArray();
											var reqvIndex = 0;
											var manyVals = new object[reqv.Length];
											foreach (var rv in reqv) {
												var miditem = Activator.CreateInstance(midType);
												foreach (var getcol in tb.Columns.Values) {
													if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "create_time", "createtime" }.Contains(getcol.CsName.ToLower()))
														fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, getcol.CsName, DateTime.Now);

													if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "update_time", "updatetime" }.Contains(getcol.CsName.ToLower()))
														fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, getcol.CsName, DateTime.Now);
												}
												//fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]);
												fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, tbref.MiddleColumns[1].CsName, rv);
												manyVals[reqvIndex++] = miditem;
											}
											var molds = await fsql.Select<object>().AsType(midType).Where(Utils.GetObjectWhereExpression(mtb, midType, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0])).ToListAsync();
											manySave.Add((tbref, manyVals, molds));
											continue;
									}
								}
							}


							using (var db = fsql.CreateDbContext()) {

								var dbset = db.Set<object>();
								dbset.AsType(enreplacedyType);

								await dbset.AddOrUpdateAsync(gereplacedem);

								foreach (var ms in manySave) {
									var midType = ms.Item1.RefMiddleEnreplacedyType;
									var moldsDic = ms.Item3.ToDictionary(a => fsql.GetEnreplacedyKeyString(midType, a, true));

									var manyset = db.Set<object>();
									manyset.AsType(midType);
									
									foreach (var msVal in ms.Item2) {
										fsql.SetEnreplacedyValueWithPropertyName(midType, msVal, ms.Item1.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]);
										await manyset.AddOrUpdateAsync(msVal);
										moldsDic.Remove(fsql.GetEnreplacedyKeyString(midType, msVal, true));
									}
									manyset.RemoveRange(moldsDic.Values);
								}

								await db.SaveChangesAsync();
							}
							gethash = new Dictionary<string, object>();
							foreach (var getcol in tb.ColumnsByCs) {
								gethash.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(gereplacedem));
							}

							await Utils.Jsonp(context, new { code = 0, success = true, message = "Success", data = gethash });
						}
						return true;
					case "del":
						if (req.Method.ToLower() == "post") {

							var delitems = new List<object>();
							var reqv = new List<string[]>();
							foreach(var delpk in tb.Primarys) {
								var reqvs = req.Form[delpk.CsName].ToArray();
								if (reqv.Count > 0 && reqvs.Length != reqv[0].Length) throw new Exception("删除失败,联合主键参数传递不对等");
								reqv.Add(reqvs);
							}
							if (reqv[0].Length == 0) return true;

							using (var ctx = fsql.CreateDbContext()) {
								var dbset = ctx.Set<object>();
								dbset.AsType(enreplacedyType);

								for (var a = 0; a < reqv[0].Length; a++) {
									object delitem = Activator.CreateInstance(enreplacedyType);
									var delpkindex = 0;
									foreach (var delpk in tb.Primarys)
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, delitem, delpk.CsName, reqv[delpkindex++][a]);
									dbset.Remove(delitem);
								}
								await ctx.SaveChangesAsync();
							}

							await Utils.Jsonp(context, new { code = 0, success = true, message = "Success" });
							return true;
						}
						break;
				}
			}
			return false;
		}

19 View Source File : TccMaster.cs
License : MIT License
Project Creator : 2881099

TccMaster<TDBKey> Then(Type tccUnitType, object state)
        {
            if (tccUnitType == null) throw new ArgumentNullException(nameof(tccUnitType));
            var unitTypeBase = typeof(TccUnit<>);
            if (state == null && tccUnitType.BaseType.GetGenericTypeDefinition() == typeof(TccUnit<>)) unitTypeBase = unitTypeBase.MakeGenericType(tccUnitType.BaseType.GetGenericArguments()[0]);
            else unitTypeBase = unitTypeBase.MakeGenericType(state.GetType());
            if (unitTypeBase.IsreplacedignableFrom(tccUnitType) == false) throw new ArgumentException($"{tccUnitType.DisplayCsharp(false)} 必须继承 {unitTypeBase.DisplayCsharp(false)}");
            var unitCtors = tccUnitType.GetConstructors();
            if (unitCtors.Length != 1 && unitCtors[0].GetParameters().Length > 0) throw new ArgumentException($"{tccUnitType.FullName} 不能使用构造函数");

            var unitTypeConved = Type.GetType(tccUnitType.replacedemblyQualifiedName);
            if (unitTypeConved == null) throw new ArgumentException($"{tccUnitType.FullName} 无效");
            var unit = unitTypeConved.CreateInstanceGetDefaultValue() as ITccUnit;
            (unit as ITccUnitSetter)?.SetState(state);
            _thenUnits.Add(unit);
            _thenUnitInfos.Add(new TccUnitInfo
            {
                Description = unitTypeConved.GetDescription(),
                Index = _thenUnitInfos.Count + 1,
                Stage = TccUnitStage.Try,
                State = state == null ? null : Newtonsoft.Json.JsonConvert.SerializeObject(state),
                StateTypeName = state?.GetType().replacedemblyQualifiedName,
                Tid = _tid,
                TypeName = tccUnitType.replacedemblyQualifiedName,
            });
            return this;
        }

19 View Source File : ObjectFormatter.cs
License : MIT License
Project Creator : 1996v

public int Size(ref BssomSizeContext context, object value)
        {
            if (value == null)
            {
                return BssomBinaryPrimitives.NullSize;
            }

            Type realType = value.GetType();
            if (realType == typeof(object))
            {
                return BssMapObjMarshal.Empty.Length + BssomBinaryPrimitives.BuildInTypeCodeSize;
            }

            object formatter = context.Option.FormatterResolver.GetFormatterWithVerify(realType);

            if (!SizeDelegates.TryGetValue(realType, out SizeMethod sizeDelegate))
            {
                Type formatterType = typeof(IBssomFormatter<>).MakeGenericType(realType);
                ParameterExpression param0 = Expression.Parameter(typeof(object), "formatter");
                ParameterExpression param1 = Expression.Parameter(typeof(BssomSizeContext).MakeByRefType(), "context");
                ParameterExpression param2 = Expression.Parameter(typeof(object), "value");

                MethodInfo sizeMethod = formatterType.GetRuntimeMethod(nameof(Size), new[] { typeof(BssomSizeContext).MakeByRefType(), realType });

                MethodCallExpression body = Expression.Call(
                    Expression.Convert(param0, formatterType),
                    sizeMethod, param1,
                    realType.IsValueType ? Expression.Unbox(param2, realType) : Expression.Convert(param2, realType)
                    );

                sizeDelegate = Expression.Lambda<SizeMethod>(body, param0, param1, param2).Compile();
                SizeDelegates.TryAdd(realType, sizeDelegate);
            }

            return sizeDelegate(formatter, ref context, value);
        }

19 View Source File : RepositoryDbContext.cs
License : MIT License
Project Creator : 2881099

static FieldInfo GetRepositoryDbField(Type type) => _dicGetRepositoryDbField.GetOrAdd(type, tp => typeof(BaseRepository<,>).MakeGenericType(tp, typeof(int)).GetField("_dbPriv", BindingFlags.Instance | BindingFlags.NonPublic));

19 View Source File : TypeBuildHelper.cs
License : MIT License
Project Creator : 1996v

public static void CallDeserializeDelegate(MethodBuilder deserializeMethod, Type genericType, FieldInfo fieldInfo)
        {
            ILGenerator il = deserializeMethod.GetILGenerator();
            il.Emit(OpCodes.Ldsfld, fieldInfo);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Ldarg_2);
            il.Emit(OpCodes.Call, typeof(Deserialize<>).MakeGenericType(genericType).GetMethod(nameof(Deserialize<int>.Invoke)));
            il.Emit(OpCodes.Ret);
        }

19 View Source File : DbContext.cs
License : MIT License
Project Creator : 2881099

public virtual IDbSet Set(Type enreplacedyType) {
			if (_dicSet.ContainsKey(enreplacedyType)) return _dicSet[enreplacedyType];
			var sd = Activator.CreateInstance(typeof(DbContextDbSet<>).MakeGenericType(enreplacedyType), this) as IDbSet;
			if (enreplacedyType != typeof(object)) _dicSet.Add(enreplacedyType, sd);
			return sd;
		}

19 View Source File : DataFilterUtil.cs
License : MIT License
Project Creator : 2881099

internal static void SetRepositoryDataFilter(object repos, Action<FluentDataFilter> scopedDataFilter) {
			if (scopedDataFilter != null) {
				SetRepositoryDataFilter(repos, null);
			}
			if (scopedDataFilter == null) {
				scopedDataFilter = _globalDataFilter;
			}
			if (scopedDataFilter == null) return;
			using (var globalFilter = new FluentDataFilter()) {
				scopedDataFilter(globalFilter);

				var type = repos.GetType();
				Type enreplacedyType = (repos as IBaseRepository).EnreplacedyType;
				if (enreplacedyType == null) throw new Exception("FreeSql.Repository 设置过滤器失败,原因是对象不属于 IRepository");

				var notExists = _dicSetRepositoryDataFilterConvertFilterNotExists.GetOrAdd(type, t => new ConcurrentDictionary<string, bool>());
				var newFilter = new Dictionary<string, LambdaExpression>();
				foreach (var gf in globalFilter._filters) {
					if (notExists.ContainsKey(gf.name)) continue;

					LambdaExpression newExp = null;
					var filterParameter1 = Expression.Parameter(enreplacedyType, gf.exp.Parameters[0].Name);
					try {
						newExp = Expression.Lambda(
							typeof(Func<,>).MakeGenericType(enreplacedyType, typeof(bool)),
							new ReplaceVisitor().Modify(gf.exp.Body, filterParameter1),
							filterParameter1
						);
					} catch {
						notExists.TryAdd(gf.name, true); //防止第二次错误
						continue;
					}
					newFilter.Add(gf.name, newExp);
				}
				if (newFilter.Any() == false) return;

				var del = _dicSetRepositoryDataFilterApplyDataFilterFunc.GetOrAdd(type, t => {
					var reposParameter = Expression.Parameter(type);
					var nameParameter = Expression.Parameter(typeof(string));
					var expressionParameter = Expression.Parameter(
						typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(enreplacedyType, typeof(bool)))
					);
					return Expression.Lambda(
						Expression.Block(
							Expression.Call(reposParameter, type.GetMethod("ApplyDataFilter", BindingFlags.Instance | BindingFlags.NonPublic), nameParameter, expressionParameter)
						),
						new[] {
						reposParameter, nameParameter, expressionParameter
						}
					).Compile();
				});
				foreach (var nf in newFilter) {
					del.DynamicInvoke(repos, nf.Key, nf.Value);
				}
				newFilter.Clear();
			}
		}

19 View Source File : Array3CodeGenResolver.cs
License : MIT License
Project Creator : 1996v

public static TypeInfo Build(DynamicFormatterreplacedembly replacedembly, ObjectSerializationInfo serializationInfo)
        {
            Type type = serializationInfo.Type;
            TypeBuilder typeBuilder = replacedembly.DefineFormatterType(type);
            serializationInfo.SerializeMemberInfosOrderByKeyIndex(type);

            MethodBuilder serializeMethod = TypeBuildHelper.DefineSerializeMethod(typeBuilder, type);
            MethodBuilder deserializeMethod = TypeBuildHelper.DefineDeserializeMethod(typeBuilder, type);
            MethodBuilder sizeMethod = TypeBuildHelper.DefineSizeMethod(typeBuilder, type);

            Type delegateCacheType = typeof(Array3DelegateCache<>).MakeGenericType(type);
            delegateCacheType.GetMethod(nameof(Array3DelegateCache<int>.Factory), BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, new object[] { replacedembly, serializationInfo });

            TypeBuildHelper.CallSerializeDelegate(serializeMethod, type, delegateCacheType.GetField(nameof(Array3DelegateCache<int>.Serialize)));
            TypeBuildHelper.CallSizeDelegate(sizeMethod, type, delegateCacheType.GetField(nameof(Array3DelegateCache<int>.Size)));
            TypeBuildHelper.CallDeserializeDelegate(deserializeMethod, type, delegateCacheType.GetField(nameof(Array3DelegateCache<int>.Deserialize)));

            return typeBuilder.CreateTypeInfo();
        }

19 View Source File : ValueMember.cs
License : MIT License
Project Creator : 404Lcc

private IProtoSerializer BuildSerializer()
        {
            int opaqueToken = 0;
            try
            {
                model.TakeLock(ref opaqueToken);// check nobody is still adding this type
                var member = backingMember ?? originalMember;
                IProtoSerializer ser;
                if (false)
                {
					Type dictionaryType,keyType,valueType;
                    ResolveMapTypes(out dictionaryType, out keyType, out valueType);

					var keyType2 = keyType;
					var valueType2 = valueType;
					if (keyType2 != null && keyType2.FullName == "ILRuntime.Runtime.Intepreter.ILTypeInstance") {
						keyType2 = PType.FindType (mapKeyTypeName);
					}
					if (valueType2 != null && valueType2.FullName == "ILRuntime.Runtime.Intepreter.ILTypeInstance") {
						valueType2 = PType.FindType (mapValueTypeName);
					}
					if(dictionaryType != null){
						dictionaryType = typeof(System.Collections.Generic.Dictionary<,>).MakeGenericType(new Type[]{ keyType, valueType});
					}

                    if (dictionaryType == null)
                    {
                        throw new InvalidOperationException("Unable to resolve map type for type: " + memberType.FullName);
                    }
                    var concreteType = defaultType;
                    if(concreteType == null && Helpers.IsClreplaced(memberType))
                    {
                        concreteType = memberType;
                    }
					WireType keyWireType;
                    var keySer = TryGetCoreSerializer(model, MapKeyFormat, keyType2, out keyWireType, false, false, false, false);
                    if(!AsReference)
                    {
                        AsReference = MetaType.GetAsReferenceDefault(model, valueType);
                    }
					WireType valueWireType;
                    var valueSer = TryGetCoreSerializer(model, MapValueFormat, valueType2, out valueWireType, AsReference, DynamicType, false, true);
#if PROFILE259
					IEnumerable<ConstructorInfo> ctors = typeof(MapDecorator<,,>).MakeGenericType(new Type[] { dictionaryType, keyType, valueType }).GetTypeInfo().DeclaredConstructors;
	                if (ctors.Count() != 1)
	                {
		                throw new InvalidOperationException("Unable to resolve MapDecorator constructor");
	                }
	                ser = (IProtoSerializer)ctors.First().Invoke(new object[] {model, concreteType, keySer, valueSer, fieldNumber,
		                DataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String, keyWireType, valueWireType, OverwriteList });
#else
				//	var ctors = typeof(MapDecorator<,,>).MakeGenericType(new Type[] { dictionaryType, keyType, valueType }).GetConstructors(
    //                    BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
				//if (ctors.Length != 1) throw new InvalidOperationException("Unable to resolve MapDecorator constructor");
    //                ser = (IProtoSerializer)ctors[0].Invoke(new object[] {model, concreteType, keySer, valueSer, fieldNumber,
    //                    DataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String, keyWireType, valueWireType, OverwriteList });
#endif
                }
                else
                {
                    WireType wireType;
                    Type finalType = itemType == null ? memberType : itemType;
                    ser = TryGetCoreSerializer(model, dataFormat, finalType, out wireType, AsReference, DynamicType, OverwriteList, true);
                    if (ser == null)
                    {
                        throw new InvalidOperationException("No serializer defined for type: " + finalType.FullName);
                    }

                    // apply tags
                    if (itemType != null && SupportNull)
                    {
                        if (IsPacked)
                        {
                            throw new NotSupportedException("Packed encodings cannot support null values");
                        }
                        ser = new TagDecorator(NullDecorator.Tag, wireType, IsStrict, ser);
                        ser = new NullDecorator(model, ser);
                        ser = new TagDecorator(fieldNumber, WireType.StartGroup, false, ser);
                    }
                    else
                    {
                        ser = new TagDecorator(fieldNumber, wireType, IsStrict, ser);
                    }
                    // apply lists if appropriate
                    if (itemType != null)
                    {
#if NO_GENERICS
                    Type underlyingItemType = itemType;
#else
                        Type underlyingItemType = SupportNull ? itemType : Helpers.GetUnderlyingType(itemType) ?? itemType;
#endif
                        Helpers.Debugreplacedert(underlyingItemType == ser.ExpectedType
                            || (ser.ExpectedType == model.MapType(typeof(object)) && !Helpers.IsValueType(underlyingItemType))
                            , "Wrong type in the tail; expected {0}, received {1}", ser.ExpectedType, underlyingItemType);
                        if (memberType.IsArray)
                        {
                            ser = new ArrayDecorator(model, ser, fieldNumber, IsPacked, wireType, memberType, OverwriteList, SupportNull);
                        }
                        else
                        {
                            ser = ListDecorator.Create(model, memberType, defaultType, ser, fieldNumber, IsPacked, wireType, member != null && PropertyDecorator.CanWrite(model, member), OverwriteList, SupportNull);
                        }
                    }
                    else if (defaultValue != null && !IsRequired && getSpecified == null)
                    {   // note: "ShouldSerialize*" / "*Specified" / etc ^^^^ take precedence over defaultValue,
                        // as does "IsRequired"
                        ser = new DefaultValueDecorator(model, defaultValue, ser);
                    }
                    if (memberType == model.MapType(typeof(Uri)))
                    {
                        ser = new UriDecorator(model, ser);
                    }
#if PORTABLE
                    else if(memberType.FullName == typeof(Uri).FullName)
                    {
                        // In PCLs, the Uri type may not match (WinRT uses Internal/Uri, .Net uses System/Uri)
                        ser = new ReflectedUriDecorator(memberType, model, ser);
                    }
#endif
                }
                if (member != null)
                {
                    PropertyInfo prop = member as PropertyInfo;
                    if (prop != null)
                    {
                        ser = new PropertyDecorator(model, parentType, (PropertyInfo)member, ser);
                    }
                    else
                    {
                        FieldInfo fld = member as FieldInfo;
                        if (fld != null)
                        {
                            ser = new FieldDecorator(parentType, (FieldInfo)member, ser);
                        }
                        else
                        {
                            throw new InvalidOperationException();
                        }
                    }
                    if (getSpecified != null || setSpecified != null)
                    {
                        ser = new MemberSpecifiedDecorator(getSpecified, setSpecified, ser);
                    }
                }
                return ser;
            }
            finally
            {
                model.ReleaseLock(opaqueToken);
            }
        }

19 View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v

public static Expression Call_DeserializeContextOptionResolver_GetFormatterWithVerify_Deserialize(Type type)
        {
            return Expression.Call(Call_GetFormatterWithVerify(DeserializeContextOptionResolver, type), typeof(IBssomFormatter<>).MakeGenericType(type).GetMethod(nameof(IBssomFormatter<int>.Deserialize)), Par_Reader, Par_DeserializeContext);
        }

19 View Source File : TypeFuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

private IEnumerable GenerateListOf(Type type, int recursionLevel)
        {
            var typeGenericTypeArguments = type.GenericTypeArguments;

            var listType = typeof(List<>);
            var constructedListType = listType.MakeGenericType(typeGenericTypeArguments);

            // Instantiates a collection of ...
            var list = Activator.CreateInstance(constructedListType) as IList;

            // Add 5 elements of this type
            for (var i = 0; i < MaxCountToFuzzInLists; i++)
            {
                list.Add(GenerateInstanceOf(typeGenericTypeArguments.Single(), recursionLevel));
            }

            return list;
        }

19 View Source File : ICollectionResolver.cs
License : MIT License
Project Creator : 1996v

internal static Type GetListFormatterType(Type itemType)
        {
            Type listT = typeof(List<>).MakeGenericType(itemType);
            return FormatterMap[listT].GetType();
        }

19 View Source File : GroupByIntoClause.cs
License : MIT License
Project Creator : 71

public static GroupByIntoClause GroupBy(ParameterExpression variable, Expression selector, ParameterExpression group)
        {
            if (selector == null)
                throw new ArgumentNullException(nameof(selector));
            if (variable == null)
                throw new ArgumentNullException(nameof(variable));

            if (!selector.IsreplacedignableTo<IEnumerable>())
                throw Error.ArgumentMustBereplacedignableTo<IEnumerable>(nameof(selector));

            if (group == null)
                group = Variable(typeof(IGrouping<,>).MakeGenericType(variable.Type, selector.Type));

            return new GroupByIntoClause(variable, selector, group);
        }

19 View Source File : CodeFirstProviderAbstract.cs
License : MIT License
Project Creator : 17MKH

public virtual void InitData(IRepositoryManager repositoryManager)
    {
        if (!Options.InitData)
            return;


        if (Options.InitDataFilePath.IsNull() || !File.Exists(Options.InitDataFilePath))
        {
            _logger.LogDebug("初始化数据文件不存在");
            return;
        }

        _logger.LogDebug("开始初始化数据");

        var jsonHelper = new JsonHelper();

        using var jsonReader = new StreamReader(Options.InitDataFilePath, Encoding.UTF8);
        var str = jsonReader.ReadToEnd();

        using var doc = JsonDoreplacedent.Parse(str);
        var properties = doc.RootElement.EnumerateObject();
        if (properties.Any())
        {
            foreach (var property in properties)
            {
                var enreplacedyDescriptor = Context.EnreplacedyDescriptors.FirstOrDefault(m => m.Name.EqualsIgnoreCase(property.Name));
                if (enreplacedyDescriptor != null)
                {
                    var list = (IList)jsonHelper.Deserialize(property.Value.ToString(),
                        typeof(List<>).MakeGenericType(enreplacedyDescriptor.EnreplacedyType));

                    var repositoryDescriptor = Context.RepositoryDescriptors.FirstOrDefault(m => m.EnreplacedyType == enreplacedyDescriptor.EnreplacedyType);

                    var repository = (IRepository)Service.BuildServiceProvider()
                        .GetService(repositoryDescriptor!.InterfaceType);

                    var tasks = new List<Task>();
                    foreach (var item in list)
                    {
                        tasks.Add(repository.Add(item));
                    }

                    Task.WaitAll(tasks.ToArray());
                }
            }
        }
    }

19 View Source File : CometaryExtensions.cs
License : MIT License
Project Creator : 71

public static Type GetCorrespondingType(this ITypeSymbol symbol)
        {
            if (symbol == null)
                throw new ArgumentNullException(nameof(symbol));

            switch (symbol.TypeKind)
            {
                case TypeKind.Array:
                    return ((IArrayTypeSymbol)symbol).ElementType.GetCorrespondingType().MakeArrayType();
                case TypeKind.Enum:
                case TypeKind.Clreplaced:
                case TypeKind.Delegate:
                case TypeKind.Interface:
                case TypeKind.Struct:
                    break;
                case TypeKind.Pointer:
                    return ((IPointerTypeSymbol)symbol).PointedAtType.GetCorrespondingType().MakePointerType();
                case TypeKind.TypeParameter:
                    ITypeParameterSymbol typeParameter = (ITypeParameterSymbol)symbol;
                    return typeParameter.DeclaringType.GetCorrespondingType().GenericTypeArguments[typeParameter.Ordinal];
                default:
                    throw new ArgumentOutOfRangeException();
            }

            INamedTypeSymbol named = (INamedTypeSymbol)symbol;
            Type type = named.ContainingNamespace.IsGlobalNamespace
                ? Type.GetType($"{named.MetadataName}, {named.Containingreplacedembly.MetadataName}")
                : Type.GetType($"{named.ContainingNamespace}.{named.MetadataName}, {named.Containingreplacedembly.MetadataName}");

            if (type == null)
                return null;

            int typeArgsLength = type.GenericTypeArguments.Length;

            if (typeArgsLength == 0)
                return type;

            Type[] typeArgs = new Type[typeArgsLength];

            for (int i = 0; i < typeArgsLength; i++)
            {
                typeArgs[i] = named.TypeArguments[i].GetCorrespondingType();
            }

            return type.MakeGenericType(typeArgs);
        }

19 View Source File : IDictionaryResolver.cs
License : MIT License
Project Creator : 1996v

public static TypeInfo BuildGenericIDictionaryImplementationType(DynamicFormatterreplacedembly replacedembly, ConstructorInfo constructor, Type type, Type genericKeyType, Type genericValueType)
        {
            TypeBuilder typeBuilder = replacedembly.DefineFormatterType(type);

            MethodBuilder serializeMethod = TypeBuildHelper.DefineSerializeMethod(typeBuilder, type);
            TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.SerializeGenericDictionary), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(new Type[] { genericKeyType, genericValueType }));

            MethodBuilder deserializeMethod = TypeBuildHelper.DefineDeserializeMethod(typeBuilder, type);
            ParameterInfo[] args = constructor.GetParameters();
            Type dynamicCacheType = typeof(IDictionaryDynamicDelegateCache<>).MakeGenericType(type);
            if (args.Length == 0)
            {
                MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(IDictionaryDynamicDelegateCache<int>.GenerateDeserializeWithGenericDictEmptyCtor));
                methodinfo.Invoke(null, new object[] { constructor, genericKeyType, genericValueType });
            }
            else
            {
                DEBUG.replacedert(args.Length == 1);
                if (args[0].ParameterType == typeof(int))
                {
                    MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(IDictionaryDynamicDelegateCache<int>.GenerateDeserializeWithGenericDictCapacityCtor));
                    methodinfo.Invoke(null, new object[] { constructor, genericKeyType, genericValueType });
                }
                else
                {
                    MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(IDictionaryDynamicDelegateCache<int>.GenerateInjectCtor));
                    methodinfo.Invoke(null, new object[] { constructor, args[0].ParameterType });
                }
            }
            TypeBuildHelper.CallDeserializeDelegate(deserializeMethod, type, dynamicCacheType.GetField(nameof(IDictionaryDynamicDelegateCache<int>.Deserialize), BindingFlags.Public | BindingFlags.Static));

            MethodBuilder sizeMethod = TypeBuildHelper.DefineSizeMethod(typeBuilder, type);
            TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.SizeGenericDictionary), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(genericKeyType, genericValueType));

            return typeBuilder.CreateTypeInfo();
        }

19 View Source File : QueryClause.cs
License : MIT License
Project Creator : 71

internal static Type QueryableType(Type type) => typeof(IQueryable<>).MakeGenericType(type);

19 View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v

public static Expression Call_SizeContextOptionResolver_GetFormatterWithVerify_Size(Expression value)
        {
            return Expression.Call(Call_GetFormatterWithVerify(SizeContextOptionResolver, value.Type), typeof(IBssomFormatter<>).MakeGenericType(value.Type).GetMethod(nameof(IBssomFormatter<int>.Size)), Par_SizeContext, value);
        }

19 View Source File : Config.cs
License : Apache License 2.0
Project Creator : aadreja

internal static Type AuditTrialRepositoryGenericType<T>()
        {
            return AuditTrailRepositoryType.MakeGenericType(typeof(T));
        }

19 View Source File : IDictionaryResolver.cs
License : MIT License
Project Creator : 1996v

private static void GenerateDeserializeWithGenericDictCore(Type keyType, Type valueType, Func<MemberExpression, Expression> ctor)
        {
            /*
               var map = MapFormatterHelper.Deserialize(ref reader,ref context);
               if (map == null)
                   return null;
               context.option.Security.DepthStep(ref reader);
               T t = new T();/new T(map.Count)
               Deserialize(IEnumerable<KeyValuePair<TKey, TValue>> pair,(ICollection<KeyValuePair<TKey, TValue>>)t);
               reader = map.Reader; context = map.Context; 
               reader.Seek(map.EndPos);
               context.Depth--;
               return t;  
            */

            ArrayPack<Expression> ary = new ArrayPack<Expression>(10);
            Type t = typeof(T);
            LabelTarget returnTarget = Expression.Label(t, "returnLable");
            ParameterExpression map = Expression.Variable(typeof(IMapDataSource<,>).MakeGenericType(keyType, valueType));
            //map = MapFormatterHelper.Deserialize(ref reader,ref context);
            ary.Add(Expression.replacedign(map, CommonExpressionMeta.Call_MapFormatterHelper_Deserialize(keyType, valueType)));
            //if (map == null)
            //      goto label;
            ary.Add(Expression.IfThen(Expression.Equal(map, Expression.Constant(null, map.Type)), Expression.Return(returnTarget, Expression.Default(t))));
            //context.option.Security.DepthStep(ref reader);
            ary.Add(CommonExpressionMeta.Call_DeserializeContext_Option_Security_DepthStep);
            //T t = ctor(map.Count);
            ParameterExpression instance = Expression.Variable(t);
            ary.Add(Expression.replacedign(instance, ctor(Expression.Property(map, nameof(BssMapObjMarshalReader<int, int>.Count)))));
            //MapFormatterHelper.FillData(map,(ICollection<KeyValuePair<TKey, TValue>>)t)
            ary.Add(Expression.Call(null, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.FillGenericIDictionaryData), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(keyType, valueType), map, Expression.Convert(instance, typeof(ICollection<>).MakeGenericType(typeof(KeyValuePair<,>).MakeGenericType(keyType, valueType)))));

            //reader = map.Reader; context = map.Context; 
            ary.Add(CommonExpressionMeta.Block_MapReaderAndContextreplacedignLocalReaderAndContext(map));
            //reader.Seek(map.EndPos);
            ary.Add(CommonExpressionMeta.Call_Reader_BufferSeek(Expression.Property(map, nameof(IMapDataSource<int, int>.EndPosition))));
            //context.Depth--;
            ary.Add(CommonExpressionMeta.Call_DeserializeContext_Depth_Decrementreplacedign);
            //return t;
            ary.Add(Expression.Return(returnTarget, instance));
            //label default(T)
            ary.Add(Expression.Label(returnTarget, instance));

            BlockExpression block = Expression.Block(new ParameterExpression[] { map, instance }, ary.GetArray());
            Deserialize = Expression.Lambda<Deserialize<T>>(block, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext).Compile();
        }

19 View Source File : EventBusRabbitMq.cs
License : MIT License
Project Creator : Abdulrhman5

private async Task ProcessEvent(string eventName, string message)
        {
            _logger.LogTrace("Processing RabbitMQ event: {EventName}", eventName);

            if (_subsManager.HreplacedubscriptionsForEvent(eventName))
            {

                var subscriptions = _subsManager.GetHandlersForEvent(eventName);
                foreach (var subscription in subscriptions)
                {

                    var handler = _container.Resolve(subscription.HandlerType);
                    if (handler == null) continue;
                    var eventType = _subsManager.GetEventTypeByName(eventName);
                    var integrationEvent = JsonConvert.DeserializeObject(message, eventType);
                    var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType);

                    await Task.Yield();
                    await (Task)concreteType.GetMethod(nameof(IIntegrationEventHandler<object>.HandleEvent)).Invoke(handler, new object[] { integrationEvent });
                }
            }
            else
            {
                _logger.LogWarning("No subscription for RabbitMQ event: {EventName}", eventName);
            }
        }

19 View Source File : Protocol16Deserializer.cs
License : MIT License
Project Creator : 0blu

private static Type DeserializeDictionaryType(Protocol16Stream input, out byte keyTypeCode, out byte valueTypeCode)
        {
            keyTypeCode = (byte)input.ReadByte();
            valueTypeCode = (byte)input.ReadByte();
            Type keyType = GetTypeOfCode(keyTypeCode);
            Type valueType = GetTypeOfCode(valueTypeCode);

            return typeof(Dictionary<,>).MakeGenericType(new Type[]
            {
                keyType,
                valueType
            });
        }

19 View Source File : RoslynDiagnosticService.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private static PropertyInfo GetTaskResultPropertyInfo(Type diagnosticDataType)
		{
			Type genericIEnumerableType = typeof(IEnumerable<>).MakeGenericType(diagnosticDataType);

			if (genericIEnumerableType == null)
				return null;

			Type genericTask = typeof(Task<>).MakeGenericType(genericIEnumerableType);
			return genericTask?.GetProperty(nameof(Task<object>.Result));
		}

19 View Source File : BuildInResolverTest_SpecialGenericType.cs
License : MIT License
Project Creator : 1996v

[Fact]
        public void ResolverGetFormatter_AnonymousTypeFormatter_CanBeObtainedNormally()
        {
            var testData = new { A = 600, CA = true, BD = new { Num = 7, TC = 17 }, EF = "oaoaoaoa" };
            var t = testData.GetType();
            BuildInResolver.Instance.GetFormatterWithVerify(t).IsType(typeof(AnonymousTypeFormatter<>).MakeGenericType(t));
        }

19 View Source File : DynamicAssembly.cs
License : MIT License
Project Creator : 1996v

public TypeBuilder DefineFormatterType(Type type)
        {
            VerifyTypeIsPublic(type);

            Type formatterType = typeof(IBssomFormatter<>).MakeGenericType(type);
            TypeBuilder typeBuilder = DefineType("Bssom.Formatters." + SubtractFullNameRegex.Replace(type.FullName, string.Empty).Replace(".", "_") + "Formatter" + Interlocked.Increment(ref nameSequence), TypeAttributes.NotPublic | TypeAttributes.Sealed, null, new[] { formatterType });
            return typeBuilder;
        }

19 View Source File : Protocol16Deserializer.cs
License : MIT License
Project Creator : 0blu

private static IDictionary DeserializeDictionary(Protocol16Stream input)
        {
            byte keyTypeCode = (byte)input.ReadByte();
            byte valueTypeCode = (byte)input.ReadByte();
            int dictionarySize = DeserializeShort(input);
            Type keyType = GetTypeOfCode(keyTypeCode);
            Type valueType = GetTypeOfCode(valueTypeCode);
            Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(new Type[]
            {
                keyType,
                valueType
            });

            IDictionary output = Activator.CreateInstance(dictionaryType) as IDictionary;
            DeserializeDictionaryElements(input, output, dictionarySize, keyTypeCode, valueTypeCode);
            return output;
        }

19 View Source File : __LeaderboardReader__.cs
License : zlib License
Project Creator : 0x0ade

[MonoModHook("System.Collections.ObjectModel.ReadOnlyCollection`1<Microsoft.Xna.Framework.GamerServices.LeaderboardEntry> Microsoft.Xna.Framework.GamerServices.LeaderboardReader::get_Entries()")]
        public static object get_Entries(/*LeaderboardReader*/ object reader) {
            // Return an empty collection.
            if (t_LeaderboardEntry == null) {
                t_LeaderboardEntry = StubXDKHelper.GamerServicesAsm.GetType("Microsoft.Xna.Framework.GamerServices.LeaderboardEntry");
            }
            if (t_IList == null) {
                t_IList = typeof(IList<>).MakeGenericType(t_LeaderboardEntry);
            }
            if (t_List == null) {
                t_List = typeof(List<>).MakeGenericType(t_LeaderboardEntry);
                ctor_List = t_List.GetConstructor(
                    BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance,
                    null,
                    new Type[] { },
                    null
                );
            }
            if (t_ReadOnlyCollection == null) {
                t_ReadOnlyCollection = typeof(ReadOnlyCollection<>).MakeGenericType(t_LeaderboardEntry);
                ctor_ReadOnlyCollection = t_List.GetConstructor(
                    BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance,
                    null,
                    new Type[] { t_IList },
                    null
                );
            }
            return ctor_ReadOnlyCollection.Invoke(new object[] { ctor_List.Invoke(new object[] { }) });
        }

19 View Source File : ObjectFormatter.cs
License : MIT License
Project Creator : 1996v

public static object Deserialize(Type type, ref BssomReader reader, ref BssomDeserializeContext context)
        {
            object formatter = context.Option.FormatterResolver.GetFormatterWithVerify(type);

            if (!DeserializerDelegates.TryGetValue(type, out DeserializeMethod deserializerDelegate))
            {
                Type formatterType = typeof(IBssomFormatter<>).MakeGenericType(type);
                ParameterExpression param0 = Expression.Parameter(typeof(object), "formatter");
                ParameterExpression param1 = Expression.Parameter(typeof(BssomReader).MakeByRefType(), "reader");
                ParameterExpression param2 = Expression.Parameter(typeof(BssomDeserializeContext).MakeByRefType(), "context");

                MethodInfo deserializeMethod = formatterType.GetRuntimeMethod(nameof(Deserialize), new[] { typeof(BssomReader).MakeByRefType(), typeof(BssomDeserializeContext).MakeByRefType() });

                //(object)IBssomFormatter<T>.Deserialize(ref reader,option);
                UnaryExpression body = Expression.Convert(Expression.Call(
                    Expression.Convert(param0, formatterType),
                    deserializeMethod,
                    param1,
                    param2), typeof(object));

                deserializerDelegate = Expression.Lambda<DeserializeMethod>(body, param0, param1, param2).Compile();
                DeserializerDelegates.TryAdd(type, deserializerDelegate);
            }

            return deserializerDelegate(formatter, ref reader, ref context);
        }

19 View Source File : TypeBuildHelper.cs
License : MIT License
Project Creator : 1996v

public static void CallSizeDelegate(MethodBuilder serializeMethod, Type genericType, FieldInfo fieldInfo)
        {
            ILGenerator il = serializeMethod.GetILGenerator();
            il.Emit(OpCodes.Ldsfld, fieldInfo);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Ldarg_2);
            il.Emit(OpCodes.Call, typeof(Size<>).MakeGenericType(genericType).GetMethod(nameof(Size<int>.Invoke)));
            il.Emit(OpCodes.Ret);
        }

19 View Source File : DbContext.cs
License : MIT License
Project Creator : 2881099

internal void InitPropSets() {
			var props = _dicGetDbSetProps.GetOrAdd(this.GetType(), tp => 
				tp.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public)
					.Where(a => a.PropertyType.IsGenericType &&
						a.PropertyType == typeof(DbSet<>).MakeGenericType(a.PropertyType.GenericTypeArguments[0])).ToArray());

			foreach (var prop in props) {
				var set = this.Set(prop.PropertyType.GenericTypeArguments[0]);

				prop.SetValue(this, set);
				AllSets.Add(prop.Name, set);
			}
		}

See More Examples