Here are the examples of the csharp api System.Type.GetMethod(string, System.Reflection.BindingFlags) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2080 Examples
19
View Source File : TerrariaHooksManager.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public static void Init() {
if (Initialized)
return;
Initialized = true;
Manager = new DetourModManager();
Manager.Ignored.Add(replacedembly.GetExecutingreplacedembly());
// Load the cecil module generator.
// Adding this more than once shouldn't hurt.
HookEndpointManager.OnGenerateCecilModule += GenerateCecilModule;
// Some mods might forget to undo their hooks.
HookOnUnloadContent = new Hook(
typeof(Mod).GetMethod("UnloadContent", BindingFlags.NonPublic | BindingFlags.Instance),
typeof(TerrariaHooksManager).GetMethod("OnUnloadContent", BindingFlags.NonPublic | BindingFlags.Static)
);
// All of our own hooks need to be undone last.
MethodBase m_Unload = typeof(ModLoader).GetMethod("Unload", BindingFlags.NonPublic | BindingFlags.Static);
if (m_Unload != null) {
HookOnUnloadAll = new Hook(
m_Unload,
typeof(TerrariaHooksManager).GetMethod("OnUnloadAll", BindingFlags.NonPublic | BindingFlags.Static)
);
} else {
/* The unofficial tML x64 form is a hot mess of tML 0.10 and 0.11 pre-beta.
* As such, mods are only unloaded when they're reloaded.
* Luckily, ModContnet.Unload runs right after unloading all mods.
* Even more luckily, it pretty much shares the same signature as the old Unload method.
*/
MethodBase m_UnloadContent =
typeof(Mod).replacedembly.GetType("Terraria.ModLoader.ModContent")
?.GetMethod("Unload", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
if (m_UnloadContent != null) {
HookOnUnloadAll = new Hook(
m_UnloadContent,
typeof(TerrariaHooksManager).GetMethod("OnUnloadAll", BindingFlags.NonPublic | BindingFlags.Static)
);
} else {
throw new Exception("Incompatible tML version: Can't find unload hook point");
}
}
// Try to hook the logger to avoid logging "silent" exceptions thrown by TerrariaHooks.
MethodBase m_LogSilentException =
typeof(Mod).replacedembly.GetType("Terraria.ModLoader.ModCompile+<>c")
?.GetMethod("<ActivateExceptionReporting>b__15_0", BindingFlags.NonPublic | BindingFlags.Instance);
if (m_LogSilentException != null) {
HookOnLogSilentException = new Hook(
m_LogSilentException,
typeof(TerrariaHooksManager).GetMethod("OnLogSilentException", BindingFlags.NonPublic | BindingFlags.Static)
);
}
}
19
View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static Expression Call_Reader_TryReadNullWithEnsureArray1BuildInType(byte code)
{
return Expression.Call(Par_Reader, typeof(BssomReader).GetMethod(nameof(BssomReader.TryReadNullWithEnsureArray1BuildInType), instanceAndInternalFlag), Expression.Constant(code, typeof(byte)));
}
19
View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static Expression Call_Reader_TryReadNullWithEnsureArray1NativeType(byte code)
{
return Expression.Call(Par_Reader, typeof(BssomReader).GetMethod(nameof(BssomReader.TryReadNullWithEnsureArray1NativeType), instanceAndInternalFlag), Expression.Constant(code, typeof(byte)));
}
19
View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static Expression Call_Reader_SeekAndSkipObject(Expression len)
{
return Expression.Call(Par_Reader, typeof(BssomReader).GetMethod(nameof(BssomReader.SeekAndSkipObject), instanceAndInternalFlag), len);
}
19
View Source File : Array3CodeGenResolver.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static TypeInfo Build(DynamicFormatterreplacedembly replacedembly, ObjectSerializationInfo serializationInfo)
{
Type type = serializationInfo.Type;
TypeBuilder typeBuilder = replacedembly.DefineFormatterType(type);
serializationInfo.SerializeMemberInfosOrderByKeyIndex(type);
MethodBuilder serializeMethod = TypeBuildHelper.DefineSerializeMethod(typeBuilder, type);
MethodBuilder deserializeMethod = TypeBuildHelper.DefineDeserializeMethod(typeBuilder, type);
MethodBuilder sizeMethod = TypeBuildHelper.DefineSizeMethod(typeBuilder, type);
Type delegateCacheType = typeof(Array3DelegateCache<>).MakeGenericType(type);
delegateCacheType.GetMethod(nameof(Array3DelegateCache<int>.Factory), BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, new object[] { replacedembly, serializationInfo });
TypeBuildHelper.CallSerializeDelegate(serializeMethod, type, delegateCacheType.GetField(nameof(Array3DelegateCache<int>.Serialize)));
TypeBuildHelper.CallSizeDelegate(sizeMethod, type, delegateCacheType.GetField(nameof(Array3DelegateCache<int>.Size)));
TypeBuildHelper.CallDeserializeDelegate(deserializeMethod, type, delegateCacheType.GetField(nameof(Array3DelegateCache<int>.Deserialize)));
return typeBuilder.CreateTypeInfo();
}
19
View Source File : ICollectionResolver.cs
License : MIT License
Project Creator : 1996v
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 : ICollectionResolver.cs
License : MIT License
Project Creator : 1996v
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 : ICollectionResolver.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
private static void GenerateDeserializeWithCore(bool isImplGenerICollec, Type itemType, Func<Expression, Expression> ctor)
{
/*
if (reader.TryReadNullWithEnsureArray1BuildInType(BssomType.Int8Code))/TryReadNullWithEnsureArray1NativeType(NativeBssomType.CharCode)/TryReadNullWithEnsureBuildInType(BssomType.Array2)
return default;
context.option.Security.DepthStep(ref reader);
reader.SkipVariableNumber();
int len = reader.ReadVariableNumber();
T t = new T(len);
Fill<T>(ref t,ref reader,ref context,len);
context.Depth--;
return t;
*/
bool isArray1Type = Array1FormatterHelper.IsArray1Type(itemType, out bool isNativeType, out byte typeCode, out string typeCodeName);
Type t = typeof(T);
List<Expression> ary = new List<Expression>(7);
LabelTarget returnTarget = Expression.Label(t, "returnLable");
if (isArray1Type)
{
if (isNativeType)
{
//if (reader.ryReadNullWithEnsureArray1NativeType(NativeType))
// goto label;
ary.Add(Expression.IfThen(CommonExpressionMeta.Call_Reader_TryReadNullWithEnsureArray1NativeType(typeCode), Expression.Return(returnTarget, Expression.Default(t))));
}
else
{
//if (reader.Call_Reader_TryReadNullWithEnsureArray1BuildInType(BuildInType))
// goto label;
ary.Add(Expression.IfThen(CommonExpressionMeta.Call_Reader_TryReadNullWithEnsureArray1BuildInType(typeCode), Expression.Return(returnTarget, Expression.Default(t))));
}
}
else
{
//if (reader.TryReadNullWithEnsureBuildInType(BssomType.Array2))
// goto label;
ary.Add(Expression.IfThen(CommonExpressionMeta.Call_Reader_TryReadNullWithEnsureBuildInType(BssomType.Array2), Expression.Return(returnTarget, Expression.Default(t))));
}
//context.option.Security.DepthStep(ref reader);
ary.Add(CommonExpressionMeta.Call_DeserializeContext_Option_Security_DepthStep);
//reader.SkipVariableNumber();
ary.Add(CommonExpressionMeta.Call_Reader_SkipVariableNumber);
//int len = reader.ReadVariableNumber();
ParameterExpression len = Expression.Variable(typeof(int));
ary.Add(Expression.replacedign(len, CommonExpressionMeta.Call_Reader_ReadVariableNumber));
//T t = ctor(len);
ParameterExpression instance = Expression.Variable(t);
ary.Add(Expression.replacedign(instance, ctor(len)));
MethodInfo method = null;
if (isImplGenerICollec == false)
{
//IColloctionFormatterHelper.Fill_ImplIList<T>(ref t,ref reader,ref context,len)
method = typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.Fill_ImplIList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(t);
}
else
{
if (isArray1Type)
{
//IColloctionFormatterHelper.Fill{TypeCodeName}<T>(ref t,ref reader,ref context,len)
method = typeof(Array1FormatterHelper).GetMethod(Array1FormatterHelper.FillPrefix + typeCodeName.ToString().Replace("Code", ""), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(t);
}
else
{
//IColloctionFormatterHelper.Fill_ImplICollection<T,TElement>(ref t,ref reader,ref context,len)
method = typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.Fill_ImplICollection), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(new Type[] { t, itemType });
}
}
ary.Add(Expression.Call(null, method, instance, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext, len));
//context.Depth--;
ary.Add(CommonExpressionMeta.Call_DeserializeContext_Depth_Decrementreplacedign);
//return t;
ary.Add(Expression.Return(returnTarget, instance));
//label default(T)
ary.Add(Expression.Label(returnTarget, instance));
BlockExpression block = Expression.Block(new ParameterExpression[] { instance, len }, ary);
Deserialize = Expression.Lambda<Deserialize<T>>(block, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext).Compile();
}
19
View Source File : IDictionaryResolver.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static TypeInfo BuildGenericIDictionaryInterfaceType(DynamicFormatterreplacedembly replacedembly, Type type, Type genericTypeDefine, Type genericKeyType, Type genericValueType)
{
DEBUG.replacedert(genericTypeDefine == typeof(IDictionary<,>) || genericTypeDefine == typeof(IReadOnlyDictionary<,>));
TypeBuilder typeBuilder = replacedembly.DefineFormatterType(type);
MethodBuilder serializeMethod = TypeBuildHelper.DefineSerializeMethod(typeBuilder, type);
TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.SerializeGenericDictionary), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(new Type[] { genericKeyType, genericValueType }));
MethodBuilder deserializeMethod = TypeBuildHelper.DefineDeserializeMethod(typeBuilder, type);
if (genericTypeDefine == typeof(IDictionary<,>))
{
TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.GenericDictionaryDeserialize), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(new Type[] { genericKeyType, genericValueType }));
}
else
{
TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.ReadOnlyGenericDictionaryDeserialize), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(new Type[] { genericKeyType, genericValueType }));
}
MethodBuilder sizeMethod = TypeBuildHelper.DefineSizeMethod(typeBuilder, type);
TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.SizeGenericDictionary), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(genericKeyType, genericValueType));
return typeBuilder.CreateTypeInfo();
}
19
View Source File : IDictionaryResolver.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static TypeInfo BuildGenericIDictionaryImplementationType(DynamicFormatterreplacedembly replacedembly, ConstructorInfo constructor, Type type, Type genericKeyType, Type genericValueType)
{
TypeBuilder typeBuilder = replacedembly.DefineFormatterType(type);
MethodBuilder serializeMethod = TypeBuildHelper.DefineSerializeMethod(typeBuilder, type);
TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.SerializeGenericDictionary), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(new Type[] { genericKeyType, genericValueType }));
MethodBuilder deserializeMethod = TypeBuildHelper.DefineDeserializeMethod(typeBuilder, type);
ParameterInfo[] args = constructor.GetParameters();
Type dynamicCacheType = typeof(IDictionaryDynamicDelegateCache<>).MakeGenericType(type);
if (args.Length == 0)
{
MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(IDictionaryDynamicDelegateCache<int>.GenerateDeserializeWithGenericDictEmptyCtor));
methodinfo.Invoke(null, new object[] { constructor, genericKeyType, genericValueType });
}
else
{
DEBUG.replacedert(args.Length == 1);
if (args[0].ParameterType == typeof(int))
{
MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(IDictionaryDynamicDelegateCache<int>.GenerateDeserializeWithGenericDictCapacityCtor));
methodinfo.Invoke(null, new object[] { constructor, genericKeyType, genericValueType });
}
else
{
MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(IDictionaryDynamicDelegateCache<int>.GenerateInjectCtor));
methodinfo.Invoke(null, new object[] { constructor, args[0].ParameterType });
}
}
TypeBuildHelper.CallDeserializeDelegate(deserializeMethod, type, dynamicCacheType.GetField(nameof(IDictionaryDynamicDelegateCache<int>.Deserialize), BindingFlags.Public | BindingFlags.Static));
MethodBuilder sizeMethod = TypeBuildHelper.DefineSizeMethod(typeBuilder, type);
TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.SizeGenericDictionary), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(genericKeyType, genericValueType));
return typeBuilder.CreateTypeInfo();
}
19
View Source File : IDictionaryResolver.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static TypeInfo BuildIDictionaryImplementationType(DynamicFormatterreplacedembly replacedembly, ConstructorInfo constructor, Type type)
{
TypeBuilder typeBuilder = replacedembly.DefineFormatterType(type);
MethodBuilder serializeMethod = TypeBuildHelper.DefineSerializeMethod(typeBuilder, type);
TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.SerializeIDictionary), BindingFlags.Public | BindingFlags.Static));
MethodBuilder deserializeMethod = TypeBuildHelper.DefineDeserializeMethod(typeBuilder, type);
ParameterInfo[] args = constructor.GetParameters();
Type dynamicCacheType = typeof(IDictionaryDynamicDelegateCache<>).MakeGenericType(type);
if (args.Length == 1)
{
DEBUG.replacedert(args[0].ParameterType == typeof(IDictionary));
//return new T(IDictionaryFormatter.Deserialize)
MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(IDictionaryDynamicDelegateCache<int>.GenerateInjectCtor));
methodinfo.Invoke(null, new object[] { constructor, args[0].ParameterType });
}
else
{
MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(IDictionaryDynamicDelegateCache<int>.GenerateDeserializeWithIDictionaryEmptyCtor));
methodinfo.Invoke(null, new object[] { });
}
TypeBuildHelper.CallDeserializeDelegate(deserializeMethod, type, dynamicCacheType.GetField(nameof(IDictionaryDynamicDelegateCache<int>.Deserialize), BindingFlags.Public | BindingFlags.Static));
MethodBuilder sizeMethod = TypeBuildHelper.DefineSizeMethod(typeBuilder, type);
TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.SizeIDictionary), BindingFlags.Public | BindingFlags.Static));
return typeBuilder.CreateTypeInfo();
}
19
View Source File : IDictionaryResolver.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
private static void GenerateDeserializeWithGenericDictCore(Type keyType, Type valueType, Func<MemberExpression, Expression> ctor)
{
/*
var map = MapFormatterHelper.Deserialize(ref reader,ref context);
if (map == null)
return null;
context.option.Security.DepthStep(ref reader);
T t = new T();/new T(map.Count)
Deserialize(IEnumerable<KeyValuePair<TKey, TValue>> pair,(ICollection<KeyValuePair<TKey, TValue>>)t);
reader = map.Reader; context = map.Context;
reader.Seek(map.EndPos);
context.Depth--;
return t;
*/
ArrayPack<Expression> ary = new ArrayPack<Expression>(10);
Type t = typeof(T);
LabelTarget returnTarget = Expression.Label(t, "returnLable");
ParameterExpression map = Expression.Variable(typeof(IMapDataSource<,>).MakeGenericType(keyType, valueType));
//map = MapFormatterHelper.Deserialize(ref reader,ref context);
ary.Add(Expression.replacedign(map, CommonExpressionMeta.Call_MapFormatterHelper_Deserialize(keyType, valueType)));
//if (map == null)
// goto label;
ary.Add(Expression.IfThen(Expression.Equal(map, Expression.Constant(null, map.Type)), Expression.Return(returnTarget, Expression.Default(t))));
//context.option.Security.DepthStep(ref reader);
ary.Add(CommonExpressionMeta.Call_DeserializeContext_Option_Security_DepthStep);
//T t = ctor(map.Count);
ParameterExpression instance = Expression.Variable(t);
ary.Add(Expression.replacedign(instance, ctor(Expression.Property(map, nameof(BssMapObjMarshalReader<int, int>.Count)))));
//MapFormatterHelper.FillData(map,(ICollection<KeyValuePair<TKey, TValue>>)t)
ary.Add(Expression.Call(null, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.FillGenericIDictionaryData), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(keyType, valueType), map, Expression.Convert(instance, typeof(ICollection<>).MakeGenericType(typeof(KeyValuePair<,>).MakeGenericType(keyType, valueType)))));
//reader = map.Reader; context = map.Context;
ary.Add(CommonExpressionMeta.Block_MapReaderAndContextreplacedignLocalReaderAndContext(map));
//reader.Seek(map.EndPos);
ary.Add(CommonExpressionMeta.Call_Reader_BufferSeek(Expression.Property(map, nameof(IMapDataSource<int, int>.EndPosition))));
//context.Depth--;
ary.Add(CommonExpressionMeta.Call_DeserializeContext_Depth_Decrementreplacedign);
//return t;
ary.Add(Expression.Return(returnTarget, instance));
//label default(T)
ary.Add(Expression.Label(returnTarget, instance));
BlockExpression block = Expression.Block(new ParameterExpression[] { map, instance }, ary.GetArray());
Deserialize = Expression.Lambda<Deserialize<T>>(block, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext).Compile();
}
19
View Source File : IDictionaryResolver.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static void GenerateDeserializeWithIDictionaryEmptyCtor()
{
/*
var map = MapFormatterHelper.Deserialize(ref reader,ref context);
if (map == null)
return null;
context.option.Security.DepthStep(ref reader);
T t = new T();
Deserialize(IEnumerable<KeyValuePair<TKey, TValue>> pair,(ICollection<KeyValuePair<TKey, TValue>>)t);
reader = map.Reader; context = map.Context;
reader.Seek(map.EndPos);
context.Depth--;
return t;
*/
ArrayPack<Expression> ary = new ArrayPack<Expression>(10);
Type t = typeof(T);
LabelTarget returnTarget = Expression.Label(t, "returnLable");
ParameterExpression map = Expression.Variable(typeof(IMapDataSource<,>).MakeGenericType(typeof(object), typeof(object)));
//map = MapFormatterHelper.Deserialize(ref reader,ref context);
ary.Add(Expression.replacedign(map, CommonExpressionMeta.Call_MapFormatterHelper_Deserialize(typeof(object), typeof(object))));
//if (map == null)
// goto label;
ary.Add(Expression.IfThen(Expression.Equal(map, Expression.Constant(null, map.Type)), Expression.Return(returnTarget, Expression.Default(t))));
//context.option.Security.DepthStep(ref reader);
ary.Add(CommonExpressionMeta.Call_DeserializeContext_Option_Security_DepthStep);
//T t = new T();
ParameterExpression instance = Expression.Variable(t);
ary.Add(Expression.replacedign(instance, Expression.New(t)));
//MapFormatterHelper.FillData(map,(IDictionary)t)
ary.Add(Expression.Call(null, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.FillIDictionaryData), BindingFlags.Public | BindingFlags.Static), map, Expression.Convert(instance, typeof(IDictionary))));
//reader = map.Reader; context = map.Context;
ary.Add(CommonExpressionMeta.Block_MapReaderAndContextreplacedignLocalReaderAndContext(map));
//reader.Seek(map.EndPos);
ary.Add(CommonExpressionMeta.Call_Reader_BufferSeek(Expression.Property(map, nameof(IMapDataSource<int, int>.EndPosition))));
//context.Depth--;
ary.Add(CommonExpressionMeta.Call_DeserializeContext_Depth_Decrementreplacedign);
//return t;
ary.Add(Expression.Return(returnTarget, instance));
//label default(T)
ary.Add(Expression.Label(returnTarget, instance));
BlockExpression block = Expression.Block(new ParameterExpression[] { map, instance }, ary.GetArray());
Deserialize = Expression.Lambda<Deserialize<T>>(block, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext).Compile();
}
19
View Source File : DataFilterUtil.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
internal static void SetRepositoryDataFilter(object repos, Action<FluentDataFilter> scopedDataFilter) {
if (scopedDataFilter != null) {
SetRepositoryDataFilter(repos, null);
}
if (scopedDataFilter == null) {
scopedDataFilter = _globalDataFilter;
}
if (scopedDataFilter == null) return;
using (var globalFilter = new FluentDataFilter()) {
scopedDataFilter(globalFilter);
var type = repos.GetType();
Type enreplacedyType = (repos as IBaseRepository).EnreplacedyType;
if (enreplacedyType == null) throw new Exception("FreeSql.Repository 设置过滤器失败,原因是对象不属于 IRepository");
var notExists = _dicSetRepositoryDataFilterConvertFilterNotExists.GetOrAdd(type, t => new ConcurrentDictionary<string, bool>());
var newFilter = new Dictionary<string, LambdaExpression>();
foreach (var gf in globalFilter._filters) {
if (notExists.ContainsKey(gf.name)) continue;
LambdaExpression newExp = null;
var filterParameter1 = Expression.Parameter(enreplacedyType, gf.exp.Parameters[0].Name);
try {
newExp = Expression.Lambda(
typeof(Func<,>).MakeGenericType(enreplacedyType, typeof(bool)),
new ReplaceVisitor().Modify(gf.exp.Body, filterParameter1),
filterParameter1
);
} catch {
notExists.TryAdd(gf.name, true); //防止第二次错误
continue;
}
newFilter.Add(gf.name, newExp);
}
if (newFilter.Any() == false) return;
var del = _dicSetRepositoryDataFilterApplyDataFilterFunc.GetOrAdd(type, t => {
var reposParameter = Expression.Parameter(type);
var nameParameter = Expression.Parameter(typeof(string));
var expressionParameter = Expression.Parameter(
typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(enreplacedyType, typeof(bool)))
);
return Expression.Lambda(
Expression.Block(
Expression.Call(reposParameter, type.GetMethod("ApplyDataFilter", BindingFlags.Instance | BindingFlags.NonPublic), nameParameter, expressionParameter)
),
new[] {
reposParameter, nameParameter, expressionParameter
}
).Compile();
});
foreach (var nf in newFilter) {
del.DynamicInvoke(repos, nf.Key, nf.Value);
}
newFilter.Clear();
}
}
19
View Source File : Helpers.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
internal static MethodInfo GetInstanceMethod(Type declaringType, string name)
{
return declaringType.GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
}
19
View Source File : Helpers.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
internal static MethodInfo GetStaticMethod(Type declaringType, string name)
{
return declaringType.GetMethod(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
}
19
View Source File : Helpers.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
private static Func<RuntimeMethodHandle, IntPtr> MakeGetFunctionPointer()
{
// Generate the "GetFunctionPointer" delegate.
DynamicMethod getFunctionPointer = new DynamicMethod(
nameof(GetFunctionPointer),
typeof(IntPtr),
new[] { typeof(RuntimeMethodHandle) },
typeof(RuntimeMethodHandle), true);
ILGenerator il = getFunctionPointer.GetILGenerator(16);
il.Emit(OpCodes.Ldarga_S, (short)0);
il.Emit(OpCodes.Call, typeof(RuntimeMethodHandle).GetMethod(nameof(GetFunctionPointer), PUBLIC_INSTANCE));
il.Emit(OpCodes.Ret);
return getFunctionPointer.CreateDelegate(typeof(Func<RuntimeMethodHandle, IntPtr>))
as Func<RuntimeMethodHandle, IntPtr>;
}
19
View Source File : Helpers.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
private static Func<DynamicMethod, RuntimeMethodHandle> MakeFindMethodHandleOfDynamicMethod()
{
// Generate the "FindMethodHandleOfDynamicMethod" delegate.
DynamicMethod findMethodHandle = new DynamicMethod(
nameof(FindMethodHandleOfDynamicMethod),
typeof(RuntimeMethodHandle),
new[] { typeof(DynamicMethod) },
typeof(DynamicMethod), true);
ILGenerator il = findMethodHandle.GetILGenerator(16);
il.Emit(OpCodes.Ldarg_0);
MethodInfo getMethodDescriptor = typeof(DynamicMethod)
.GetMethod("GetMethodDescriptor", NON_PUBLIC_INSTANCE);
if (getMethodDescriptor != null)
{
il.Emit(OpCodes.Callvirt, getMethodDescriptor);
}
else
{
FieldInfo handleField = typeof(DynamicMethod).GetField("m_method", NON_PUBLIC_INSTANCE)
?? typeof(DynamicMethod).GetField("mhandle", NON_PUBLIC_INSTANCE)
?? typeof(DynamicMethod).GetField("m_methodHandle", NON_PUBLIC_INSTANCE);
il.Emit(OpCodes.Ldfld, handleField);
}
il.Emit(OpCodes.Ret);
return findMethodHandle.CreateDelegate(typeof(Func<DynamicMethod, RuntimeMethodHandle>))
as Func<DynamicMethod, RuntimeMethodHandle>;
}
19
View Source File : Redirection.Reactive.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
private static MethodRedirection CreateDynamicRedirection(MethodBase method, out int id)
{
// Make id
do
{
id = ObservingRedirectionsIdGenerator.Next();
}
while (ObservingRedirections.ContainsKey(id));
// Creates an array containing all parameter types
int diff = method.IsStatic ? 0 : 1;
ParameterInfo[] originalParameters = method.GetParameters();
Type[] originalParameterTypes = new Type[originalParameters.Length + diff];
if (diff == 1 /* !method.IsStatic */)
originalParameterTypes[0] = method.DeclaringType;
for (int i = 0; i < originalParameters.Length; i++)
{
originalParameterTypes[i + diff] = originalParameters[i].ParameterType;
}
// Create an identical method
bool isCtor = method is ConstructorInfo;
Type returnType = isCtor ? typeof(void) : ((MethodInfo)method).ReturnType;
DynamicMethod dyn = new DynamicMethod(
name: method.Name,
attributes: MethodAttributes.Public | MethodAttributes.Static,
callingConvention: CallingConventions.Standard,
returnType: returnType,
parameterTypes: originalParameterTypes,
owner: method.DeclaringType,
skipVisibility: true);
// Make the method call the observable
ILGenerator il = dyn.GetILGenerator();
{
// This is in a block to make every more readable,
// the following comments describe what's happening in the generated method.
// Emit "this", or "null"
if (method.IsStatic)
{
il.Emit(OpCodes.Ldnull);
}
else
{
il.Emit(OpCodes.Ldarg_0);
if (method.DeclaringType.GetTypeInfo().IsValueType)
{
il.Emit(OpCodes.Ldobj, method.DeclaringType);
il.Emit(OpCodes.Box, method.DeclaringType);
}
}
// Create an array containing all parameters
il.Emit(OpCodes.Ldc_I4, originalParameters.Length);
il.Emit(OpCodes.Newarr, typeof(object));
for (int i = 0; i < originalParameters.Length; i++)
{
il.Emit(OpCodes.Dup);
il.Emit(OpCodes.Ldc_I4, i);
il.Emit(OpCodes.Ldarg, i + diff);
Type parameterType = originalParameterTypes[i + diff];
if (parameterType.GetTypeInfo().IsValueType)
il.Emit(OpCodes.Box, parameterType);
il.Emit(OpCodes.Stelem_Ref);
}
// Array is still on stack (thanks to dup)
// Emit id
il.Emit(OpCodes.Ldc_I4, id);
// Call "hook" method
il.Emit(OpCodes.Call, typeof(Redirection).GetMethod(nameof(OnInvoked), BindingFlags.Static | BindingFlags.NonPublic));
// Return returned result
// (But first, cast it if needed)
if (returnType == typeof(void))
il.Emit(OpCodes.Pop);
else if (returnType.GetTypeInfo().IsValueType)
il.Emit(OpCodes.Unbox_Any, returnType);
else if (returnType != typeof(object))
il.Emit(OpCodes.Castclreplaced, returnType);
il.Emit(OpCodes.Ret);
}
// Return the redirection
return new MethodRedirection(method, dyn, false);
}
19
View Source File : Ryder.Lightweight.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
private static Func<DynamicMethod, RuntimeMethodHandle> MakeFindMethodHandleOfDynamicMethod()
{
// Generate the "FindMethodHandleOfDynamicMethod" delegate.
DynamicMethod findMethodHandle = new DynamicMethod(
nameof(FindMethodHandleOfDynamicMethod),
typeof(RuntimeMethodHandle),
new[] { typeof(DynamicMethod) },
typeof(DynamicMethod), true);
ILGenerator il = findMethodHandle.GetILGenerator(16);
il.Emit(OpCodes.Ldarg_0);
MethodInfo getMethodDescriptor = typeof(DynamicMethod)
.GetMethod("GetMethodDescriptor", NON_PUBLIC_INSTANCE);
if (getMethodDescriptor != null)
{
il.Emit(OpCodes.Callvirt, getMethodDescriptor);
}
else
{
FieldInfo handleField = typeof(DynamicMethod).GetField("m_method", NON_PUBLIC_INSTANCE)
?? typeof(DynamicMethod).GetField("mhandle", NON_PUBLIC_INSTANCE)
?? typeof(DynamicMethod).GetField("m_methodHandle", NON_PUBLIC_INSTANCE);
il.Emit(OpCodes.Ldfld, handleField);
}
il.Emit(OpCodes.Ret);
return findMethodHandle.CreateDelegate(typeof(Func<DynamicMethod, RuntimeMethodHandle>))
as Func<DynamicMethod, RuntimeMethodHandle>;
}
19
View Source File : Ryder.Lightweight.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
private static Func<RuntimeMethodHandle, IntPtr> MakeGetFunctionPointer()
{
// Generate the "GetFunctionPointer" delegate.
DynamicMethod getFunctionPointer = new DynamicMethod(
nameof(GetFunctionPointer),
typeof(IntPtr),
new[] { typeof(RuntimeMethodHandle) },
typeof(RuntimeMethodHandle), true);
ILGenerator il = getFunctionPointer.GetILGenerator(16);
il.Emit(OpCodes.Ldarga_S, (short)0);
il.Emit(OpCodes.Call, typeof(RuntimeMethodHandle).GetMethod(nameof(GetFunctionPointer), PUBLIC_INSTANCE));
il.Emit(OpCodes.Ret);
return getFunctionPointer.CreateDelegate(typeof(Func<RuntimeMethodHandle, IntPtr>))
as Func<RuntimeMethodHandle, IntPtr>;
}
19
View Source File : HelpersTests.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
[Fact(Skip = "Inlining behavior is not understood enough.")]
public void TestInlinedMethods()
{
MethodInfo inlinedMethod = GetType().GetMethod(nameof(LikelyInlined), BindingFlags.Static | BindingFlags.Public);
MethodInfo nonInlinedMethod = GetType().GetMethod(nameof(UnlikelyInlined), BindingFlags.Static | BindingFlags.Public);
IntPtr inlinedStart = inlinedMethod.GetRuntimeMethodHandle().GetMethodStart();
IntPtr nonInlinedStart = nonInlinedMethod.GetRuntimeMethodHandle().GetMethodStart();
// IntPtr inlinedTarget = inlinedStart + Marshal.ReadInt32(inlinedStart + 1) + 5;
// IntPtr nonInlinedTarget = nonInlinedStart + Marshal.ReadInt32(nonInlinedStart + 1) + 5;
// byte[] inl = new byte[16];
// byte[] noinl = new byte[16];
// Marshal.Copy(inlinedTarget, inl, 0, 16);
// Marshal.Copy(nonInlinedTarget, noinl, 0, 16);
inlinedStart.HasBeenCompiled().ShouldBeFalse();
nonInlinedStart.HasBeenCompiled().ShouldBeFalse();
LikelyInlined().ShouldBe(UnlikelyInlined());
// I tried testing inlining after some operations, but
// the results all change depending on the configuration, and i don't wanna mess with this.
}
19
View Source File : ReactiveTests.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
[Fact]
public void TestInstanceRedirection()
{
MethodInfo method = typeof(TestClreplaced)
.GetMethod(nameof(TestClreplaced.ComputeHash), BindingFlags.Instance | BindingFlags.Public);
const int SEED = 0xEA6C23;
TestClreplaced test = new TestClreplaced(SEED);
string testStr = "42";
int testHash = testStr.GetHashCode();
test.ComputeHash(testStr).ShouldBe(unchecked(testHash * SEED));
test.ComputeHash(testStr).ShouldNotBe(SEED);
using (Redirection.Observe(method, ctx => ctx.ReturnValue = ((TestClreplaced)ctx.Sender).Seed))
{
test.ComputeHash(testStr).ShouldBe(SEED);
}
test.ComputeHash(testStr).ShouldBe(unchecked(testHash * SEED));
}
19
View Source File : Object.Extension.cs
License : MIT License
Project Creator : 7Bytes-Studio
License : MIT License
Project Creator : 7Bytes-Studio
public static object Invoke(this object instance, string methodName, params object[] args)
{
if (null == instance) return null;
var type = instance.GetType();
var key = type.FullName + methodName;
var bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static;
if (!s_MethodInfoDic.ContainsKey(key))
{
s_MethodInfoDic.Add(key, type.GetMethod(methodName, bindingFlags));
}
return s_MethodInfoDic[key].Invoke(instance,args);
}
19
View Source File : Utility.Reflection.cs
License : MIT License
Project Creator : 7Bytes-Studio
License : MIT License
Project Creator : 7Bytes-Studio
public static void Invoke(Type type,string methodName,params object[] args)
{
BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public;
var method = type.GetMethod(methodName,bindingFlags);
method.Invoke(null,args);
}
19
View Source File : PowerToolsIntegration.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
private static UnityEngine.Object GetPowerPackPersistanceInstance()
{
var method = GetPowerPackPersistanceType().GetMethod("GetInstance", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
return method.Invoke(null, null) as UnityEngine.Object;
}
19
View Source File : VxFormColumnBase.cs
License : MIT License
Project Creator : Aaltuj
License : MIT License
Project Creator : Aaltuj
public RenderFragment CreateFormElement() => builder =>
{
if (FormColumnDefinition.Model.GetType() == typeof(ExpandoObject))
{
// Accesing a ExpandoObject requires to cast the model as a dictionary, so it's accesable by a key of type string
var accessor = ((IDictionary<string, object>)FormColumnDefinition.Model);
foreach (var key in accessor.Keys)
{
// get the value of the object
var value = accessor[key];
// Get the generic CreateFormComponent and set the property type of the model and the elementType that is rendered
MethodInfo method = typeof(VxFormColumnBase).GetMethod(nameof(VxFormColumnBase.CreateFormElementReferenceExpando), BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo genericMethod = method.MakeGenericMethod(value.GetType());
// Execute the method with the following parameters
genericMethod.Invoke(this, new object[] { accessor, key, builder, FormColumnDefinition });
}
}
else // replacedume it's a regular clreplaced, could be tighter scoped
{
var propertyFormElement = FormColumnDefinition.Model.GetType().GetProperty(FormColumnDefinition.Name);
// Get the generic CreateFormComponent and set the property type of the model and the elementType that is rendered
MethodInfo method = typeof(VxFormColumnBase).GetMethod(nameof(VxFormColumnBase.CreateFormElementReferencePoco), BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo genericMethod = method.MakeGenericMethod(propertyFormElement.PropertyType);
// Execute the method with the following parameters
genericMethod.Invoke(this, new object[] { FormColumnDefinition.Model, propertyFormElement, builder, FormColumnDefinition });
}
};
19
View Source File : FormElementBase.cs
License : MIT License
Project Creator : Aaltuj
License : MIT License
Project Creator : Aaltuj
private void CheckForInterfaceActions(object target,
object dataContext,
string fieldIdentifier, RenderTreeBuilder builder, int indexBuilder, Type elementType)
{
// Check if the component has the IRenderChildren and renderen them in the form control
if (VxHelpers.TypeImplementsInterface(elementType, typeof(IRenderChildren)))
{
var method = elementType.GetMethod(nameof(IRenderChildren.RenderChildren), BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Static);
method.Invoke(null, new object[] { builder, indexBuilder, dataContext, fieldIdentifier });
}
}
19
View Source File : OCFactionManager.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public static void AddNewFaction(FactionOnline factionOnline)
{
FactionDef facDef = DefDatabase<FactionDef>.GetNamed(factionOnline.DefName);
Faction faction = new Faction();
faction.def = facDef;
faction.loadID = factionOnline.loadID;
faction.colorFromSpectrum = FactionGenerator.NewRandomColorFromSpectrum(faction);
faction.Name = factionOnline.Name;
faction.centralMelanin = Rand.Value;
foreach (Faction current in Find.FactionManager.AllFactionsListForReading)
{
faction.TryMakeInitialRelationsWith(current);
}
faction.TryGenerateNewLeader();
Find.FactionManager.Add(faction);
typeof(FactionManager).GetMethod("RecacheFactions", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Invoke(Find.FactionManager, null);
}
19
View Source File : ContextIsolatedTask.cs
License : Microsoft Public License
Project Creator : AArnott
License : Microsoft Public License
Project Creator : AArnott
private bool ExecuteInnerTask(object innerTask)
{
Type innerTaskType = innerTask.GetType();
Type innerTaskBaseType = innerTaskType;
while (innerTaskBaseType.FullName != typeof(ContextIsolatedTask).FullName)
{
innerTaskBaseType = innerTaskBaseType.GetTypeInfo().BaseType;
}
var outerProperties = this.GetType().GetRuntimeProperties().ToDictionary(i => i.Name);
var innerProperties = innerTaskType.GetRuntimeProperties().ToDictionary(i => i.Name);
var propertiesDiscovery = from outerProperty in outerProperties.Values
where outerProperty.SetMethod != null && outerProperty.GetMethod != null
let innerProperty = innerProperties[outerProperty.Name]
select new { outerProperty, innerProperty };
var propertiesMap = propertiesDiscovery.ToArray();
var outputPropertiesMap = propertiesMap.Where(pair => pair.outerProperty.GetCustomAttribute<OutputAttribute>() != null).ToArray();
foreach (var propertyPair in propertiesMap)
{
object outerPropertyValue = propertyPair.outerProperty.GetValue(this);
propertyPair.innerProperty.SetValue(innerTask, outerPropertyValue);
}
// Forward any cancellation requests
MethodInfo innerCancelMethod = innerTaskType.GetMethod(nameof(Cancel));
using (this.CancellationToken.Register(() => innerCancelMethod.Invoke(innerTask, new object[0])))
{
this.CancellationToken.ThrowIfCancellationRequested();
// Execute the inner task.
var executeInnerMethod = innerTaskType.GetMethod(nameof(ExecuteIsolated), BindingFlags.Instance | BindingFlags.NonPublic);
bool result = (bool)executeInnerMethod.Invoke(innerTask, new object[0]);
// Retrieve any output properties.
foreach (var propertyPair in outputPropertiesMap)
{
propertyPair.outerProperty.SetValue(this, propertyPair.innerProperty.GetValue(innerTask));
}
return result;
}
}
19
View Source File : PrefixWriter.cs
License : MIT License
Project Creator : Abc-Arbitrage
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 : FdbTuplePackers.cs
License : MIT License
Project Creator : abdullin
License : MIT License
Project Creator : abdullin
private static Delegate GetSerializerFor([NotNull] Type type)
{
if (type == null) throw new ArgumentNullException("type");
if (type == typeof(object))
{ // return a generic serializer that will inspect the runtime type of the object
return new Encoder<object>(FdbTuplePackers.SerializeObjectTo);
}
var typeArgs = new[] { typeof(TupleWriter).MakeByRefType(), type };
var method = typeof(FdbTuplePackers).GetMethod("SerializeTo", BindingFlags.Static | BindingFlags.Public, null, typeArgs, null);
if (method != null)
{ // we have a direct serializer
return method.CreateDelegate(typeof(Encoder<>).MakeGenericType(type));
}
// maybe if it is a tuple ?
if (typeof(IFdbTuple).IsreplacedignableFrom(type))
{
method = typeof(FdbTuplePackers).GetMethod("SerializeTupleTo", BindingFlags.Static | BindingFlags.Public);
if (method != null)
{
return method.MakeGenericMethod(type).CreateDelegate(typeof(Encoder<>).MakeGenericType(type));
}
}
if (typeof(ITupleFormattable).IsreplacedignableFrom(type))
{
method = typeof(FdbTuplePackers).GetMethod("SerializeFormattableTo", BindingFlags.Static | BindingFlags.Public);
if (method != null)
{
return method.CreateDelegate(typeof(Encoder<>).MakeGenericType(type));
}
}
if (typeof(IFdbKey).IsreplacedignableFrom(type))
{
method = typeof(FdbTuplePackers).GetMethod("SerializeFdbKeyTo", BindingFlags.Static | BindingFlags.Public);
if (method != null)
{
return method.CreateDelegate(typeof(Encoder<>).MakeGenericType(type));
}
}
var nullableType = Nullable.GetUnderlyingType(type);
if (nullableType != null)
{ // nullable types can reuse the underlying type serializer
method = typeof(FdbTuplePackers).GetMethod("SerializeNullableTo", BindingFlags.Static | BindingFlags.Public);
if (method != null)
{
return method.MakeGenericMethod(nullableType).CreateDelegate(typeof(Encoder<>).MakeGenericType(type));
}
}
// TODO: look for a static SerializeTo(BWB, T) method on the type itself ?
// no luck..
return null;
}
19
View Source File : FdbTuplePackers.cs
License : MIT License
Project Creator : abdullin
License : MIT License
Project Creator : abdullin
private static Delegate MakeNullableDeserializer([NotNull] Type nullableType, [NotNull] Type type, [NotNull] Delegate decoder)
{
Contract.Requires(nullableType != null && type != null && decoder != null);
// We have a Decoder of T, but we have to transform it into a Decoder for Nullable<T>, which returns null if the slice is "nil", or falls back to the underlying decoder if the slice contains something
var prmSlice = Expression.Parameter(typeof(Slice), "slice");
var body = Expression.Condition(
// IsNilSegment(slice) ?
Expression.Call(typeof(FdbTuplePackers).GetMethod("IsNilSegment", BindingFlags.Static | BindingFlags.NonPublic), prmSlice),
// True => default(Nullable<T>)
Expression.Default(nullableType),
// False => decoder(slice)
Expression.Convert(Expression.Invoke(Expression.Constant(decoder), prmSlice), nullableType)
);
return Expression.Lambda(body, prmSlice).Compile();
}
19
View Source File : MixedRealityOptimizeUtils.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
public static SerializedObject GetLightmapSettings()
{
var getLightmapSettingsMethod = typeof(LightmapEditorSettings).GetMethod("GetLightmapSettings", BindingFlags.Static | BindingFlags.NonPublic);
var lightmapSettings = getLightmapSettingsMethod.Invoke(null, null) as UnityEngine.Object;
return new SerializedObject(lightmapSettings);
}
19
View Source File : UnityPlayerBuildTools.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
public static void SyncSolution()
{
var syncVs = Type.GetType("UnityEditor.SyncVS,UnityEditor");
var syncSolution = syncVs.GetMethod("SyncSolution", BindingFlags.Public | BindingFlags.Static);
syncSolution.Invoke(null, null);
}
19
View Source File : MixedRealityCanvasInspector.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
private void OnDisable()
{
if (canvasEditorType != null)
{
MethodInfo onDisable = canvasEditorType.GetMethod("OnDisable", BindingFlags.Instance | BindingFlags.NonPublic);
if (onDisable != null)
{
onDisable.Invoke(internalEditor, null);
}
DestroyImmediate(internalEditor);
}
}
19
View Source File : AndroidVideoEditorUtil.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
private static string GetBuildToolsDirectory(BuildTarget bt)
{
return (string)(typeof(BuildPipeline).GetMethod("GetBuildToolsDirectory", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic).Invoke(null, new object[] { bt }));
}
19
View Source File : EventToCommandBehavior.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private void AttachHandler(string eventName)
{
// detach old event
if (_oldEvent != null)
_oldEvent.RemoveEventHandler(this.replacedociatedObject, _handler);
// attach new event
if (!string.IsNullOrEmpty(eventName))
{
EventInfo ei = this.replacedociatedObject.GetType().GetEvent(eventName);
if (ei != null)
{
MethodInfo mi = this.GetType().GetMethod("ExecuteCommand", BindingFlags.Instance | BindingFlags.NonPublic);
_handler = Delegate.CreateDelegate(ei.EventHandlerType, this, mi);
ei.AddEventHandler(this.replacedociatedObject, _handler);
_oldEvent = ei; // store to detach in case the Event property changes
}
else
throw new ArgumentException(string.Format("The event '{0}' was not found on type '{1}'", eventName,
this.replacedociatedObject.GetType().Name));
}
}
19
View Source File : OutOfProcessSettingValueProvider.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
internal static bool IsOutOfProcessEnabled(this AreplacedinatorVSPackage package, Workspace workspace)
{
package.ThrowOnNull(nameof(package));
package.VSVersion.ThrowOnNull($"{nameof(AreplacedinatorVSPackage)}.{nameof(AreplacedinatorVSPackage.VSVersion)}");
if (!package.VSVersion.IsVS2019)
return false;
// Faster version gets setting OOP64Bit from the VS session store. If it is true then the OOP is enabled
bool? outOfProcessFromSettingsStore = GetOutOfProcessSettingFromSessionStore(package);
if (outOfProcessFromSettingsStore == true)
return true;
// If OOP is false or its retrieval failed then we need to resort to the internal Roslyn helper RemoteHostOptions.IsUsingServiceHubOutOfProcess
if (workspace?.Services != null)
{
Type remoteHostOptionsType = (from replacedembly in AppDomain.CurrentDomain.Getreplacedemblies()
where replacedembly.GetName().Name == "Microsoft.Codereplacedysis.Remote.Workspaces"
from type in replacedembly.GetTypes()
where type.IsClreplaced && type.IsAbstract && type.IsSealed && !type.IsPublic && type.Name == "RemoteHostOptions"
select type)
.SingleOrDefault();
MethodInfo isUsingServiceHubOutOfProcess = remoteHostOptionsType?.GetMethod("IsUsingServiceHubOutOfProcess",
BindingFlags.Static | BindingFlags.Public);
object isOutOfProcessFromRoslynInternalsObj = isUsingServiceHubOutOfProcess?.Invoke(null, new object[] { workspace.Services });
if (isOutOfProcessFromRoslynInternalsObj is bool isOutOfProcessFromRoslynInternals)
return isOutOfProcessFromRoslynInternals;
}
return false;
}
19
View Source File : AsOfSqlExpressionFactory.cs
License : MIT License
Project Creator : Adam-Langley
License : MIT License
Project Creator : Adam-Langley
public override SelectExpression Select(IEnreplacedyType enreplacedyType)
{
if (enreplacedyType.FindAnnotation(SqlServerAsOfEnreplacedyTypeBuilderExtensions.ANNOTATION_TEMPORAL) != null)
{
var asOfTableExpression = new AsOfTableExpression(
enreplacedyType.GetTableName(),
enreplacedyType.GetSchema(),
enreplacedyType.GetTableName().ToLower().Substring(0, 1));
var selectContructor = typeof(SelectExpression).GetConstructor(BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance, null, new Type[] { typeof(IEnreplacedyType), typeof(TableExpressionBase) }, null);
var select = (SelectExpression)selectContructor.Invoke(new object[] { enreplacedyType, asOfTableExpression });
var privateInitializer = typeof(SqlExpressionFactory).GetMethod("AddConditions", BindingFlags.NonPublic | BindingFlags.Instance);
privateInitializer.Invoke(this, new object[] { select, enreplacedyType, null, null });
return select;
}
return base.Select(enreplacedyType);
}
19
View Source File : TestTools.cs
License : MIT License
Project Creator : adamecr
License : MIT License
Project Creator : adamecr
public static object InvokeNonPublicStaticMethod<TType>(string methodName, params object[] parameters)
{
var factoryType = typeof(TType);
try
{
return factoryType
.GetMethod(methodName, BindingFlags.NonPublic|BindingFlags.InvokeMethod | BindingFlags.Static)
.Invoke(null, parameters);
}
catch (TargetInvocationException ex)
{
throw ex.InnerException;
}
}
19
View Source File : TestTools.cs
License : MIT License
Project Creator : adamecr
License : MIT License
Project Creator : adamecr
public static object InvokeNonPublicMethod(object instance,string methodName, params object[] parameters)
{
var factoryType = instance.GetType();
try
{
return factoryType
.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.InvokeMethod | BindingFlags.Instance)
.Invoke(instance, parameters);
}
catch (TargetInvocationException ex)
{
throw ex.InnerException;
}
}
19
View Source File : ErrorNotifierModule.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static string GetTraceByReflection(TraceContext trace)
{
// temporarily enable PageOutput (via the _isEnabled field) so that calling Render produces output
var isEnabledField = typeof(TraceContext).GetField("_isEnabled", BindingFlags.NonPublic | BindingFlags.Instance);
var originalIsEnabledValue = isEnabledField.GetValue(trace);
trace.IsEnabled = true;
try
{
var sb = new StringBuilder();
using (var htw = new Html32TextWriter(new StringWriter(sb, CultureInfo.InvariantCulture)))
{
typeof(TraceContext)
.GetMethod("Render", BindingFlags.NonPublic | BindingFlags.Instance)
.Invoke(trace, new object[] { htw });
}
return sb.ToString();
}
finally
{
// reset the _isEnabled field
isEnabledField.SetValue(trace, originalIsEnabledValue);
}
}
19
View Source File : Utility.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static T RegisterPrecompiledVirtualPathProvider<T>() where T : VirtualPathProvider, new()
{
var providerInstance = new T();
var hostingEnvironmentInstance = typeof(HostingEnvironment).InvokeMember(
"_theHostingEnvironment",
BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.GetField,
null,
null,
null) as HostingEnvironment;
if (hostingEnvironmentInstance == null) return null;
var mi = typeof(HostingEnvironment).GetMethod(
"RegisterVirtualPathProviderInternal",
BindingFlags.NonPublic | BindingFlags.Static);
if (mi == null) return null;
mi.Invoke(hostingEnvironmentInstance, new object[] { providerInstance });
return providerInstance;
}
19
View Source File : SetupConfig.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static SetupManager GetSetupManager()
{
var type = TypeExtensions.GetType("Site.Global");
if (type != null)
{
var method = type.GetMethod("GetSetupManager", BindingFlags.Public | BindingFlags.Static);
if (method != null)
{
return (SetupManager)method.Invoke(null, null);
}
}
return DefaultSetupManager.Create();
}
19
View Source File : ImmediateWindow.cs
License : MIT License
Project Creator : adrenak
License : MIT License
Project Creator : adrenak
void OnGUI() {
// start the scroll view
scrollPos = EditorGUILayout.BeginScrollView(scrollPos);
// show the script field
string newScriptText = EditorGUILayout.TextArea(scriptText);
if (newScriptText != scriptText) {
// if the script changed, update our cached version and null out our cached method
scriptText = newScriptText;
lastScriptMethod = null;
}
// store if the GUI is enabled so we can restore it later
bool guiEnabled = GUI.enabled;
// disable the GUI if the script text is empty
GUI.enabled = guiEnabled && !string.IsNullOrEmpty(scriptText);
// show the execute button
if (GUILayout.Button("Execute")) {
// if our script method needs compiling
if (lastScriptMethod == null) {
// create and configure the code provider
var codeProvider = new CSharpCodeProvider();
var options = new CompilerParameters();
options.GenerateInMemory = true;
options.GenerateExecutable = false;
// bring in system libraries
options.Referencedreplacedemblies.Add("System.dll");
options.Referencedreplacedemblies.Add("System.Core.dll");
// bring in Unity replacedemblies
options.Referencedreplacedemblies.Add(typeof(EditorWindow).replacedembly.Location);
options.Referencedreplacedemblies.Add(typeof(Transform).replacedembly.Location);
// compile an replacedembly from our source code
var result = codeProvider.CompilereplacedemblyFromSource(options, string.Format(scriptFormat, scriptText));
// log any errors we got
if (result.Errors.Count > 0) {
foreach (CompilerError error in result.Errors) {
// the magic -11 on the line is to compensate for usings and clreplaced wrapper around the user script code.
// subtracting 11 from it will give the user the line numbers in their code.
Debug.LogError(string.Format("Immediate Compiler Error ({0}): {1}", error.Line - 11, error.ErrorText));
}
}
// otherwise use reflection to pull out our action method so we can invoke it
else {
var type = result.Compiledreplacedembly.GetType("ImmediateWindowCodeWrapper");
lastScriptMethod = type.GetMethod("PerformAction", BindingFlags.Public | BindingFlags.Static);
}
}
// if we have a compiled method, invoke it
if (lastScriptMethod != null)
lastScriptMethod.Invoke(null, null);
}
// restore the GUI
GUI.enabled = guiEnabled;
// close the scroll view
EditorGUILayout.EndScrollView();
}
19
View Source File : EventTriggerBase.cs
License : GNU General Public License v3.0
Project Creator : aduskin
License : GNU General Public License v3.0
Project Creator : aduskin
private void RegisterEvent(object obj, string eventName)
{
var eventInfo = obj.GetType().GetEvent(eventName);
if (eventInfo == null)
{
if (SourceObject != null)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
ExceptionStringTable.EventTriggerCannotFindEventNameExceptionMessage,
new object[] {eventName, obj.GetType().Name}));
}
else if (!IsValidEvent(eventInfo))
{
if (SourceObject != null)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
ExceptionStringTable.EventTriggerBaseInvalidEventExceptionMessage,
new object[] {eventName, obj.GetType().Name}));
}
else
{
_eventHandlerMethodInfo =
typeof(EventTriggerBase).GetMethod("OnEventImpl", BindingFlags.NonPublic | BindingFlags.Instance);
eventInfo.AddEventHandler(obj,
Delegate.CreateDelegate(eventInfo.EventHandlerType, this, _eventHandlerMethodInfo ?? throw new InvalidOperationException()));
}
}
19
View Source File : NPCPatches.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
public static bool NPC_tryToReceiveActiveObject_Prefix(NPC __instance, ref Farmer who, Dictionary<string, string> ___dialogue, ref List<int> __state)
{
try
{
if (who.ActiveObject.ParentSheetIndex == 808 && __instance.Name.Equals("Krobus"))
{
Monitor.Log($"Void pendant to {__instance.Name}");
if (who.getFriendshipHeartLevelForNPC(__instance.Name) >= 10 && who.HouseUpgradeLevel >= 1 && !who.isEngaged())
{
typeof(NPC).GetMethod("engagementResponse", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(__instance, new object[] { who, true });
return false;
}
}
if (who.ActiveObject.ParentSheetIndex == 458)
{
Monitor.Log($"Try give bouquet to {__instance.Name}");
if (Misc.GetSpouses(who, 1).ContainsKey(__instance.Name))
{
who.spouse = __instance.Name;
Misc.ResetSpouses(who);
Game1.currentLocation.playSound("dwop", NetAudio.SoundContext.NPC);
FarmHouse fh = Utility.getHomeOfFarmer(who);
fh.showSpouseRoom();
Helper.Reflection.GetMethod(fh, "resetLocalState").Invoke();
return false;
}
if (!__instance.datable.Value)
{
if (ModEntry.myRand.NextDouble() < 0.5)
{
Game1.drawObjectDialogue(Game1.content.LoadString("Strings\\StringsFromCSFiles:NPC.cs.3955", __instance.displayName));
return false;
}
__instance.CurrentDialogue.Push(new Dialogue((ModEntry.myRand.NextDouble() < 0.5) ? Game1.content.LoadString("Strings\\StringsFromCSFiles:NPC.cs.3956") : Game1.LoadStringByGender(__instance.Gender, "Strings\\StringsFromCSFiles:NPC.cs.3957"), __instance));
Game1.drawDialogue(__instance);
return false;
}
else
{
if (__instance.datable.Value && who.friendshipData.ContainsKey(__instance.Name) && who.friendshipData[__instance.Name].IsDating())
{
Game1.drawObjectDialogue(Game1.content.LoadString("Strings\\UI:AlreadyDatingBouquet", __instance.displayName));
return false;
}
if (__instance.datable.Value && who.friendshipData.ContainsKey(__instance.Name) && who.friendshipData[__instance.Name].IsDivorced())
{
__instance.CurrentDialogue.Push(new Dialogue(Game1.content.LoadString("Strings\\Characters:Divorced_bouquet"), __instance));
Game1.drawDialogue(__instance);
return false;
}
if (__instance.datable.Value && who.friendshipData.ContainsKey(__instance.Name) && who.friendshipData[__instance.Name].Points < Config.MinPointsToDate / 2f)
{
__instance.CurrentDialogue.Push(new Dialogue((ModEntry.myRand.NextDouble() < 0.5) ? Game1.content.LoadString("Strings\\StringsFromCSFiles:NPC.cs.3958") : Game1.LoadStringByGender(__instance.gender, "Strings\\StringsFromCSFiles:NPC.cs.3959"), __instance));
Game1.drawDialogue(__instance);
return false;
}
if (__instance.datable.Value && who.friendshipData.ContainsKey(__instance.Name) && who.friendshipData[__instance.Name].Points < Config.MinPointsToDate)
{
__instance.CurrentDialogue.Push(new Dialogue((ModEntry.myRand.NextDouble() < 0.5) ? Game1.content.LoadString("Strings\\StringsFromCSFiles:NPC.cs.3960") : Game1.content.LoadString("Strings\\StringsFromCSFiles:NPC.cs.3961"), __instance));
Game1.drawDialogue(__instance);
return false;
}
Friendship friendship = who.friendshipData[__instance.Name];
if (!friendship.IsDating())
{
friendship.Status = FriendshipStatus.Dating;
Multiplayer mp = ModEntry.PHelper.Reflection.GetField<Multiplayer>(typeof(Game1), "multiplayer").GetValue();
mp.globalChatInfoMessage("Dating", new string[]
{
who.Name,
__instance.displayName
});
}
__instance.CurrentDialogue.Push(new Dialogue((ModEntry.myRand.NextDouble() < 0.5) ? Game1.LoadStringByGender(__instance.gender, "Strings\\StringsFromCSFiles:NPC.cs.3962") : Game1.LoadStringByGender(__instance.Gender, "Strings\\StringsFromCSFiles:NPC.cs.3963"), __instance));
who.changeFriendship(25, __instance);
who.reduceActiveItemByOne();
who.completelyStopAnimatingOrDoingAction();
__instance.doEmote(20, true);
Game1.drawDialogue(__instance);
return false;
}
}
else if (who.ActiveObject.ParentSheetIndex == 460)
{
Monitor.Log($"Try give pendant to {__instance.Name}");
if (who.isEngaged())
{
Monitor.Log($"Tried to give pendant while engaged");
__instance.CurrentDialogue.Push(new Dialogue((ModEntry.myRand.NextDouble() < 0.5) ? Game1.LoadStringByGender(__instance.gender, "Strings\\StringsFromCSFiles:NPC.cs.3965") : Game1.LoadStringByGender(__instance.gender, "Strings\\StringsFromCSFiles:NPC.cs.3966"), __instance));
Game1.drawDialogue(__instance);
return false;
}
if (!__instance.datable.Value || __instance.isMarriedOrEngaged() || (who.friendshipData.ContainsKey(__instance.Name) && who.friendshipData[__instance.Name].Points < Config.MinPointsToMarry * 0.6f))
{
Monitor.Log($"Tried to give pendant to someone not datable");
if (ModEntry.myRand.NextDouble() < 0.5)
{
Game1.drawObjectDialogue(Game1.content.LoadString("Strings\\StringsFromCSFiles:NPC.cs.3969", __instance.displayName));
return false;
}
__instance.CurrentDialogue.Push(new Dialogue((__instance.Gender == 1) ? Game1.content.LoadString("Strings\\StringsFromCSFiles:NPC.cs.3970") : Game1.content.LoadString("Strings\\StringsFromCSFiles:NPC.cs.3971"), __instance));
Game1.drawDialogue(__instance);
return false;
}
else if (__instance.datable.Value && who.friendshipData.ContainsKey(__instance.Name) && who.friendshipData[__instance.Name].Points < Config.MinPointsToMarry)
{
Monitor.Log($"Tried to give pendant to someone not marriable");
if (!who.friendshipData[__instance.Name].ProposalRejected)
{
__instance.CurrentDialogue.Push(new Dialogue((ModEntry.myRand.NextDouble() < 0.5) ? Game1.content.LoadString("Strings\\StringsFromCSFiles:NPC.cs.3972") : Game1.content.LoadString("Strings\\StringsFromCSFiles:NPC.cs.3973"), __instance));
Game1.drawDialogue(__instance);
who.changeFriendship(-20, __instance);
who.friendshipData[__instance.Name].ProposalRejected = true;
return false;
}
__instance.CurrentDialogue.Push(new Dialogue((ModEntry.myRand.NextDouble() < 0.5) ? Game1.LoadStringByGender(__instance.gender, "Strings\\StringsFromCSFiles:NPC.cs.3974") : Game1.LoadStringByGender(__instance.gender, "Strings\\StringsFromCSFiles:NPC.cs.3975"), __instance));
Game1.drawDialogue(__instance);
who.changeFriendship(-50, __instance);
return false;
}
else
{
Monitor.Log($"Tried to give pendant to someone marriable");
if (!__instance.datable.Value || who.HouseUpgradeLevel >= 1)
{
typeof(NPC).GetMethod("engagementResponse", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(__instance, new object[] { who, false });
return false;
}
Monitor.Log($"Can't marry");
if (ModEntry.myRand.NextDouble() < 0.5)
{
Game1.drawObjectDialogue(Game1.content.LoadString("Strings\\StringsFromCSFiles:NPC.cs.3969", __instance.displayName));
return false;
}
__instance.CurrentDialogue.Push(new Dialogue(Game1.content.LoadString("Strings\\StringsFromCSFiles:NPC.cs.3972"), __instance));
Game1.drawDialogue(__instance);
return false;
}
}
else if (who.ActiveObject.ParentSheetIndex == 809 && !who.ActiveObject.bigCraftable.Value)
{
Monitor.Log($"Tried to give movie ticket to {__instance.Name}");
if (Misc.GetSpouses(who, 1).ContainsKey(__instance.Name) && Utility.doesMasterPlayerHaveMailReceivedButNotMailForTomorrow("ccMovieTheater") && !__instance.Name.Equals("Krobus") && who.lastSeenMovieWeek.Value < Game1.Date.TotalWeeks && !Utility.isFestivalDay(Game1.dayOfMonth, Game1.currentSeason) && Game1.timeOfDay <= 2100 && __instance.lastSeenMovieWeek.Value < Game1.Date.TotalWeeks && MovieTheater.GetResponseForMovie(__instance) != "reject")
{
Monitor.Log($"Tried to give movie ticket to spouse");
foreach (MovieInvitation invitation in who.team.movieInvitations)
{
if (invitation.farmer == who)
{
return true;
}
}
foreach (MovieInvitation invitation2 in who.team.movieInvitations)
{
if (invitation2.invitedNPC == __instance)
{
return true;
}
}
Monitor.Log($"Giving movie ticket to spouse");
if (LocalizedContentManager.CurrentLanguageCode == LocalizedContentManager.LanguageCode.en)
{
__instance.CurrentDialogue.Push(new Dialogue(__instance.GetDispositionModifiedString("Strings\\Characters:MovieInvite_Spouse_" + __instance.Name, new object[0]), __instance));
}
else if (LocalizedContentManager.CurrentLanguageCode == LocalizedContentManager.LanguageCode.en && ___dialogue != null && ___dialogue.ContainsKey("MovieInvitation"))
{
__instance.CurrentDialogue.Push(new Dialogue(___dialogue["MovieInvitation"], __instance));
}
else
{
__instance.CurrentDialogue.Push(new Dialogue(__instance.GetDispositionModifiedString("Strings\\Characters:MovieInvite_Invited", new object[0]), __instance));
}
Game1.drawDialogue(__instance);
who.reduceActiveItemByOne();
who.completelyStopAnimatingOrDoingAction();
who.currentLocation.localSound("give_gift");
MovieTheater.Invite(who, __instance);
if (who == Game1.player)
{
ModEntry.mp.globalChatInfoMessage("MovieInviteAccept", new string[]
{
Game1.player.displayName,
__instance.displayName
});
return false;
}
}
return true;
}
}
catch (Exception ex)
{
Monitor.Log($"Failed in {nameof(NPC_tryToReceiveActiveObject_Prefix)}:\n{ex}", LogLevel.Error);
}
return true;
}
19
View Source File : NPCPatches.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
public static bool NPC_tryToReceiveActiveObject_Prefix(NPC __instance, ref Farmer who, Dictionary<string, string> ___dialogue, ref List<int> __state)
{
try
{
if (Misc.GetSpouses(who,1).ContainsKey(__instance.Name))
{
Monitor.Log($"Gift to spouse {__instance.name}");
__state = new List<int> {
who.friendshipData[__instance.Name].GiftsThisWeek,
who.friendshipData[__instance.Name].GiftsToday,
0
};
who.friendshipData[__instance.Name].GiftsThisWeek = 0;
if (Config.MaxGiftsPerDay < 0 || who.friendshipData[__instance.Name].GiftsToday < Config.MaxGiftsPerDay)
{
who.friendshipData[__instance.Name].GiftsToday = 0;
}
else
{
who.friendshipData[__instance.Name].GiftsToday = 1;
__state[2] = 1; // flag to say we set it to 1
}
}
if (who.ActiveObject.ParentSheetIndex == 808 && __instance.Name.Equals("Krobus"))
{
Monitor.Log($"Pendant to {__instance.name}");
if (who.getFriendshipHeartLevelForNPC(__instance.Name) >= 10 && who.houseUpgradeLevel >= 1 && !who.isEngaged())
{
typeof(NPC).GetMethod("engagementResponse", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(__instance, new object[] { who, true });
return false;
}
}
if (who.ActiveObject.ParentSheetIndex == 458)
{
Monitor.Log($"Try give bouquet to {__instance.name}");
if (Misc.GetSpouses(who, 1).ContainsKey(__instance.Name))
{
who.spouse = __instance.Name;
Misc.ResetSpouses(who);
Game1.currentLocation.playSound("dwop", NetAudio.SoundContext.NPC);
FarmHouse fh = Utility.getHomeOfFarmer(who);
if (Config.BuildAllSpousesRooms)
{
Maps.BuildSpouseRooms(fh);
}
return false;
}
if (!__instance.datable)
{
if (ModEntry.myRand.NextDouble() < 0.5)
{
Game1.drawObjectDialogue(Game1.content.LoadString("Strings\\StringsFromCSFiles:NPC.cs.3955", __instance.displayName));
return false;
}
__instance.CurrentDialogue.Push(new Dialogue((ModEntry.myRand.NextDouble() < 0.5) ? Game1.content.LoadString("Strings\\StringsFromCSFiles:NPC.cs.3956") : Game1.LoadStringByGender(__instance.gender, "Strings\\StringsFromCSFiles:NPC.cs.3957"), __instance));
Game1.drawDialogue(__instance);
return false;
}
else
{
if (__instance.datable && who.friendshipData.ContainsKey(__instance.Name) && who.friendshipData[__instance.Name].IsDating())
{
Game1.drawObjectDialogue(Game1.content.LoadString("Strings\\UI:AlreadyDatingBouquet", __instance.displayName));
return false;
}
if (__instance.datable && who.friendshipData.ContainsKey(__instance.Name) && who.friendshipData[__instance.Name].IsDivorced())
{
if (Config.FriendlyDivorce)
{
who.friendshipData[__instance.Name].Points = Config.MinPointsToDate;
who.friendshipData[__instance.Name].Status = FriendshipStatus.Friendly;
}
else
{
__instance.CurrentDialogue.Push(new Dialogue(Game1.content.LoadString("Strings\\Characters:Divorced_bouquet"), __instance));
Game1.drawDialogue(__instance);
return false;
}
}
if (__instance.datable && who.friendshipData.ContainsKey(__instance.Name) && who.friendshipData[__instance.Name].Points < Config.MinPointsToDate / 2f)
{
__instance.CurrentDialogue.Push(new Dialogue((ModEntry.myRand.NextDouble() < 0.5) ? Game1.content.LoadString("Strings\\StringsFromCSFiles:NPC.cs.3958") : Game1.LoadStringByGender(__instance.gender, "Strings\\StringsFromCSFiles:NPC.cs.3959"), __instance));
Game1.drawDialogue(__instance);
return false;
}
if (__instance.datable && who.friendshipData.ContainsKey(__instance.Name) && who.friendshipData[__instance.Name].Points < Config.MinPointsToDate)
{
__instance.CurrentDialogue.Push(new Dialogue((ModEntry.myRand.NextDouble() < 0.5) ? Game1.content.LoadString("Strings\\StringsFromCSFiles:NPC.cs.3960") : Game1.content.LoadString("Strings\\StringsFromCSFiles:NPC.cs.3961"), __instance));
Game1.drawDialogue(__instance);
return false;
}
Friendship friendship = who.friendshipData[__instance.Name];
if (!friendship.IsDating())
{
friendship.Status = FriendshipStatus.Dating;
Multiplayer mp = ModEntry.PHelper.Reflection.GetField<Multiplayer>(typeof(Game1), "multiplayer").GetValue();
mp.globalChatInfoMessage("Dating", new string[]
{
who.Name,
__instance.displayName
});
}
__instance.CurrentDialogue.Push(new Dialogue((ModEntry.myRand.NextDouble() < 0.5) ? Game1.LoadStringByGender(__instance.gender, "Strings\\StringsFromCSFiles:NPC.cs.3962") : Game1.LoadStringByGender(__instance.gender, "Strings\\StringsFromCSFiles:NPC.cs.3963"), __instance));
who.changeFriendship(25, __instance);
who.reduceActiveItemByOne();
who.completelyStopAnimatingOrDoingAction();
__instance.doEmote(20, true);
Game1.drawDialogue(__instance);
return false;
}
}
else if (who.ActiveObject.ParentSheetIndex == 460)
{
Monitor.Log($"Try give pendant to {__instance.name}");
if (who.isEngaged())
{
Monitor.Log($"Tried to give pendant while engaged");
__instance.CurrentDialogue.Push(new Dialogue((ModEntry.myRand.NextDouble() < 0.5) ? Game1.LoadStringByGender(__instance.gender, "Strings\\StringsFromCSFiles:NPC.cs.3965") : Game1.LoadStringByGender(__instance.gender, "Strings\\StringsFromCSFiles:NPC.cs.3966"), __instance));
Game1.drawDialogue(__instance);
return false;
}
if (!__instance.datable || __instance.isMarriedOrEngaged() || (who.friendshipData.ContainsKey(__instance.Name) && who.friendshipData[__instance.Name].Points < Config.MinPointsToMarry * 0.6f))
{
Monitor.Log($"Tried to give pendant to someone not datable");
if (ModEntry.myRand.NextDouble() < 0.5)
{
Game1.drawObjectDialogue(Game1.content.LoadString("Strings\\StringsFromCSFiles:NPC.cs.3969", __instance.displayName));
return false;
}
__instance.CurrentDialogue.Push(new Dialogue((__instance.Gender == 1) ? Game1.content.LoadString("Strings\\StringsFromCSFiles:NPC.cs.3970") : Game1.content.LoadString("Strings\\StringsFromCSFiles:NPC.cs.3971"), __instance));
Game1.drawDialogue(__instance);
return false;
}
else if (__instance.datable && who.friendshipData.ContainsKey(__instance.Name) && who.friendshipData[__instance.Name].Points < Config.MinPointsToMarry)
{
Monitor.Log($"Tried to give pendant to someone not marriable");
if (!who.friendshipData[__instance.Name].ProposalRejected)
{
__instance.CurrentDialogue.Push(new Dialogue((ModEntry.myRand.NextDouble() < 0.5) ? Game1.content.LoadString("Strings\\StringsFromCSFiles:NPC.cs.3972") : Game1.content.LoadString("Strings\\StringsFromCSFiles:NPC.cs.3973"), __instance));
Game1.drawDialogue(__instance);
who.changeFriendship(-20, __instance);
who.friendshipData[__instance.Name].ProposalRejected = true;
return false;
}
__instance.CurrentDialogue.Push(new Dialogue((ModEntry.myRand.NextDouble() < 0.5) ? Game1.LoadStringByGender(__instance.gender, "Strings\\StringsFromCSFiles:NPC.cs.3974") : Game1.LoadStringByGender(__instance.gender, "Strings\\StringsFromCSFiles:NPC.cs.3975"), __instance));
Game1.drawDialogue(__instance);
who.changeFriendship(-50, __instance);
return false;
}
else
{
Monitor.Log($"Tried to give pendant to someone marriable");
if (!__instance.datable.Value || who.HouseUpgradeLevel >= 1)
{
typeof(NPC).GetMethod("engagementResponse", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(__instance, new object[] { who, false });
return false;
}
Monitor.Log($"Can't marry");
if (ModEntry.myRand.NextDouble() < 0.5)
{
Game1.drawObjectDialogue(Game1.content.LoadString("Strings\\StringsFromCSFiles:NPC.cs.3969", __instance.displayName));
return false;
}
__instance.CurrentDialogue.Push(new Dialogue(Game1.content.LoadString("Strings\\StringsFromCSFiles:NPC.cs.3972"), __instance));
Game1.drawDialogue(__instance);
return false;
}
}
else if (who.ActiveObject.ParentSheetIndex == 809 && !who.ActiveObject.bigCraftable.Value)
{
Monitor.Log($"Tried to give movie ticket to {__instance.Name}");
if (Misc.GetSpouses(who, 1).ContainsKey(__instance.Name) && Utility.doesMasterPlayerHaveMailReceivedButNotMailForTomorrow("ccMovieTheater") && !__instance.Name.Equals("Krobus") && who.lastSeenMovieWeek.Value < Game1.Date.TotalWeeks && !Utility.isFestivalDay(Game1.dayOfMonth, Game1.currentSeason) && Game1.timeOfDay <= 2100 && __instance.lastSeenMovieWeek.Value < Game1.Date.TotalWeeks && MovieTheater.GetResponseForMovie(__instance) != "reject")
{
Monitor.Log($"Tried to give movie ticket to spouse");
foreach (MovieInvitation invitation in who.team.movieInvitations)
{
if (invitation.farmer == who)
{
return true;
}
}
foreach (MovieInvitation invitation2 in who.team.movieInvitations)
{
if (invitation2.invitedNPC == __instance)
{
return true;
}
}
Monitor.Log($"Giving movie ticket to spouse");
if (LocalizedContentManager.CurrentLanguageCode == LocalizedContentManager.LanguageCode.en)
{
__instance.CurrentDialogue.Push(new Dialogue(__instance.GetDispositionModifiedString("Strings\\Characters:MovieInvite_Spouse_" + __instance.Name, new object[0]), __instance));
}
else if (LocalizedContentManager.CurrentLanguageCode == LocalizedContentManager.LanguageCode.en && ___dialogue != null && ___dialogue.ContainsKey("MovieInvitation"))
{
__instance.CurrentDialogue.Push(new Dialogue(___dialogue["MovieInvitation"], __instance));
}
else
{
__instance.CurrentDialogue.Push(new Dialogue(__instance.GetDispositionModifiedString("Strings\\Characters:MovieInvite_Invited", new object[0]), __instance));
}
Game1.drawDialogue(__instance);
who.reduceActiveItemByOne();
who.completelyStopAnimatingOrDoingAction();
who.currentLocation.localSound("give_gift");
MovieTheater.Invite(who, __instance);
if (who == Game1.player)
{
ModEntry.mp.globalChatInfoMessage("MovieInviteAccept", new string[]
{
Game1.player.displayName,
__instance.displayName
});
return false;
}
}
return true;
}
}
catch (Exception ex)
{
Monitor.Log($"Failed in {nameof(NPC_tryToReceiveActiveObject_Prefix)}:\n{ex}", LogLevel.Error);
}
return true;
}
19
View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
private static bool Serpent_updateAnimation_prefix(Serpent __instance, GameTime time)
{
if (__instance.Health <= 0 || Config.MonstersIgnorePlayer)
{
var ftn = typeof(Monster).GetMethod("updateAnimation", BindingFlags.NonPublic | BindingFlags.Instance).MethodHandle.GetFunctionPointer();
var action = (Action<GameTime>)Activator.CreateInstance(typeof(Action<GameTime>), __instance, ftn);
action(time);
__instance.Sprite.Animate(time, 0, 9, 40f);
typeof(Monster).GetMethod("resetAnimationSpeed", BindingFlags.NonPublic | BindingFlags.Instance).Invoke((Monster)__instance, new object[] { });
return false;
}
return true;
}
See More Examples