System.Type.GetMethod(string, System.Type[])

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

996 Examples 7

19 View Source File : ExpressionCompilationTests.cs
License : Apache License 2.0
Project Creator : alexz76

[Fact]
		public void ExpressionTree_TestOne()
		{
			// Arrange
			var companies = new[]
			{
				"Consolidated Messenger", "Alpine Ski House", "Southridge Video", "City Power & Light", "Coho Winery", "Wide World Importers",
				"Graphic Design Insreplacedute", "Adventure Works", "Humongous Insurance", "Woodgrove Bank", "Margie's Travel", "Northwind Traders",
				"Blue Yonder Airlines", "Trey Research", "The Phone Company", "Wingtip Toys", "Lucerne Publishing", "Fourth Coffee"
			}.AsQueryable();

			var expParameter = Expression.Parameter(typeof(string), "company");
			var expArguments = Expression.Constant("ho");
			var expContains = Expression.Call(expParameter, typeof(string).GetMethod(nameof(string.Contains), new[] { typeof(string) }), new[] { expArguments });

			var expContainsIsTrue = Expression.IsTrue(expContains);

			var isTrueCall = Expression.Call(
				typeof(Queryable),
				nameof(Queryable.Where),
				new[] { companies.ElementType },
				companies.Expression,
				Expression.Lambda<Func<string, bool>>(expContainsIsTrue, new[] { expParameter }));

			// Act
			var results = companies.Provider.CreateQuery<string>(isTrueCall);

			// replacedert
			results.Any().Should().BeTrue();
			results.Count().Should().BeGreaterThan(0);
		}

19 View Source File : SyntaxTreeToQueryConvertor.cs
License : MIT License
Project Creator : alirezanet

private static MethodInfo GetIsNullOrEmptyMethod() => typeof(string).GetMethod("IsNullOrEmpty", new[] { typeof(string) })

19 View Source File : PrefixWriter.cs
License : MIT License
Project Creator : Abc-Arbitrage

private static Action<PrefixWriter, ILogEventHeader> BuildAppendMethod(ICollection<PatternPart> parts, Dictionary<string, (int offset, int length)> stringMap)
        {
            var method = new DynamicMethod("WritePrefix", typeof(void), new[] { typeof(PrefixWriter), typeof(ILogEventHeader) }, typeof(PrefixWriter), false)
            {
                InitLocals = false
            };

            var il = method.GetILGenerator();

            var stringBufferLocal = il.DeclareLocal(typeof(StringBuffer));
            var stringsLocal = il.DeclareLocal(typeof(char).MakeByRefType(), true);
            var dateTimeLocal = default(LocalBuilder);

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, typeof(PrefixWriter).GetField(nameof(_stringBuffer), BindingFlags.Instance | BindingFlags.NonPublic)!);
            il.Emit(OpCodes.Stloc, stringBufferLocal);

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, typeof(PrefixWriter).GetField(nameof(_strings), BindingFlags.Instance | BindingFlags.NonPublic)!);
            il.Emit(OpCodes.Ldc_I4_0);
            il.Emit(OpCodes.Ldelema, typeof(char));
            il.Emit(OpCodes.Stloc, stringsLocal);

            foreach (var part in parts)
            {
                switch (part.Type)
                {
                    case PatternPartType.String:
                    {
                        // _stringBuffer.Append(&_strings[0] + offset * sizeof(char), length);

                        var (offset, length) = stringMap[part.Value!];

                        il.Emit(OpCodes.Ldloc, stringBufferLocal);

                        il.Emit(OpCodes.Ldloc, stringsLocal);
                        il.Emit(OpCodes.Conv_U);
                        il.Emit(OpCodes.Ldc_I4, offset * sizeof(char));
                        il.Emit(OpCodes.Add);

                        il.Emit(OpCodes.Ldc_I4, length);

                        il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(char*), typeof(int) })!);
                        break;
                    }

                    case PatternPartType.Date:
                    {
                        // _stringBuffer.Append(logEventHeader.Timestamp, new StringView(&_strings[0] + offset * sizeof(char), length));

                        var (offset, length) = stringMap[_dateFormat];

                        il.Emit(OpCodes.Ldloc, stringBufferLocal);

                        il.Emit(OpCodes.Ldarg_1);
                        il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Timestamp))?.GetGetMethod()!);

                        il.Emit(OpCodes.Ldloc, stringsLocal);
                        il.Emit(OpCodes.Conv_U);
                        il.Emit(OpCodes.Ldc_I4, offset * sizeof(char));
                        il.Emit(OpCodes.Add);

                        il.Emit(OpCodes.Ldc_I4, length);

                        il.Emit(OpCodes.Newobj, typeof(StringView).GetConstructor(new[] { typeof(char*), typeof(int) })!);

                        il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(DateTime), typeof(StringView) })!);
                        break;
                    }

                    case PatternPartType.Time:
                    {
                        // _stringBuffer.Append(logEventHeader.Timestamp.TimeOfDay, StringView.Empty);

                        il.Emit(OpCodes.Ldloc, stringBufferLocal);

                        il.Emit(OpCodes.Ldarg_1);
                        il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Timestamp))?.GetGetMethod()!);
                        il.Emit(OpCodes.Stloc, dateTimeLocal ??= il.DeclareLocal(typeof(DateTime)));
                        il.Emit(OpCodes.Ldloca, dateTimeLocal);
                        il.Emit(OpCodes.Call, typeof(DateTime).GetProperty(nameof(DateTime.TimeOfDay))?.GetGetMethod()!);

                        il.Emit(OpCodes.Ldsfld, typeof(StringView).GetField(nameof(StringView.Empty))!);

                        il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(TimeSpan), typeof(StringView) })!);
                        break;
                    }

                    case PatternPartType.Thread:
                    {
                        // AppendThread(logEventHeader.Thread);

                        il.Emit(OpCodes.Ldarg_0);

                        il.Emit(OpCodes.Ldarg_1);
                        il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Thread))?.GetGetMethod()!);

                        il.Emit(OpCodes.Call, typeof(PrefixWriter).GetMethod(nameof(AppendThread), BindingFlags.Instance | BindingFlags.NonPublic)!);
                        break;
                    }

                    case PatternPartType.Level:
                    {
                        // _stringBuffer.Append(LevelStringCache.GetLevelString(logEventHeader.Level));

                        il.Emit(OpCodes.Ldloc, stringBufferLocal);

                        il.Emit(OpCodes.Ldarg_1);
                        il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Level))?.GetGetMethod()!);
                        il.Emit(OpCodes.Call, typeof(LevelStringCache).GetMethod(nameof(LevelStringCache.GetLevelString))!);

                        il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(string) })!);
                        break;
                    }

                    case PatternPartType.Logger:
                    {
                        // _stringBuffer.Append(logEventHeader.Name);

                        il.Emit(OpCodes.Ldloc, stringBufferLocal);

                        il.Emit(OpCodes.Ldarg_1);
                        il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Name))?.GetGetMethod()!);

                        il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(string) })!);
                        break;
                    }

                    default:
                        throw new ArgumentOutOfRangeException();
                }
            }

            il.Emit(OpCodes.Ret);

            return (Action<PrefixWriter, ILogEventHeader>)method.CreateDelegate(typeof(Action<PrefixWriter, ILogEventHeader>));
        }

19 View Source File : DynamicUtils.cs
License : MIT License
Project Creator : akaskela

private static object CreateSharpArgumentInfoArray(params int[] values)
            {
                Type csharpArgumentInfoType = Type.GetType(CSharpArgumentInfoTypeName);
                Type csharpArgumentInfoFlags = Type.GetType(CSharpArgumentInfoFlagsTypeName);

                Array a = Array.CreateInstance(csharpArgumentInfoType, values.Length);

                for (int i = 0; i < values.Length; i++)
                {
                    MethodInfo createArgumentInfoMethod = csharpArgumentInfoType.GetMethod("Create", new[] { csharpArgumentInfoFlags, typeof(string) });
                    object arg = createArgumentInfoMethod.Invoke(null, new object[] { 0, null });
                    a.SetValue(arg, i);
                }

                return a;
            }

19 View Source File : Serializer.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

static Func<Dictionary<string, string>, T> CompileDeserializer()
        {
            var o_t = typeof(T);
            var o_ctor = o_t.GetConstructor(new[] { typeof(SerializationInfo), typeof(StreamingContext) });

            var d_t = typeof(Dictionary<string, string>);
            var d = Expression.Parameter(d_t, "d");
            var d_mi_get_enumerator = d_t.GetMethod("GetEnumerator");

            var fc_t = typeof(LocalVariableInfo);
            var fc = Expression.Variable(fc_t, "fc");
            var fc_init = Expression.MemberInit(Expression.New(fc_t));

            var info_t = typeof(SerializationInfo);
            var info = Expression.Variable(info_t, "info");
            var info_ctor = info_t.GetConstructor(new[] { typeof(Type), fc_t });
            var info_init = Expression.MemberInit(Expression.New(info_ctor, Expression.Constant(o_t), fc));
            var info_mi_add_value = info_t.GetMethod("AddValue", new[] { typeof(String), typeof(Object) });

            var ctx_t = typeof(StreamingContext);
            var ctx = Expression.Variable(ctx_t, "ctx");
            var ctx_init = Expression.MemberInit(Expression.New(ctx_t));

            var enumerator_t = typeof(Dictionary<string, string>.Enumerator);
            var enumerator = Expression.Variable(enumerator_t, "enumerator");
            var enumerator_mi_move_next = enumerator_t.GetMethod("MoveNext");
            var enumerator_current = Expression.Property(enumerator, "Current");

            var kvp_t = typeof(KeyValuePair<string, string>);
            var kvp_pi_key = kvp_t.GetProperty("Key");
            var kvp_pi_value = kvp_t.GetProperty("Value");

            var exit_loop = Expression.Label("exit_loop");

            var body = Expression.Block(new[] { fc, info, ctx, enumerator },
                Expression.replacedign(fc, fc_init),
                Expression.replacedign(info, info_init),
                Expression.replacedign(ctx, ctx_init),
                Expression.replacedign(enumerator, Expression.Call(d, d_mi_get_enumerator)),

                Expression.Loop(
                    Expression.IfThenElse(
                        Expression.Call(enumerator, enumerator_mi_move_next),
                        Expression.Call(info, info_mi_add_value, Expression.Property(enumerator_current, kvp_pi_key), Expression.Property(enumerator_current, kvp_pi_value)),
                        Expression.Break(exit_loop)),
                    exit_loop),

                Expression.MemberInit(Expression.New(o_ctor, info, ctx))
            );

            return Expression.Lambda<Func<Dictionary<string, string>, T>>(body, d)
                .Compile();
        }

19 View Source File : PowerToolsIntegration.cs
License : Apache License 2.0
Project Creator : A7ocin

public static void Show(UMARecipeBase recipeBase)
		{
			var go = new GameObject("PowerTools_" + recipeBase.name);
			go.hideFlags = HideFlags.HideInHierarchy | HideFlags.HideInInspector;
			var avatar = go.AddComponent<UMADynamicAvatar>();
			avatar.umaRecipe = recipeBase;

			var persistance = GetPowerPackPersistanceType();
			var showAvatarMethod = persistance.GetMethod("ShowAvatar", new Type[] { typeof(UMAAvatarBase) });
			var instance = GetPowerPackPersistanceInstance();
			showAvatarMethod.Invoke(instance, new object[] { avatar });
			ReleasePowerPackPersistanceInstance(instance);
			SetAvatarDestroyParent(avatar, true);
#if UNITY_EDITOR
			go.transform.position = UnityEditor.SceneView.lastActiveSceneView.pivot - new Vector3(0,1,0);
#endif
		}

19 View Source File : InvokeWrapperInspectorDrawer.cs
License : Apache License 2.0
Project Creator : Algoryx

private static DefaultAndUserValueResult HandleDefaultAndUserValue<ValueT>( object[] objects,
                                                                                InvokeWrapper wrapper )
      where ValueT : struct
    {
      if ( s_floatFieldMethod == null )
        s_floatFieldMethod = typeof( EditorGUI ).GetMethod( "FloatField",
                                                            new[]
                                                            {
                                                              typeof( Rect ),
                                                              typeof( string ),
                                                              typeof( float )
                                                            } );
      if ( s_vector3FieldMethod == null )
        s_vector3FieldMethod = typeof( EditorGUI ).GetMethod( "Vector3Field",
                                                              new[]
                                                              {
                                                                typeof( Rect ),
                                                                typeof( string ),
                                                                typeof( Vector3 )
                                                              } );

      var method = typeof( ValueT ) == typeof( float ) ?
                      s_floatFieldMethod :
                    typeof( ValueT ) == typeof( Vector3 ) ?
                      s_vector3FieldMethod :
                      null;

      if ( method == null )
        throw new NullReferenceException( "Unknown DefaultAndUserValue type: " + typeof( ValueT ).Name );

      var updateButtonWidth = 20.0f;
      var rect = EditorGUILayout.GetControlRect();

      // Now we know the total width if the Inspector. Remove
      // width of button and right most spacing.
      rect.xMax -= updateButtonWidth;

      // We don't want the tooltip of the toggle to show when
      // hovering the update button or float field(s) so use
      // xMax as label width minus some magic number so that
      // e.g., Mreplaced float field slider appears and works.
      var widthUntilButton = rect.xMax;
      rect.xMax = EditorGUIUtility.labelWidth - 28;

      // Result and reference instance.
      var result = new DefaultAndUserValueResult();
      var instance = wrapper.Get<DefaultAndUserValue<ValueT>>( objects[ 0 ] );

      UnityEngine.GUI.changed = false;
      var hasMixedUseDefault = !CompareMulti<ValueT>( objects,
                                                       wrapper,
                                                       other => other.UseDefault == instance.UseDefault );
      EditorGUI.showMixedValue = hasMixedUseDefault;

      var toggleInput = hasMixedUseDefault ?
                          false :
                          instance.UseDefault;
      // During showMixedValue - Toggle will always return true (enabled)
      // when the user clicks regardless of instance.UseDefault.
      var toggleOutput = EditorGUI.ToggleLeft( rect,
                                               GUI.MakeLabel( wrapper.Member.Name.SplitCamelCase(),
                                                              false,
                                                              "If checked - value will be default. Uncheck to manually enter value." ),
                                               toggleInput );
      if ( toggleOutput != toggleInput ) {
        result.DefaultToggleChanged = true;
        result.UseDefault = toggleOutput;
      }

      // Restore width and calculate new start of the float
      // field(s). Start is label width but we have to remove
      // the current indent level since label width is independent
      // of the indent level. Unsure why we have to add LayoutMagicNumber pixels...
      // could be float field(s) default minimum label size.
      rect.xMax = widthUntilButton;
      rect.x = EditorGUIUtility.labelWidth - InspectorGUI.IndentScope.PixelLevel + InspectorGUI.LayoutMagicNumber;
      rect.xMax += -rect.x + InspectorGUI.LayoutMagicNumber;

      s_fieldMethodArgs[ 0 ] = rect;
      s_fieldMethodArgs[ 2 ] = instance.Value;
      var newValue = default( ValueT );

      EditorGUI.showMixedValue = !CompareMulti<ValueT>( objects,
                                                        wrapper,
                                                        other => instance.Value.Equals( other.Value ) );
      using ( new GUI.EnabledBlock( UnityEngine.GUI.enabled &&
                                    !instance.UseDefault &&
                                    !hasMixedUseDefault ) ) {
        EditorGUI.BeginChangeCheck();
        newValue = (ValueT)method.Invoke( null, s_fieldMethodArgs );
        if ( EditorGUI.EndChangeCheck() ) {
          // Validate input here so that, e.g., 0 isn't propagated. It's
          // not possible to check this in the CopyOp callback.
          var clampAttribute = wrapper.GetAttribute<ClampAboveZeroInInspector>();
          if ( clampAttribute == null || clampAttribute.IsValid( newValue ) )
            result.OnChange<ValueT>( instance.Value, newValue );
        }
      }

      rect.x = rect.xMax;
      rect.width = updateButtonWidth;
      rect.height = EditorGUIUtility.singleLineHeight -
                                    EditorGUIUtility.standardVerticalSpacing;
      result.UpdateDefaultClicked = InspectorGUI.Button( rect,
                                                         MiscIcon.Update,
                                                         instance.UseDefault,
                                                         InspectorEditor.Skin.ButtonRight,
                                                         "Force update of default value.",
                                                         1.2f );

      return result;
    }

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

static Func<Dictionary<string, string>, T> CompileDeserializer()
        {
            var o_t = typeof(T);
            var o_ctor = o_t.GetConstructor(new[] { typeof(SerializationInfo), typeof(StreamingContext) });

            var d_t = typeof(Dictionary<string, string>);
            var d = Expression.Parameter(d_t, "d");
            var d_mi_get_enumerator = d_t.GetMethod("GetEnumerator");

            var fc_t = typeof(IFormatterConverter);// typeof(LocalVariableInfo);
            var fc = Expression.Variable(fc_t, "fc");
            var fc_init = Expression.MemberInit(Expression.New(typeof(System.Runtime.Serialization.FormatterConverter))); //Expression.MemberInit(Expression.New(fc_t));

            var info_t = typeof(SerializationInfo);
            var info = Expression.Variable(info_t, "info");
            var info_ctor = info_t.GetConstructor(new[] { typeof(Type), fc_t });
            var info_init = Expression.MemberInit(Expression.New(info_ctor, Expression.Constant(o_t), fc));
            var info_mi_add_value = info_t.GetMethod("AddValue", new[] { typeof(String), typeof(Object) });

            var ctx_t = typeof(StreamingContext);
            var ctx = Expression.Variable(ctx_t, "ctx");
            var ctx_init = Expression.MemberInit(Expression.New(ctx_t));

            var enumerator_t = typeof(Dictionary<string, string>.Enumerator);
            var enumerator = Expression.Variable(enumerator_t, "enumerator");
            var enumerator_mi_move_next = enumerator_t.GetMethod("MoveNext");
            var enumerator_current = Expression.Property(enumerator, "Current");

            var kvp_t = typeof(KeyValuePair<string, string>);
            var kvp_pi_key = kvp_t.GetProperty("Key");
            var kvp_pi_value = kvp_t.GetProperty("Value");

            var exit_loop = Expression.Label("exit_loop");

            var body = Expression.Block(new[] { fc, info, ctx, enumerator },
                Expression.replacedign(fc, fc_init),
                Expression.replacedign(info, info_init),
                Expression.replacedign(ctx, ctx_init),
                Expression.replacedign(enumerator, Expression.Call(d, d_mi_get_enumerator)),

                Expression.Loop(
                    Expression.IfThenElse(
                        Expression.Call(enumerator, enumerator_mi_move_next),
                        Expression.Call(info, info_mi_add_value, Expression.Property(enumerator_current, kvp_pi_key), Expression.Property(enumerator_current, kvp_pi_value)),
                        Expression.Break(exit_loop)),
                    exit_loop),

                Expression.MemberInit(Expression.New(o_ctor, info, ctx))
            );

            return Expression.Lambda<Func<Dictionary<string, string>, T>>(body, d)
                .Compile();
        }

19 View Source File : SyntaxTreeToQueryConvertor.cs
License : MIT License
Project Creator : alirezanet

private static MethodInfo GetCompareMethod() =>
         typeof(string).GetMethod("Compare", new[] { typeof(string), typeof(string) })

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 : ConvertUtils.cs
License : MIT License
Project Creator : akaskela

private static Func<object, object> CreateCastConverter(TypeConvertKey t)
        {
            MethodInfo castMethodInfo = t.TargetType.GetMethod("op_Implicit", new[] { t.InitialType });
            if (castMethodInfo == null)
            {
                castMethodInfo = t.TargetType.GetMethod("op_Explicit", new[] { t.InitialType });
            }

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

            MethodCall<object, object> call = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(castMethodInfo);

            return o => call(null, o);
        }

19 View Source File : AdminStore.cs
License : Apache License 2.0
Project Creator : Aguafrommars

private async Task<object> GetSubItemsAsync(TEnreplacedy enreplacedy, Type propertyType)
        {
            var storeType = typeof(IAdminStore<>).MakeGenericType(propertyType.GetGenericArguments()[0]);
            var subStore = _provider.GetRequiredService(storeType);
            var getPageResponseMethod = storeType.GetMethod(nameof(IAdminStore<object>.GetAsync), new[] { typeof(PageRequest), typeof(CancellationToken) });
            var task = getPageResponseMethod.Invoke(subStore, new[]
            {
                    new PageRequest
                    {
                        Filter = $"{GetSubEnreplacedyParentIdName(_enreplacedyType)} eq '{enreplacedy.Id}'",
                        Take = null
                    },
                    null
                });
            await (task as Task).ConfigureAwait(false);
            var response = task.GetType().GetProperty(nameof(Task<object>.Result)).GetValue(task);
            var items = response.GetType().GetProperty(nameof(PageResponse<object>.Items)).GetValue(response);
            return items;
        }

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

public unsafe static void RegisterCLRMethodRedirction(AppDomain appdomain)
        {
            Type logUtilType = typeof(LogUtil);
            var logMethod = logUtilType.GetMethod("Log", new[] { typeof(object) });
            appdomain.RegisterCLRMethodRedirection(logMethod, Log);
            var logWarningMethod = logUtilType.GetMethod("LogWarning", new[] { typeof(object) });
            appdomain.RegisterCLRMethodRedirection(logWarningMethod, LogWarning);
            var logErrorMethod = logUtilType.GetMethod("LogError", new[] { typeof(object) });
            appdomain.RegisterCLRMethodRedirection(logErrorMethod, LogError);
        }

19 View Source File : QueryableExtensions.cs
License : MIT License
Project Creator : albyho

public static IQueryable<TEnreplacedy> WhereOrStringContains<TEnreplacedy, String>
            (
            this IQueryable<TEnreplacedy> query,
            Expression<Func<TEnreplacedy, String>> selector,
            IEnumerable<String> values
            )
        {
            /*
             * 实现效果:
             * var tags = new[] { "A", "B", "C" };
             * SELECT * FROM [User] Where Name='Test' AND (Tags LIKE '%A%' Or Tags LIKE  '%B%')
             */

            if (selector == null)
            {
                throw new ArgumentNullException(nameof(selector));
            }
            if (values == null)
            {
                throw new ArgumentNullException(nameof(values));
            }

            if (!values.Any()) return query;

            ParameterExpression p = selector.Parameters.Single();
            var containsExpressions = values.Select(value => (Expression)Expression.Call(selector.Body, typeof(String).GetMethod("Contains", new[] { typeof(String) }), Expression.Constant(value)));
            Expression body = containsExpressions.Aggregate((acreplacedulate, containsExpression) => Expression.Or(acreplacedulate, containsExpression));

            return query.Where(Expression.Lambda<Func<TEnreplacedy, bool>>(body, p));
        }

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

static Func<T, Dictionary<string, string>> CompilePropertySerializer()
        {
            var o_t = typeof(T);
            var o = Expression.Parameter(o_t, "o");

            var d_t = typeof(Dictionary<string, string>);
            var d = Expression.Variable(d_t, "d");
            var d_init = Expression.MemberInit(Expression.New(d_t));
            var d_add = d_t.GetMethod("Add");
            var d_setters = o_t.GetProperties(BindingFlags.Public | BindingFlags.Instance) // build setters via Add(k,v)
                .Where(x => x.CanRead)
                .Select(x =>
                {
                    var prop = Expression.Property(o, x.Name);
                    var prop_mi_to_string = x.PropertyType.GetMethod("ToString", new Type[0]);
                    var add_to_dict = Expression.Call(d, d_add, Expression.Constant(x.Name), Expression.Call(prop, prop_mi_to_string));

                    if (!x.PropertyType.IsByRef)
                        return (Expression)add_to_dict;
                    else
                        return (Expression)Expression.IfThen(
                            Expression.Not(Expression.Equal(prop, Expression.Constant(null))),
                            add_to_dict);
                });

            // run this
            var body = Expression.Block(new[] { d }, // scope variables
                Expression.replacedign(d, d_init), // initialize
                Expression.Block(d_setters), // set
                d); // return

            return Expression.Lambda<Func<T, Dictionary<string, string>>>(body, o)
                .Compile();
        }

19 View Source File : CollisionGroupEntry.cs
License : Apache License 2.0
Project Creator : Algoryx

private void InvokeIdMethod( string method, object obj )
    {
      if ( obj == null )
        return;

      var m = obj.GetType().GetMethod( method, new Type[] { typeof( UInt32 ) } );
      if ( m == null )
        throw new Exception( "Method " + method + " not found in type: " + obj.GetType().FullName );
      m.Invoke( obj, new object[] { Tag.To32BitFnv1aHash() } );
    }

19 View Source File : PowerToolsIntegration.cs
License : Apache License 2.0
Project Creator : A7ocin

public static void Refresh(UMARecipeBase recipeBase)
		{
			var avatar = GetPreview(recipeBase).GetComponent<UMADynamicAvatar>();
			var persistance = GetPowerPackPersistanceType();
			SetAvatarDestroyParent(avatar, false);
			var hideAvatarMethod = persistance.GetMethod("HideAvatar", new Type[] { typeof(UMAAvatarBase) });
			var instance = GetPowerPackPersistanceInstance();
			hideAvatarMethod.Invoke(instance, new object[] { avatar });
			var showAvatarMethod = persistance.GetMethod("ShowAvatar", new Type[] { typeof(UMAAvatarBase) });
			showAvatarMethod.Invoke(instance, new object[] { avatar });
			SetAvatarDestroyParent(avatar, true);
			ReleasePowerPackPersistanceInstance(instance);
		}

19 View Source File : SyntaxTreeToQueryConvertor.cs
License : MIT License
Project Creator : alirezanet

private static MethodInfo GetStartWithMethod() => typeof(string).GetMethod("StartsWith", new[] { typeof(string) })

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 : SyntaxTreeToQueryConvertor.cs
License : MIT License
Project Creator : alirezanet

private static MethodInfo GetCompareMethodWithStringComparison() =>
         typeof(string).GetMethod("Compare", new[] { typeof(string), typeof(string), typeof(StringComparison) })

19 View Source File : CrmProfileProvider.cs
License : MIT License
Project Creator : Adoxio

private Expression<Func<Enreplacedy, bool>> CreateOrModifyWherePredicate(Expression<Func<Enreplacedy, bool>> wherePredicate, ProfileAuthenticationOption authenticationOption)
		{
			var isAnonymous = authenticationOption == ProfileAuthenticationOption.Anonymous;

			if (wherePredicate == null)
			{
				return enreplacedy => enreplacedy.GetAttributeValue<bool?>(_attributeMapIsAnonymous).GetValueOrDefault() == isAnonymous;
			}
			
			// Set the wherePredicate so that the clause is equivilant to:
			// enreplacedy => wherePreicate.Body && enreplacedy.GetAttributeValue<bool?>(_attributeMapIsAnonymous).GetValueOrDefault() == isAnonymous

			var enreplacedyParameter = wherePredicate.Parameters.Single();

			Expression getPropertyValue = Expression.Call(enreplacedyParameter, "GetPropertyValue", new[] { typeof(bool?) }, Expression.Constant(_attributeMapIsAnonymous));

			var left = Expression.Call(getPropertyValue, typeof(bool?).GetMethod("GetValueOrDefault", Type.EmptyTypes));

			var anonymousPredicateBody = Expression.Equal(left, Expression.Constant(isAnonymous));

			return Expression.Lambda<Func<Enreplacedy, bool>>(Expression.AndAlso(wherePredicate.Body, anonymousPredicateBody), enreplacedyParameter);
		}

19 View Source File : EHHelper.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private static bool BuildInternalPreserve(Type type)
        {
            try
            {
                const BindingFlags fl = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod;
                var at = (string) typeof(Environment).InvokeMember("GetResourceString", fl, null, null, new object[] {"Word_At"});

                var preserve = type.GetMethod("InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic);
                var field = type.GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic);
                var stackTrace = type.GetProperty("StackTrace", BindingFlags.Instance | BindingFlags.Public).GetGetMethod();
                var fmt = typeof(string).GetMethod("Format", new[] {typeof(string), typeof(object), typeof(object)});

                var dm = new DynamicMethod("", typeof(void), new[] {typeof(Exception), typeof(string), typeof(bool)}, true);
                var ilGen = dm.GetILGenerator();
                var lbl = ilGen.DefineLabel();
                var lbl2 = ilGen.DefineLabel();
                var lbl3 = ilGen.DefineLabel();

                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);

                ilGen.Emit(System.Reflection.Emit.OpCodes.Dup);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Dup);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldfld, field);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Brtrue, lbl2);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Callvirt, stackTrace);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Br, lbl3);
                ilGen.MarkLabel(lbl2);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldfld, field);
                ilGen.MarkLabel(lbl3);

                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);

                ilGen.Emit(System.Reflection.Emit.OpCodes.Call, preserve);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Stfld, field);

                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Brfalse, lbl);

                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_2);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Brtrue, lbl);

                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);

                ilGen.Emit(System.Reflection.Emit.OpCodes.Dup);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldstr,
                    "{1}" + Environment.NewLine + "   " + at + " DarksVM.Load() [{0}]" + Environment.NewLine);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldfld, field);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Call, fmt);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Stfld, field);


                ilGen.Emit(System.Reflection.Emit.OpCodes.Throw);

                ilGen.MarkLabel(lbl);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Throw);

                rethrow = (Throw) dm.CreateDelegate(typeof(Throw));
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex);
                return false;
            }
            return true;
        }

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 : Serializer.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

static Func<T, Dictionary<string, string>> CompileSerializer()
        {
            var o_t = typeof(T);
            var o = Expression.Parameter(o_t, "original");
            var o_get_object_data = o_t.GetMethod("GetObjectData");

            var d_t = typeof(Dictionary<string, string>);
            var d = Expression.Variable(d_t, "d"); // define object variable
            var d_init = Expression.MemberInit(Expression.New(d_t)); // object ctor
            var d_add = d_t.GetMethod("Add"); // add method

            var fc_t = typeof(LocalVariableInfo);
            var fc = Expression.Variable(fc_t, "fc");
            var fc_init = Expression.MemberInit(Expression.New(fc_t));

            var info_t = typeof(SerializationInfo);
            var info = Expression.Variable(info_t, "info");
            var info_ctor = info_t.GetConstructor(new[] { typeof(Type), fc_t });
            var info_init = Expression.MemberInit(Expression.New(info_ctor, Expression.Constant(o_t), fc));
            var info_get_enumerator = info_t.GetMethod("GetEnumerator");

            var ctx_t = typeof(StreamingContext);
            var ctx = Expression.Variable(ctx_t, "ctx");
            var ctx_init = Expression.MemberInit(Expression.New(ctx_t));

            var enumerator_t = typeof(SerializationInfoEnumerator);
            var enumerator = Expression.Variable(enumerator_t, "enumerator");
            var enumerator_move_next = enumerator_t.GetMethod("MoveNext");
            var enumerator_name = Expression.Property(enumerator, "Name");
            var enumerator_value = Expression.Property(enumerator, "Value");
            var mi_to_string = typeof(Object).GetMethod("ToString", new Type[0]);
            var exit_loop = Expression.Label("exit_loop");
            var body = Expression.Block(new[] { d, fc, info, ctx },
                Expression.replacedign(d, d_init),
                Expression.replacedign(fc, fc_init),
                Expression.replacedign(info, info_init),
                Expression.replacedign(ctx, ctx_init),
                Expression.Call(o, o_get_object_data, info, ctx),

                Expression.Block(new[] { enumerator },
                    Expression.replacedign(enumerator, Expression.Call(info, info_get_enumerator)),
                    Expression.Loop(
                        Expression.IfThenElse(
                            Expression.Call(enumerator, enumerator_move_next), // test
                            Expression.IfThen(
                                Expression.NotEqual(enumerator_value, Expression.Constant(null)),
                                Expression.Call(d, d_add, enumerator_name, Expression.Call(enumerator_value, mi_to_string))
                            ),
                            Expression.Break(exit_loop)), // if false
                        exit_loop)),
                d); // return

            // compile
            return Expression.Lambda<Func<T, Dictionary<string, string>>>(body, o)
                .Compile();
        }

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

async Task AddOrUpdateNavigateListAsync(TEnreplacedy item) {
			Type itemType = null;
			foreach (var prop in _table.Properties) {
				if (_table.ColumnsByCsIgnore.ContainsKey(prop.Key)) continue;
				if (_table.ColumnsByCs.ContainsKey(prop.Key)) continue;
				var tref = _table.GetTableRef(prop.Key, true);
				if (tref == null) continue;

				switch (tref.RefType) {
					case Internal.Model.TableRefType.OneToOne:
					case Internal.Model.TableRefType.ManyToOne:
					case Internal.Model.TableRefType.ManyToMany:
						continue;
					case Internal.Model.TableRefType.OneToMany:
						if (itemType == null) itemType = item.GetType();
						if (_table.TypeLazy != null && itemType == _table.TypeLazy) {
							var lazyField = _dicLazyIsSetField.GetOrAdd(_table.TypeLazy, tl => new ConcurrentDictionary<string, System.Reflection.FieldInfo>()).GetOrAdd(prop.Key, propName =>
								_table.TypeLazy.GetField($"__lazy__{propName}", System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance));
							if (lazyField != null) {
								var lazyFieldValue = (bool)lazyField.GetValue(item);
								if (lazyFieldValue == false) continue;
							}
						}
						var propVal = prop.Value.GetValue(item);
						var propValEach = propVal as IEnumerable;
						if (propValEach == null) continue;
						object dbset = null;
						System.Reflection.MethodInfo dbsetAddOrUpdate = null;
						foreach (var propValItem in propValEach) {
							if (dbset == null) {
								dbset = _ctx.Set(tref.RefEnreplacedyType);
								dbsetAddOrUpdate = dbset.GetType().GetMethod("AddOrUpdateAsync", new Type[] { tref.RefEnreplacedyType });
							}
							for (var colidx = 0; colidx < tref.Columns.Count; colidx++) {
								tref.RefColumns[colidx].Table.Properties[tref.RefColumns[colidx].CsName]
									.SetValue(propValItem, tref.Columns[colidx].Table.Properties[tref.Columns[colidx].CsName].GetValue(item));
							}
							Task task = dbsetAddOrUpdate.Invoke(dbset, new object[] { propValItem }) as Task;
							await task;
						}
						break;
				}
			}
		}

19 View Source File : DynamicUtils.cs
License : MIT License
Project Creator : akaskela

private static void CreateMemberCalls()
            {
                Type csharpArgumentInfoType = Type.GetType(CSharpArgumentInfoTypeName, true);
                Type csharpBinderFlagsType = Type.GetType(CSharpBinderFlagsTypeName, true);
                Type binderType = Type.GetType(BinderTypeName, true);

                Type csharpArgumentInfoTypeEnumerableType = typeof(IEnumerable<>).MakeGenericType(csharpArgumentInfoType);

                MethodInfo getMemberMethod = binderType.GetMethod("GetMember", new[] { csharpBinderFlagsType, typeof(string), typeof(Type), csharpArgumentInfoTypeEnumerableType });
                _getMemberCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(getMemberMethod);

                MethodInfo setMemberMethod = binderType.GetMethod("SetMember", new[] { csharpBinderFlagsType, typeof(string), typeof(Type), csharpArgumentInfoTypeEnumerableType });
                _setMemberCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(setMemberMethod);
            }

19 View Source File : AdminStore.cs
License : Apache License 2.0
Project Creator : Aguafrommars

private async Task PopulateSubEnreplacediesAsync(string path, TEnreplacedy enreplacedy)
        {
            var property = _enreplacedyType.GetProperty(path);
            var propertyType = property.PropertyType;
            
            if (propertyType.ImplementsGenericInterface(typeof(ICollection<>)))
            {
                var items = await GetSubItemsAsync(enreplacedy, propertyType).ConfigureAwait(false);
                property.SetValue(enreplacedy, items);
                return;
            }

            var navigationProperty = _enreplacedyType.GetProperty($"{path}Id");
            var parentId = navigationProperty.GetValue(enreplacedy) as string;
            var storeType = typeof(IAdminStore<>).MakeGenericType(propertyType);
            var subStore = _provider.GetRequiredService(storeType);
            var getMethod = storeType.GetMethod(nameof(IAdminStore<object>.GetAsync), new[] { typeof(string), typeof(GetRequest), typeof(CancellationToken) });

            var task = getMethod.Invoke(subStore, new[]
            {
                    parentId,
                    null,
                    null
                });
            await (task as Task).ConfigureAwait(false);
            var response = task.GetType().GetProperty(nameof(Task<object>.Result)).GetValue(task);
            property.SetValue(enreplacedy, response);
        }

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

private static MethodInfo GetConvOp (Type t1, Type t2)
        {
            lock (conv_ops_lock) {
                if (! conv_ops.ContainsKey (t1))
                    conv_ops.Add (t1, new Dictionary<Type, MethodInfo> ());
            }

            if (conv_ops[t1].ContainsKey (t2))
                return conv_ops[t1][t2];

            MethodInfo op = t1.GetMethod (
                "op_Implicit", new Type[] { t2 });

            lock (conv_ops_lock) {
                try {
                    conv_ops[t1].Add (t2, op);
                } catch (ArgumentException) {
                    return conv_ops[t1][t2];
                }
            }

            return op;
        }

19 View Source File : DefaultContractResolver.cs
License : MIT License
Project Creator : akaskela

private static void SetExtensionDataDelegates(JsonObjectContract contract, MemberInfo member)
        {
            JsonExtensionDataAttribute extensionDataAttribute = ReflectionUtils.GetAttribute<JsonExtensionDataAttribute>(member);
            if (extensionDataAttribute == null)
            {
                return;
            }

            Type t = ReflectionUtils.GetMemberUnderlyingType(member);

            Type dictionaryType;
            ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out dictionaryType);

            Type keyType = dictionaryType.GetGenericArguments()[0];
            Type valueType = dictionaryType.GetGenericArguments()[1];

            Type createdType;

            // change type to a clreplaced if it is the base interface so it can be instantiated if needed
            if (ReflectionUtils.IsGenericDefinition(t, typeof(IDictionary<,>)))
            {
                createdType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType);
            }
            else
            {
                createdType = t;
            }

            Func<object, object> getExtensionDataDictionary = JsonTypeReflector.ReflectionDelegateFactory.CreateGet<object>(member);

            if (extensionDataAttribute.ReadData)
            {
                Action<object, object> setExtensionDataDictionary = (ReflectionUtils.CanSetMemberValue(member, true, false))
                 ? JsonTypeReflector.ReflectionDelegateFactory.CreateSet<object>(member)
                 : null;
                Func<object> createExtensionDataDictionary = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor<object>(createdType);
                MethodInfo addMethod = t.GetMethod("Add", new[] { keyType, valueType });
                MethodCall<object, object> setExtensionDataDictionaryValue = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(addMethod);

                ExtensionDataSetter extensionDataSetter = (o, key, value) =>
                {
                    object dictionary = getExtensionDataDictionary(o);
                    if (dictionary == null)
                    {
                        if (setExtensionDataDictionary == null)
                        {
                            throw new JsonSerializationException("Cannot set value onto extension data member '{0}'. The extension data collection is null and it cannot be set.".FormatWith(CultureInfo.InvariantCulture, member.Name));
                        }

                        dictionary = createExtensionDataDictionary();
                        setExtensionDataDictionary(o, dictionary);
                    }

                    setExtensionDataDictionaryValue(dictionary, key, value);
                };

                contract.ExtensionDataSetter = extensionDataSetter;
            }

            if (extensionDataAttribute.WriteData)
            {
                Type enumerableWrapper = typeof(EnumerableDictionaryWrapper<,>).MakeGenericType(keyType, valueType);
                ConstructorInfo constructors = enumerableWrapper.GetConstructors().First();
                ObjectConstructor<object> createEnumerableWrapper = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(constructors);

                ExtensionDataGetter extensionDataGetter = o =>
                {
                    object dictionary = getExtensionDataDictionary(o);
                    if (dictionary == null)
                    {
                        return null;
                    }

                    return (IEnumerable<KeyValuePair<object, object>>)createEnumerableWrapper(dictionary);
                };

                contract.ExtensionDataGetter = extensionDataGetter;
            }

            contract.ExtensionDataValueType = valueType;
        }

19 View Source File : DotNetToJScript.cs
License : MIT License
Project Creator : 1y0n

static object BuildLoaderDelegateMscorlib(byte[] replacedembly)
        {
            Delegate res = Delegate.CreateDelegate(typeof(Converter<byte[], replacedembly>),
                replacedembly,
                typeof(replacedembly).GetMethod("Load", new Type[] { typeof(byte[]), typeof(byte[]) }));

            HeaderHandler d = new HeaderHandler(Convert.ToString);

            d = (HeaderHandler)Delegate.Combine(d, (Delegate)d.Clone());
            d = (HeaderHandler)Delegate.Combine(d, (Delegate)d.Clone());

            FieldInfo fi = typeof(MulticastDelegate).GetField("_invocationList", BindingFlags.NonPublic | BindingFlags.Instance);

            object[] invoke_list = d.GetInvocationList();
            invoke_list[1] = res;
            fi.SetValue(d, invoke_list);

            d = (HeaderHandler)Delegate.Remove(d, (Delegate)invoke_list[0]);
            d = (HeaderHandler)Delegate.Remove(d, (Delegate)invoke_list[2]);

            return d;
        }

19 View Source File : TypeRegister.cs
License : MIT License
Project Creator : Albeoris

public void RegisterreplacedemblyTypes()
        {
            try
            {
                _log.LogInfo("Registering replacedembly types...");

                MethodInfo registrator = typeof(ClreplacedInjector).GetMethod("RegisterTypeInIl2Cpp", new Type[0]);
                if (registrator == null)
                    throw new Exception("Cannot find method RegisterTypeInIl2Cpp.");
                
                replacedembly replacedembly = replacedembly.GetExecutingreplacedembly();
                Int32 count = RegisterTypes(replacedembly, registrator);
                
                _log.LogInfo($"{count} replacedembly types registered successfully.");
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to register replacedembly types.", ex);
            }
        }

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

internal static bool IsMethodOverriden(this Type type, Type baseType, string methodName, params Type[] parameters)
        {
            Debug.replacedert(type != null);
            Debug.replacedert(baseType != null);
            Debug.replacedert(methodName != null);

            return type.GetMethod(methodName, parameters)?.DeclaringType == baseType;
        }

19 View Source File : BaseNodeView.cs
License : MIT License
Project Creator : alelievr

public void Initialize(BaseGraphView owner, BaseNode node)
		{
			nodeTarget = node;
			this.owner = owner;

			if (!node.deletable)
				capabilities &= ~Capabilities.Deletable;
			// Note that the Renamable capability is useless right now as it haven't been implemented in Graphview
			if (node.isRenamable)
				capabilities |= Capabilities.Renamable;

			owner.computeOrderUpdated += ComputeOrderUpdatedCallback;
			node.onMessageAdded += AddMessageView;
			node.onMessageRemoved += RemoveMessageView;
			node.onPortsUpdated += a => schedule.Execute(_ => UpdatePortsForField(a)).ExecuteLater(0);

            styleSheets.Add(Resources.Load<StyleSheet>(baseNodeStyle));

            if (!string.IsNullOrEmpty(node.layoutStyle))
                styleSheets.Add(Resources.Load<StyleSheet>(node.layoutStyle));

			InitializeView();
			InitializePorts();
			InitializeDebug();

			// If the standard Enable method is still overwritten, we call it
			if (GetType().GetMethod(nameof(Enable), new Type[]{}).DeclaringType != typeof(BaseNodeView))
				ExceptionToLog.Call(() => Enable());
			else
				ExceptionToLog.Call(() => Enable(false));

			InitializeSettings();

			RefreshExpandedState();

			this.RefreshPorts();

			RegisterCallback<GeometryChangedEvent>(OnGeometryChanged);
			RegisterCallback<DetachFromPanelEvent>(e => ExceptionToLog.Call(Disable));
			OnGeometryChanged(null);
		}

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

public static Expression Call_WriteBuildInType(Expression value)
        {
            return Expression.Call(Par_Writer, typeof(BssomWriter).GetMethod(nameof(BssomWriter.WriteBuildInType), new Type[] { value.Type }), value);
            //return Expression.Call(Par_Writer, typeof(BssomWriter).GetMethod(nameof(BssomWriter.WriteBuildInType), instanceAndInternalFlag, null, new Type[] { value.Type }, null), value);
        }

19 View Source File : Reflection.cs
License : MIT License
Project Creator : alfa-laboratory

public static object ConvertObject(object obj, Type type)
        {
            var t = GetObjectType(type);

            if(obj == null)
            {
                return GetDefault(t);
            }

            if(t.IsEnum)
            {
                obj = Enum.Parse(t, obj is string value ? value : obj.ToString(), false);
            }

            if(t == typeof(string))
            {
                if(obj is string convertObject)
                {
                    return convertObject;
                }

                var mi = obj.GetType().GetMethods().SingleOrDefault(m => m.Name == "ToString" && !m.GetMethodParameters().Any());
                return mi?.Invoke(obj, Array.Empty<object>());
            }

            if((obj is string s) && t == typeof(char[]))
            {
                return s.Split();
            }

            if(t.IsArray)
            {
                if(obj is Array arrSrc)
                {
                    var arrDest = (Array)CreateArray(t.GetElementType(), arrSrc.Length);
                    Array.Copy(arrSrc, arrDest, arrSrc.Length);
                    return arrDest;
                }
            }

            if(t == typeof(object))
            {
                return obj;
            }

            if(obj is not string o)
            {
                return Convert.ChangeType(obj, t);
            }

            if(t == typeof(bool))
            {
                if(short.TryParse(o, out var i))
                {
                    return i != 0;
                }

                return bool.Parse(o);
            }

            if(t == typeof(decimal) || t == typeof(float))
            {
                var types = new[] { typeof(string), typeof(NumberStyles), typeof(IFormatProvider), t.MakeByRefType() };
                var args = new[] { o, NumberStyles.Any, new NumberFormatInfo { NumberDecimalSeparator = "," }, GetDefault(t) };

                if((bool)t.GetMethod("TryParse", types)?.Invoke(null, args)!)
                {
                    return args[3];
                }

                types = new[] { typeof(string), typeof(NumberStyles), typeof(IFormatProvider) };
                args = new object[] { o, NumberStyles.Any, new NumberFormatInfo { NumberDecimalSeparator = "." } };
                return t.GetMethod("Parse", types)?.Invoke(null, args);
            }

            if(t == typeof(long)
                || t == typeof(ulong)
                || t == typeof(int)
                || t == typeof(uint)
                || t == typeof(short)
                || t == typeof(ushort)
                || t == typeof(byte)
                || t == typeof(sbyte)
                || t == typeof(char))
            {
                return t.GetMethod("Parse", new[] { typeof(string) })?.Invoke(null, new object[] {o});
            }

            if(t == typeof(DateTime))
            {
                return DateTime.TryParse(o, CultureInfo.GetCultureInfo("ru-RU"), DateTimeStyles.replacedumeLocal, out var dt) ? dt : DateTime.Parse(o, CultureInfo.GetCultureInfo("en-US"), DateTimeStyles.replacedumeLocal);
            }

            return Convert.ChangeType(o, t);
        }

19 View Source File : PowerToolsIntegration.cs
License : Apache License 2.0
Project Creator : A7ocin

public static void Hide(UMARecipeBase recipeBase)
		{
			var avatar = GetPreview(recipeBase).GetComponent<UMADynamicAvatar>();
			var persistance = GetPowerPackPersistanceType();
			var hideAvatarMethod = persistance.GetMethod("HideAvatar", new Type[] { typeof(UMAAvatarBase) });
			var instance = GetPowerPackPersistanceInstance();
			hideAvatarMethod.Invoke(instance, new object[] { avatar });
			ReleasePowerPackPersistanceInstance(instance);
		}

19 View Source File : WindAndWaterParameters.cs
License : Apache License 2.0
Project Creator : Algoryx

private MethodInfo FindGetOrCreateMethod( Type argType )
    {
      var methodName = typeof( T ) == typeof( agxModel.HydrodynamicsParameters ) ?
                         "getOrCreateHydrodynamicsParameters" :
                         "getOrCreateAerodynamicsParameters";
      try {
        var getOrCreateMethod = typeof( agxModel.WindAndWaterController ).GetMethod( methodName, new Type[] { argType } );
        return getOrCreateMethod;
      }
      catch ( Exception e ) {
        Debug.LogException( e, this );
        return null;
      }
    }

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

static Func<Dictionary<string, string>, T> CompilePropertyDeserializer()
        {
            var o_t = typeof(T);
            var o = Expression.Variable(o_t, "o");
            var o_new = Expression.New(typeof(T));

            var d_t = typeof(Dictionary<string, string>);
            var d = Expression.Parameter(d_t, "d");
            var d_mi_try_get_value = d_t.GetMethod("TryGetValue");

            var item_t = typeof(String);
            var item = Expression.Variable(item_t, "item");

            var tc_t = typeof(TypeConverter);
            var tc = Expression.Variable(tc_t, "tc");
            var tc_mi_can_convert_from = tc_t.GetMethod("CanConvertFrom", new[] { typeof(Type) });
            var tc_mi_convert_from = tc_t.GetMethod("ConvertFrom", new[] { typeof(Object) });

            var td_t = typeof(TypeDescriptor);
            var td_mi_get_converter = td_t.GetMethod("GetConverter", new[] { typeof(Type) });

            var binds = o_t.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .Where(x => x.CanRead)
                .Select(x =>
                {
                    var value_t = x.PropertyType;
                    var value = Expression.Variable(value_t, "value");
                    var target = Expression.Label(x.PropertyType);

                    return Expression.Bind(x, Expression.Block(new[] { item, value },
                        Expression.replacedign(tc, Expression.Call(null, td_mi_get_converter, Expression.Constant(x.PropertyType))),
                        Expression.IfThen(
                            Expression.Call(d, d_mi_try_get_value, Expression.Constant(x.Name), item),
                            Expression.IfThen(
                                Expression.NotEqual(item, Expression.Constant(null)),
                                Expression.IfThen(
                                    Expression.Call(tc, tc_mi_can_convert_from, Expression.Constant(typeof(String))),
                                    Expression.Block(
                                        Expression.replacedign(value, Expression.Convert(Expression.Call(tc, tc_mi_convert_from, item), x.PropertyType)),
                                        Expression.Return(target, value, x.PropertyType))))),
                        Expression.Label(target, value)
                    ));
                }).ToArray();

            var body = Expression.Block(new[] { o, tc },
                Expression.MemberInit(o_new, binds)
            );

            return Expression.Lambda<Func<Dictionary<string, string>, T>>(body, d)
                .Compile();
        }

19 View Source File : SyntaxTreeToQueryConvertor.cs
License : MIT License
Project Creator : alirezanet

private static MethodInfo GetEndsWithMethod() => typeof(string).GetMethod("EndsWith", new[] { typeof(string) })

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

private static void ConvertValueToEnum(ILGenerator il, Type from, Type to, Type via)
        {
            MethodInfo op;
            if (from == (via ?? to))
            {
                il.Emit(OpCodes.Unbox_Any, to); // stack is now [target][target][typed-value]
            }
            else if ((op = GetOperator(from, to)) != null)
            {
                // this is handy for things like decimal <===> double
                il.Emit(OpCodes.Unbox_Any, from); // stack is now [target][target][data-typed-value]
                il.Emit(OpCodes.Call, op); // stack is now [target][target][typed-value]
            }
            else
            {
                bool handled = false;
                OpCode opCode = default;
                switch (Type.GetTypeCode(from))
                {
                    case TypeCode.Boolean:
                    case TypeCode.Byte:
                    case TypeCode.SByte:
                    case TypeCode.Int16:
                    case TypeCode.UInt16:
                    case TypeCode.Int32:
                    case TypeCode.UInt32:
                    case TypeCode.Int64:
                    case TypeCode.UInt64:
                    case TypeCode.Single:
                    case TypeCode.Double:
                        handled = true;
                        switch (Type.GetTypeCode(via ?? to))
                        {
                            case TypeCode.Byte:
                                opCode = OpCodes.Conv_Ovf_I1_Un; break;
                            case TypeCode.SByte:
                                opCode = OpCodes.Conv_Ovf_I1; break;
                            case TypeCode.UInt16:
                                opCode = OpCodes.Conv_Ovf_I2_Un; break;
                            case TypeCode.Int16:
                                opCode = OpCodes.Conv_Ovf_I2; break;
                            case TypeCode.UInt32:
                                opCode = OpCodes.Conv_Ovf_I4_Un; break;
                            case TypeCode.Boolean: // boolean is basically an int, at least at this level
                            case TypeCode.Int32:
                                opCode = OpCodes.Conv_Ovf_I4; break;
                            case TypeCode.UInt64:
                                opCode = OpCodes.Conv_Ovf_I8_Un; break;
                            case TypeCode.Int64:
                                opCode = OpCodes.Conv_Ovf_I8; break;
                            case TypeCode.Single:
                                opCode = OpCodes.Conv_R4; break;
                            case TypeCode.Double:
                                opCode = OpCodes.Conv_R8; break;
                            default:
                                handled = false;
                                break;
                        }
                        break;
                }
                if (handled)
                {
                    il.Emit(OpCodes.Unbox_Any, from); // stack is now [target][target][col-typed-value]
                    il.Emit(opCode); // stack is now [target][target][typed-value]
                    if (to == typeof(bool))
                    { // compare to zero; I checked "csc" - this is the trick it uses; nice
                        il.Emit(OpCodes.Ldc_I4_0);
                        il.Emit(OpCodes.Ceq);
                        il.Emit(OpCodes.Ldc_I4_0);
                        il.Emit(OpCodes.Ceq);
                    }
                }
                else
                {
                    il.Emit(OpCodes.Ldtoken, via ?? to); // stack is now [target][target][value][member-type-token]
                    il.EmitCall(OpCodes.Call, typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle)), null); // stack is now [target][target][value][member-type]
                    il.EmitCall(OpCodes.Call, typeof(Convert).GetMethod(nameof(Convert.ChangeType), new Type[] { typeof(object), typeof(Type) }), null); // stack is now [target][target][boxed-member-type-value]
                    il.Emit(OpCodes.Unbox_Any, to); // stack is now [target][target][typed-value]
                }
            }
        }

19 View Source File : SyntaxTreeToQueryConvertor.cs
License : MIT License
Project Creator : alirezanet

private static MethodInfo GetContainsMethod() => typeof(string).GetMethod("Contains", new[] { typeof(string) })

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

public static Expression Call_GetFormatterWithVerify(Expression resolver, Type formatterType)
        {
            return Expression.Call(null, typeof(FormatterResolverExtensions).GetMethod(nameof(FormatterResolverExtensions.GetFormatterWithVerify), new Type[] { typeof(IFormatterResolver) }).MakeGenericMethod(formatterType), resolver);
        }

19 View Source File : SyntaxTreeToQueryConvertor.cs
License : MIT License
Project Creator : alirezanet

private static MethodInfo GetToLowerMethod() => typeof(string).GetMethod("ToLower", new Type[] { })

19 View Source File : ChildrenCodeTemplate.cs
License : MIT License
Project Creator : adamant

public string ToStringWithCulture(object objectToConvert)
            {
                if ((objectToConvert == null))
                {
                    throw new global::System.ArgumentNullException("objectToConvert");
                }
                System.Type t = objectToConvert.GetType();
                System.Reflection.MethodInfo method = t.GetMethod("ToString", new System.Type[] {
                            typeof(System.IFormatProvider)});
                if ((method == null))
                {
                    return objectToConvert.ToString();
                }
                else
                {
                    return ((string)(method.Invoke(objectToConvert, new object[] {
                                this.formatProviderField })));
                }
            }

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

static Func<T, Dictionary<string, string>> CompileSerializer()
        {
            var o_t = typeof(T);
            var o = Expression.Parameter(o_t, "original");
            var o_get_object_data = o_t.GetMethod("GetObjectData");

            var d_t = typeof(Dictionary<string, string>);
            var d = Expression.Variable(d_t, "d"); // define object variable
            var d_init = Expression.MemberInit(Expression.New(d_t)); // object ctor
            var d_add = d_t.GetMethod("Add"); // add method

            var fc_t = typeof(IFormatterConverter);// typeof(LocalVariableInfo);
            var fc = Expression.Variable(fc_t, "fc");
            var fc_init = Expression.MemberInit(Expression.New(typeof(System.Runtime.Serialization.FormatterConverter))); //Expression.MemberInit(Expression.New(fc_t));

            var info_t = typeof(SerializationInfo);
            var info = Expression.Variable(info_t, "info");
            var info_ctor = info_t.GetConstructor(new[] { typeof(Type), fc_t });
            var info_init = Expression.MemberInit(Expression.New(info_ctor, Expression.Constant(o_t), fc));
            var info_get_enumerator = info_t.GetMethod("GetEnumerator");

            var ctx_t = typeof(StreamingContext);
            var ctx = Expression.Variable(ctx_t, "ctx");
            var ctx_init = Expression.MemberInit(Expression.New(ctx_t));

            var enumerator_t = typeof(SerializationInfoEnumerator);
            var enumerator = Expression.Variable(enumerator_t, "enumerator");
            var enumerator_move_next = enumerator_t.GetMethod("MoveNext");
            var enumerator_name = Expression.Property(enumerator, "Name");
            var enumerator_value = Expression.Property(enumerator, "Value");
            var mi_to_string = typeof(Object).GetMethod("ToString", new Type[0]);
            var exit_loop = Expression.Label("exit_loop");
            var body = Expression.Block(new[] { d, fc, info, ctx },
                Expression.replacedign(d, d_init),
                Expression.replacedign(fc, fc_init),
                Expression.replacedign(info, info_init),
                Expression.replacedign(ctx, ctx_init),
                Expression.Call(o, o_get_object_data, info, ctx),

                Expression.Block(new[] { enumerator },
                    Expression.replacedign(enumerator, Expression.Call(info, info_get_enumerator)),
                    Expression.Loop(
                        Expression.IfThenElse(
                            Expression.Call(enumerator, enumerator_move_next), // test
                            Expression.IfThen(
                                Expression.NotEqual(enumerator_value, Expression.Constant(null)),
                                Expression.Call(d, d_add, enumerator_name, Expression.Call(enumerator_value, mi_to_string))
                            ),
                            Expression.Break(exit_loop)), // if false
                        exit_loop)),
                d); // return

            // compile
            return Expression.Lambda<Func<T, Dictionary<string, string>>>(body, o)
                .Compile();
        }

19 View Source File : EntityMapperProvider.cs
License : Apache License 2.0
Project Creator : 1448376744

private Func<object, Dictionary<string, object>> CreateTypeDeserializerHandler(Type type)
        {
            var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            var methodName = $"{type.Name}Deserializer{Guid.NewGuid():N}";
            var dynamicMethod = new DynamicMethod(methodName, typeof(Dictionary<string, object>), new Type[] { typeof(object) }, type, true);
            var generator = dynamicMethod.GetILGenerator();
            LocalBuilder enreplacedyLocal1 = generator.DeclareLocal(typeof(Dictionary<string, object>));
            LocalBuilder enreplacedyLocal2 = generator.DeclareLocal(type);
            generator.Emit(OpCodes.Newobj, typeof(Dictionary<string, object>).GetConstructor(Type.EmptyTypes));
            generator.Emit(OpCodes.Stloc, enreplacedyLocal1);
            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(OpCodes.Castclreplaced, type);
            generator.Emit(OpCodes.Stloc, enreplacedyLocal2);
            foreach (var item in properties)
            {
                generator.Emit(OpCodes.Ldloc, enreplacedyLocal1);
                generator.Emit(OpCodes.Ldstr, item.Name);
                generator.Emit(OpCodes.Ldloc, enreplacedyLocal2);
                generator.Emit(OpCodes.Callvirt, item.GetGetMethod());
                if (item.PropertyType.IsValueType)
                {
                    generator.Emit(OpCodes.Box, item.PropertyType);
                }
                var addMethod = typeof(Dictionary<string, object>).GetMethod(nameof(Dictionary<string, object>.Add), new Type[] { typeof(string), typeof(object) });
                generator.Emit(OpCodes.Callvirt, addMethod);
            }
            generator.Emit(OpCodes.Ldloc, enreplacedyLocal1);
            generator.Emit(OpCodes.Ret);
            return dynamicMethod.CreateDelegate(typeof(Func<object, Dictionary<string, object>>)) as Func<object, Dictionary<string, object>>;
        }

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

public static Expression Call_WriteRaw(Expression value)
        {
            return Expression.Call(Par_Writer, typeof(BssomWriter).GetMethod(nameof(BssomWriter.WriteRaw), new Type[] { value.Type }), value);
        }

19 View Source File : DotNetToJScript.cs
License : MIT License
Project Creator : 1y0n

static object BuildLoaderDelegate(byte[] replacedembly)
        {
            // Create a bound delegate which will load our replacedembly from a byte array.
            Delegate res = Delegate.CreateDelegate(typeof(XmlValueGetter),
                replacedembly,
                typeof(replacedembly).GetMethod("Load", new Type[] { typeof(byte[]) }));

            // Create a COM invokable delegate to call the loader. Abuses contra-variance
            // to make an array of headers to an array of objects (which we'll just preplaced
            // null to anyway).
            return new HeaderHandler(res.DynamicInvoke);
        }

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

void AddOrUpdateNavigateList(TEnreplacedy item) {
			Type itemType = null;
			foreach (var prop in _table.Properties) {
				if (_table.ColumnsByCsIgnore.ContainsKey(prop.Key)) continue;
				if (_table.ColumnsByCs.ContainsKey(prop.Key)) continue;

				object propVal = null;

				if (itemType == null) itemType = item.GetType();
				if (_table.TypeLazy != null && itemType == _table.TypeLazy) {
					var lazyField = _dicLazyIsSetField.GetOrAdd(_table.TypeLazy, tl => new ConcurrentDictionary<string, FieldInfo>()).GetOrAdd(prop.Key, propName =>
						_table.TypeLazy.GetField($"__lazy__{propName}", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance));
					if (lazyField != null) {
						var lazyFieldValue = (bool)lazyField.GetValue(item);
						if (lazyFieldValue == false) continue;
					}
					propVal = prop.Value.GetValue(item);
				} else {
					propVal = prop.Value.GetValue(item);
					if (propVal == null) continue;
				}

				var tref = _table.GetTableRef(prop.Key, true);
				if (tref == null) continue;

				switch(tref.RefType) {
					case Internal.Model.TableRefType.OneToOne:
					case Internal.Model.TableRefType.ManyToOne:
					case Internal.Model.TableRefType.ManyToMany:
						continue;
					case Internal.Model.TableRefType.OneToMany:
						var propValEach = propVal as IEnumerable;
						if (propValEach == null) continue;
						object dbset = null;
						MethodInfo dbsetAddOrUpdate = null;
						foreach (var propValItem in propValEach) {
							if (dbset == null) {
								dbset = _ctx.Set(tref.RefEnreplacedyType);
								dbsetAddOrUpdate = dbset.GetType().GetMethod("AddOrUpdate", new Type[] { tref.RefEnreplacedyType });
							}
							for (var colidx = 0; colidx < tref.Columns.Count; colidx++) {
								tref.RefColumns[colidx].Table.Properties[tref.RefColumns[colidx].CsName]
									.SetValue(propValItem, tref.Columns[colidx].Table.Properties[tref.Columns[colidx].CsName].GetValue(item));
							}
							dbsetAddOrUpdate.Invoke(dbset, new object[] { propValItem });
						}
						break;
				}
			}
		}

19 View Source File : Main.cs
License : MIT License
Project Creator : AhmedMinegames

private void ObfuscasteCode(string ToProtect)
        {
            ModuleContext ModuleCont = ModuleDefMD.CreateModuleContext();
            ModuleDefMD FileModule = ModuleDefMD.Load(ToProtect, ModuleCont);
            replacedemblyDef replacedembly1 = FileModule.replacedembly;

            if (checkBox7.Checked)
            {
                foreach (var tDef in FileModule.Types)
                {
                    if (tDef == FileModule.GlobalType) continue;
                    foreach (var mDef in tDef.Methods)
                    {
                        if (mDef.Name.StartsWith("get_") || mDef.Name.StartsWith("set_")) continue;
                        if (!mDef.HasBody || mDef.IsConstructor) continue;
                        mDef.Body.SimplifyBranches();
                        mDef.Body.SimplifyMacros(mDef.Parameters);
                        var blocks = GetMethod(mDef);
                        var ret = new List<Block>();
                        foreach (var group in blocks)
                        {
                            Random rnd = new Random();
                            ret.Insert(rnd.Next(0, ret.Count), group);
                        }
                        blocks = ret;
                        mDef.Body.Instructions.Clear();
                        var local = new Local(mDef.Module.CorLibTypes.Int32);
                        mDef.Body.Variables.Add(local);
                        var target = Instruction.Create(OpCodes.Nop);
                        var instr = Instruction.Create(OpCodes.Br, target);
                        var instructions = new List<Instruction> { Instruction.Create(OpCodes.Ldc_I4, 0) };
                        foreach (var instruction in instructions)
                            mDef.Body.Instructions.Add(instruction);
                        mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Stloc, local));
                        mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Br, instr));
                        mDef.Body.Instructions.Add(target);
                        foreach (var block in blocks.Where(block => block != blocks.Single(x => x.Number == blocks.Count - 1)))
                        {
                            mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Ldloc, local));
                            var instructions1 = new List<Instruction> { Instruction.Create(OpCodes.Ldc_I4, block.Number) };
                            foreach (var instruction in instructions1)
                                mDef.Body.Instructions.Add(instruction);
                            mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Ceq));
                            var instruction4 = Instruction.Create(OpCodes.Nop);
                            mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Brfalse, instruction4));

                            foreach (var instruction in block.Instructions)
                                mDef.Body.Instructions.Add(instruction);

                            var instructions2 = new List<Instruction> { Instruction.Create(OpCodes.Ldc_I4, block.Number + 1) };
                            foreach (var instruction in instructions2)
                                mDef.Body.Instructions.Add(instruction);

                            mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Stloc, local));
                            mDef.Body.Instructions.Add(instruction4);
                        }
                        mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Ldloc, local));
                        var instructions3 = new List<Instruction> { Instruction.Create(OpCodes.Ldc_I4, blocks.Count - 1) };
                        foreach (var instruction in instructions3)
                            mDef.Body.Instructions.Add(instruction);
                        mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Ceq));
                        mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Brfalse, instr));
                        mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Br, blocks.Single(x => x.Number == blocks.Count - 1).Instructions[0]));
                        mDef.Body.Instructions.Add(instr);

                        foreach (var lastBlock in blocks.Single(x => x.Number == blocks.Count - 1).Instructions)
                            mDef.Body.Instructions.Add(lastBlock);
                    }
                }
            }

            if (checkBox2.Checked)
            {
                for (int i = 200; i < 300; i++)
                {
                    InterfaceImpl Interface = new InterfaceImplUser(FileModule.GlobalType);
                    TypeDef typedef = new TypeDefUser("", $"Form{i.ToString()}", FileModule.CorLibTypes.GetTypeRef("System", "Attribute"));
                    InterfaceImpl interface1 = new InterfaceImplUser(typedef);
                    FileModule.Types.Add(typedef);
                    typedef.Interfaces.Add(interface1);
                    typedef.Interfaces.Add(Interface);
                }
            }

            string[] FakeObfuscastionsAttributes = { "ConfusedByAttribute", "YanoAttribute", "NetGuard", "DotfuscatorAttribute", "BabelAttribute", "ObfuscatedByGoliath", "dotNetProtector" };
            if (checkBox5.Checked)
            {
                for (int i = 0; i < FakeObfuscastionsAttributes.Length; i++)
                {
                    var FakeObfuscastionsAttribute = new TypeDefUser(FakeObfuscastionsAttributes[i], FileModule.CorLibTypes.Object.TypeDefOrRef);
                    FileModule.Types.Add(FakeObfuscastionsAttribute);
                }
            }

            if (checkBox8.Checked)
            {
                foreach (TypeDef type in FileModule.Types)
                {
                    FileModule.Name = RandomName(12);
                    if (type.IsGlobalModuleType || type.IsRuntimeSpecialName || type.IsSpecialName || type.IsWindowsRuntime || type.IsInterface)
                    {
                        continue;
                    }
                    else
                    {
                        for (int i = 200; i < 300; i++)
                        {
                            foreach (PropertyDef property in type.Properties)
                            {
                                if (property.IsRuntimeSpecialName) continue;
                                property.Name = RandomName(20) + i + RandomName(10) + i;
                            }
                            foreach (FieldDef fields in type.Fields)
                            {
                                fields.Name = RandomName(20) + i + RandomName(10) + i;
                            }
                            foreach (EventDef eventdef in type.Events)
                            {
                                eventdef.Name = RandomName(20) + i + RandomName(10) + i;
                            }
                            foreach (MethodDef method in type.Methods)
                            {
                                if (method.IsConstructor || method.IsRuntimeSpecialName || method.IsRuntime || method.IsStaticConstructor || method.IsVirtual) continue;
                                method.Name = RandomName(20) + i + RandomName(10) + i;
                            }
                            foreach(MethodDef method in type.Methods)
                            {
                                foreach(Parameter RenameParameters in method.Parameters)
                                {
                                    RenameParameters.Name = RandomName(10);
                                }
                            }
                        }
                    }
                    foreach (ModuleDefMD module in FileModule.replacedembly.Modules)
                    {
                        module.Name = RandomName(13);
                        module.replacedembly.Name = RandomName(14);
                    }
                }

                foreach (TypeDef type in FileModule.Types)
                {
                    foreach (MethodDef GetMethods in type.Methods)
                    {
                        for (int i = 200; i < 300; i++)
                        {
                            if (GetMethods.IsConstructor || GetMethods.IsRuntimeSpecialName || GetMethods.IsRuntime || GetMethods.IsStaticConstructor) continue;
                            GetMethods.Name = RandomName(15) + i;
                        }
                    }
                }
            }

            if (checkBox6.Checked)
            {
                for (int i = 0; i < 200; i++)
                {
                    var Junk = new TypeDefUser(RandomName(10) + i + RandomName(10) + i + RandomName(10) + i, FileModule.CorLibTypes.Object.TypeDefOrRef);
                    FileModule.Types.Add(Junk);
                }

                for (int i = 0; i < 200; i++)
                {
                    var Junk = new TypeDefUser("<" + RandomName(10) + i + RandomName(10) + i + RandomName(10) + i + ">", FileModule.CorLibTypes.Object.TypeDefOrRef);
                    var Junk2 = new TypeDefUser(RandomName(11) + i + RandomName(11) + i + RandomName(11) + i, FileModule.CorLibTypes.Object.TypeDefOrRef);
                    FileModule.Types.Add(Junk);
                    FileModule.Types.Add(Junk2);
                }

                for (int i = 0; i < 200; i++)
                {
                    var Junk = new TypeDefUser("<" + RandomName(10) + i + RandomName(10) + i + RandomName(10) + i + ">", FileModule.CorLibTypes.Object.Namespace);
                    var Junk2 = new TypeDefUser(RandomName(11) + i + RandomName(11) + i + RandomName(11) + i, FileModule.CorLibTypes.Object.Namespace);
                    FileModule.Types.Add(Junk);
                    FileModule.Types.Add(Junk2);
                }
            }

            if (checkBox1.Checked)
            {
                foreach (TypeDef type in FileModule.Types)
                {
                    foreach (MethodDef method in type.Methods)
                    {
                        if (method.Body == null) continue;
                        method.Body.SimplifyBranches();
                        for (int i = 0; i < method.Body.Instructions.Count; i++)
                        {
                            if (method.Body.Instructions[i].OpCode == OpCodes.Ldstr)
                            {
                                string EncodedString = method.Body.Instructions[i].Operand.ToString();
                                string InsertEncodedString = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(EncodedString));
                                method.Body.Instructions[i].OpCode = OpCodes.Nop;
                                method.Body.Instructions.Insert(i + 1, new Instruction(OpCodes.Call, FileModule.Import(typeof(Encoding).GetMethod("get_UTF8", new Type[] { }))));
                                method.Body.Instructions.Insert(i + 2, new Instruction(OpCodes.Ldstr, InsertEncodedString));
                                method.Body.Instructions.Insert(i + 3, new Instruction(OpCodes.Call, FileModule.Import(typeof(Convert).GetMethod("FromBase64String", new Type[] { typeof(string) }))));
                                method.Body.Instructions.Insert(i + 4, new Instruction(OpCodes.Callvirt, FileModule.Import(typeof(Encoding).GetMethod("GetString", new Type[] { typeof(byte[]) }))));
                                i += 4;
                            }
                        }
                    }
                }
            }

            if (checkBox10.Checked)
            {
                foreach (var type in FileModule.GetTypes())
                {
                    if (type.IsGlobalModuleType) continue;
                    foreach (var method in type.Methods)
                    {
                        if (!method.HasBody) continue;
                        {
                            for (var i = 0; i < method.Body.Instructions.Count; i++)
                            {
                                if (!method.Body.Instructions[i].IsLdcI4()) continue;
                                var numorig = new Random(Guid.NewGuid().GetHashCode()).Next();
                                var div = new Random(Guid.NewGuid().GetHashCode()).Next();
                                var num = numorig ^ div;
                                var nop = OpCodes.Nop.ToInstruction();
                                var local = new Local(method.Module.ImportAsTypeSig(typeof(int)));
                                method.Body.Variables.Add(local);
                                method.Body.Instructions.Insert(i + 1, OpCodes.Stloc.ToInstruction(local));
                                method.Body.Instructions.Insert(i + 2, Instruction.Create(OpCodes.Ldc_I4, method.Body.Instructions[i].GetLdcI4Value() - sizeof(float)));
                                method.Body.Instructions.Insert(i + 3, Instruction.Create(OpCodes.Ldc_I4, num));
                                method.Body.Instructions.Insert(i + 4, Instruction.Create(OpCodes.Ldc_I4, div));
                                method.Body.Instructions.Insert(i + 5, Instruction.Create(OpCodes.Xor));
                                method.Body.Instructions.Insert(i + 6, Instruction.Create(OpCodes.Ldc_I4, numorig));
                                method.Body.Instructions.Insert(i + 7, Instruction.Create(OpCodes.Bne_Un, nop));
                                method.Body.Instructions.Insert(i + 8, Instruction.Create(OpCodes.Ldc_I4, 2));
                                method.Body.Instructions.Insert(i + 9, OpCodes.Stloc.ToInstruction(local));
                                method.Body.Instructions.Insert(i + 10, Instruction.Create(OpCodes.Sizeof, method.Module.Import(typeof(float))));
                                method.Body.Instructions.Insert(i + 11, Instruction.Create(OpCodes.Add));
                                method.Body.Instructions.Insert(i + 12, nop);
                                i += 12;
                            }
                            method.Body.SimplifyBranches();
                        }
                    }
                }
            }

            if (checkBox11.Checked)
            {
                foreach (ModuleDef module in FileModule.replacedembly.Modules)
                {
                    TypeRef attrRef = FileModule.CorLibTypes.GetTypeRef("System.Runtime.CompilerServices", "SuppressIldasmAttribute");
                    var ctorRef = new MemberRefUser(module, ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void), attrRef);
                    var attr = new CustomAttribute(ctorRef);
                    module.CustomAttributes.Add(attr);
                }
            }

            if (checkBox13.Checked)
            {
                // later
            }

            if (File.Exists(Environment.CurrentDirectory + @"\Obfuscasted.exe") == false)
            {
                File.Copy(ToProtect, Environment.CurrentDirectory + @"\Obfuscasted.exe");
                FileModule.Write(Environment.CurrentDirectory + @"\Obfuscasted.exe");
                if (checkBox12.Checked)
                {
                    string RandomreplacedemblyName = RandomName(12);
                    PackAndEncrypt(Environment.CurrentDirectory + @"\Obfuscasted.exe", Environment.CurrentDirectory + @"\" + RandomreplacedemblyName + ".tmp");
                    File.Delete(Environment.CurrentDirectory + @"\Obfuscasted.exe");
                    File.Move(Environment.CurrentDirectory + @"\" + RandomreplacedemblyName + ".tmp", Environment.CurrentDirectory + @"\Obfuscasted.exe");
                }
            }
            else
            {
                MessageBox.Show("Please Delete or move the file: " + Environment.CurrentDirectory + @"\Obfuscasted.exe" + " first to Obfuscaste your file", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
            }
        }

See More Examples