Here are the examples of the csharp api System.Type.GetProperty(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
3421 Examples
19
View Source File : ExpressionActivator.cs
License : Apache License 2.0
Project Creator : 1448376744
License : Apache License 2.0
Project Creator : 1448376744
private Expression CreateExpression(ParameterExpression parameter, string expression)
{
var expressions1 = Factorization(expression);
var expressions2 = new Dictionary<string, Expression>();
foreach (var item in expressions1)
{
var subexpr = item.Value.Trim('(', ')');
var @opterator = ResovleOperator(item.Value);
var opt = GetExpressionType(@opterator);
if (opt == ExpressionType.Not)
{
Expression exp;
var text = subexpr.Split(new string[] { @opterator }, StringSplitOptions.RemoveEmptyEntries)[0].Trim();
if (expressions2.ContainsKey(text))
{
exp = expressions2[text];
}
else if (parameter.Type.GetProperties().Any(a => a.Name == text))
{
var property = parameter.Type.GetProperty(text);
exp = Expression.MakeMemberAccess(parameter, property);
}
else
{
exp = Expression.Constant(Convert.ToBoolean(text));
}
expressions2.Add(item.Key, Expression.MakeUnary(opt, exp, null));
}
else
{
var text1 = subexpr
.Split(new string[] { @opterator }, StringSplitOptions.RemoveEmptyEntries)[0]
.Trim();
var text2 = subexpr
.Split(new string[] { @opterator }, StringSplitOptions.RemoveEmptyEntries)[1]
.Trim();
string temp = null;
Expression exp1, exp2;
//永远将变量放在第一个操作数
if (parameter.Type.GetProperties().Any(a => a.Name == text2))
{
temp = text1;
text1 = text2;
text2 = temp;
}
//是否为上一次的分式
if (expressions2.ContainsKey(text1))
{
exp1 = expressions2[text1];
}
else if (parameter.Type.GetProperties().Any(a => a.Name == text1))
{
//是否为变量
var property = parameter.Type.GetProperty(text1);
exp1 = Expression.MakeMemberAccess(parameter, property);
}
else
{
exp1 = ResovleConstantExpression(text1);
}
//是否为上一次的分式
if (expressions2.ContainsKey(text2))
{
exp2 = expressions2[text2];
}
//如果第一个操作数是变量
else if (parameter.Type.GetProperties().Any(a => a.Name == text1))
{
var constantType = parameter.Type.GetProperty(text1).PropertyType;
exp2 = ResovleConstantExpression(text2, constantType);
}
else
{
exp2 = ResovleConstantExpression(text1, (exp1 as ConstantExpression)?.Type);
}
expressions2.Add(item.Key, Expression.MakeBinary(opt, exp1, exp2));
}
}
return expressions2.Last().Value;
}
19
View Source File : DbBuilder.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
private void CreateDbContext()
{
var sp = Services.BuildServiceProvider();
var dbLogger = new DbLogger(Options, sp.GetService<IDbLoggerProvider>());
var accountResolver = sp.GetService<IAccountResolver>();
//获取数据库适配器的程序集
var dbAdapterreplacedemblyName = replacedembly.GetCallingreplacedembly().GetName().Name!.Replace("Core", "Adapter.") + Options.Provider;
var dbAdapterreplacedembly = replacedemblyLoadContext.Default.LoadFromreplacedemblyName(new replacedemblyName(dbAdapterreplacedemblyName));
//创建数据库上下文实例,通过反射设置属性
DbContext = (IDbContext)Activator.CreateInstance(_dbContextType);
_dbContextType.GetProperty("Options")?.SetValue(DbContext, Options);
_dbContextType.GetProperty("Logger")?.SetValue(DbContext, dbLogger);
_dbContextType.GetProperty("Adapter")?.SetValue(DbContext, CreateDbAdapter(dbAdapterreplacedemblyName, dbAdapterreplacedembly));
_dbContextType.GetProperty("SchemaProvider")?.SetValue(DbContext, CreateSchemaProvider(dbAdapterreplacedemblyName, dbAdapterreplacedembly));
_dbContextType.GetProperty("CodeFirstProvider")?.SetValue(DbContext, CreateCodeFirstProvider(dbAdapterreplacedemblyName, dbAdapterreplacedembly, Services));
_dbContextType.GetProperty("AccountResolver")?.SetValue(DbContext, accountResolver);
// ReSharper disable once replacedignNullToNotNullAttribute
Services.AddSingleton(_dbContextType, DbContext);
}
19
View Source File : DbBuilder.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
private IDbAdapter CreateDbAdapter(string dbAdapterreplacedemblyName, replacedembly dbAdapterreplacedembly)
{
var dbAdapterType = dbAdapterreplacedembly.GetType($"{dbAdapterreplacedemblyName}.{Options.Provider}DbAdapter");
Check.NotNull(dbAdapterType, $"数据库适配器{dbAdapterreplacedemblyName}未安装");
var dbAdapter = (IDbAdapter)Activator.CreateInstance(dbAdapterType!);
dbAdapterType.GetProperty("Options")!.SetValue(dbAdapter, Options);
return dbAdapter;
}
19
View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
{
if (t.IsPrimitive)
{
if (t == typeof(byte))
{
return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
}
if (t == typeof(sbyte))
{
return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
}
if (t == typeof(short))
{
return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
}
if (t == typeof(ushort))
{
return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
}
if (t == typeof(int))
{
var bytes = new byte[4];
Rand.NextBytes(bytes);
return BitConverter.ToInt32(bytes, 0);
}
if (t == typeof(uint))
{
var bytes = new byte[4];
Rand.NextBytes(bytes);
return BitConverter.ToUInt32(bytes, 0);
}
if (t == typeof(long))
{
var bytes = new byte[8];
Rand.NextBytes(bytes);
return BitConverter.ToInt64(bytes, 0);
}
if (t == typeof(ulong))
{
var bytes = new byte[8];
Rand.NextBytes(bytes);
return BitConverter.ToUInt64(bytes, 0);
}
if (t == typeof(float))
{
var bytes = new byte[4];
Rand.NextBytes(bytes);
var f = BitConverter.ToSingle(bytes, 0);
if (float.IsNaN(f))
f = (float)RandomValue<short>();
return f;
}
if (t == typeof(double))
{
var bytes = new byte[8];
Rand.NextBytes(bytes);
var d= BitConverter.ToDouble(bytes, 0);
if (double.IsNaN(d))
d = (double)RandomValue<short>();
return d;
}
if (t == typeof(char))
{
var roll = Rand.Next(ASCII.Length);
return ASCII[roll];
}
if (t == typeof(bool))
{
return (Rand.Next(2) == 1);
}
throw new InvalidOperationException();
}
if (t == typeof(decimal))
{
return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
}
if (t == typeof(string))
{
int start = stringValueAllowEmpty ? 0 : 1;
var len = Rand.Next(start, 40);
var c = new char[len];
for (var i = 0; i < c.Length; i++)
{
c[i] = (char)typeof(char).RandomValue();
}
return new string(c);
}
if (t == typeof(DateTime))
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var bytes = new byte[4];
Rand.NextBytes(bytes);
var secsOffset = BitConverter.ToInt32(bytes, 0);
var retDate = epoch.AddSeconds(secsOffset);
return retDate;
}
if (t == typeof(TimeSpan))
{
return new TimeSpan(RandomValue<DateTime>().Ticks);
}
if (t == typeof(DataTable))
{
DataTable dt = new DataTable();
int coluCount = Rand.Next(10, 30);
for (int i = 0; i < coluCount; i++)
{
string n = RandomHelper.RandomValue<string>(false);
while(dt.Columns.Contains(n))
n = RandomHelper.RandomValue<string>(false);
dt.Columns.Add(n, typeof(object));
}
int rowCount = Rand.Next(20, 50);
for (int i = 0; i < rowCount; i++)
{
var row = new object[coluCount];
for (int zi = 0; zi < coluCount; zi++)
{
row[zi] = RandomHelper.RandomValue<object>();
}
dt.Rows.Add(row);
}
return dt;
}
if (t.IsNullable())
{
// leave it unset
if (Rand.Next(2) == 0)
{
// null!
return Activator.CreateInstance(t);
}
var underlying = Nullable.GetUnderlyingType(t);
var val = underlying.RandomValue(stringValueAllowEmpty);
var cons = t.GetConstructor(new[] { underlying });
return cons.Invoke(new object[] { val });
}
if (t.IsEnum)
{
var allValues = Enum.GetValues(t);
var ix = Rand.Next(allValues.Length);
return allValues.GetValue(ix);
}
if (t.IsArray)
{
var valType = t.GetElementType();
var len = Rand.Next(20, 50);
var ret = Array.CreateInstance(valType, len);
//var add = t.GetMethod("SetValue");
for (var i = 0; i < len; i++)
{
var elem = valType.RandomValue(stringValueAllowEmpty);
ret.SetValue(elem, i);
}
return ret;
}
if (t.IsGenericType)
{
var defind = t.GetGenericTypeDefinition();
if (defind == typeof(HashSet<>))
{
var valType = t.GetGenericArguments()[0];
var ret = Activator.CreateInstance(t);
var add = t.GetMethod("Add");
var contains = t.GetMethod("Contains");
var len = Rand.Next(20, 50);
for (var i = 0; i < len; i++)
{
var elem = valType.RandomValue(stringValueAllowEmpty);
while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
elem = valType.RandomValue(stringValueAllowEmpty);
add.Invoke(ret, new object[] { elem });
}
return ret;
}
if (defind == typeof(Dictionary<,>))
{
var keyType = t.GetGenericArguments()[0];
var valType = t.GetGenericArguments()[1];
var ret = Activator.CreateInstance(t);
var add = t.GetMethod("Add");
var contains = t.GetMethod("ContainsKey");
var len = Rand.Next(20, 50);
if (keyType == typeof(Boolean))
len = 2;
for (var i = 0; i < len; i++)
{
var val = valType.RandomValue(stringValueAllowEmpty);
var key = keyType.RandomValue(stringValueAllowEmpty);
while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
key = keyType.RandomValue(stringValueAllowEmpty);
add.Invoke(ret, new object[] { key, val });
}
return ret;
}
if (defind == typeof(List<>))
{
var valType = t.GetGenericArguments()[0];
var ret = Activator.CreateInstance(t);
var add = t.GetMethod("Add");
var len = Rand.Next(20, 50);
for (var i = 0; i < len; i++)
{
var elem = valType.RandomValue(stringValueAllowEmpty);
add.Invoke(ret, new object[] { elem });
}
return ret;
}
if (defind == typeof(ArraySegment<>))
{
var valType = t.GetGenericArguments()[0];
var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
var lenT = ary.GetType().GetProperty("Length");
var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
var len = (int)lenT.GetValue(ary) - offset;
return Activator.CreateInstance(t, ary, offset, len);
}
}
if (t == typeof(Guid))
return Guid.NewGuid();
if (t == typeof(object))
{
var code = Rand.Next(0, 9);
switch (code)
{
case 0:
return RandomValue<int>();
case 1:
return RandomValue<long>();
case 2:
return RandomValue<Char>();
case 3:
return RandomValue<DateTime>();
case 4:
return RandomValue<string>(stringValueAllowEmpty);
case 5:
return RandomValue<Guid>();
case 6:
return RandomValue<decimal>();
case 7:
return RandomValue<double>();
case 8:
return RandomValue<float>();
default:
return RandomValue<short>();
}
}
//model
var retObj = Activator.CreateInstance(t);
foreach (var p in t.GetFields())
{
//if (Rand.Next(5) == 0) continue;
var fieldType = p.FieldType;
p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
}
foreach (var p in t.GetProperties())
{
//if (Rand.Next(5) == 0) continue;
if (p.CanWrite && p.CanRead)
{
var fieldType = p.PropertyType;
p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
}
}
return retObj;
}
19
View Source File : SegmentedControlOption.cs
License : MIT License
Project Creator : 1iveowl
License : MIT License
Project Creator : 1iveowl
private void SetTextFromItemProperty()
{
if (Item != null && TextPropertyName != null)
Text = Item.GetType().GetProperty(TextPropertyName)?.GetValue(Item)?.ToString();
}
19
View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
{
if (t.IsPrimitive)
{
if (t == typeof(byte))
{
return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
}
if (t == typeof(sbyte))
{
return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
}
if (t == typeof(short))
{
return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
}
if (t == typeof(ushort))
{
return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
}
if (t == typeof(int))
{
var bytes = new byte[4];
Rand.NextBytes(bytes);
return BitConverter.ToInt32(bytes, 0);
}
if (t == typeof(uint))
{
var bytes = new byte[4];
Rand.NextBytes(bytes);
return BitConverter.ToUInt32(bytes, 0);
}
if (t == typeof(long))
{
var bytes = new byte[8];
Rand.NextBytes(bytes);
return BitConverter.ToInt64(bytes, 0);
}
if (t == typeof(ulong))
{
var bytes = new byte[8];
Rand.NextBytes(bytes);
return BitConverter.ToUInt64(bytes, 0);
}
if (t == typeof(float))
{
var bytes = new byte[4];
Rand.NextBytes(bytes);
var f = BitConverter.ToSingle(bytes, 0);
if (float.IsNaN(f))
f = (float)RandomValue<short>();
return f;
}
if (t == typeof(double))
{
var bytes = new byte[8];
Rand.NextBytes(bytes);
var d = BitConverter.ToDouble(bytes, 0);
if (double.IsNaN(d))
d = (double)RandomValue<short>();
return d;
}
if (t == typeof(char))
{
var roll = Rand.Next(ASCII.Length);
return ASCII[roll];
}
if (t == typeof(bool))
{
return (Rand.Next(2) == 1);
}
throw new InvalidOperationException();
}
if (t == typeof(decimal))
{
return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
}
if (t == typeof(string))
{
int start = stringValueAllowEmpty ? 0 : 1;
var len = Rand.Next(start, 28);
var c = new char[len];
for (var i = 0; i < c.Length; i++)
{
c[i] = (char)typeof(char).RandomValue();
}
return new string(c);
}
if (t == typeof(DateTime))
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var bytes = new byte[4];
Rand.NextBytes(bytes);
var secsOffset = BitConverter.ToInt32(bytes, 0);
var retDate = epoch.AddSeconds(secsOffset);
return retDate;
}
if (t == typeof(TimeSpan))
{
return new TimeSpan(RandomValue<DateTime>().Ticks);
}
if (t == typeof(DataTable))
{
DataTable dt = new DataTable();
int coluCount = Rand.Next(10, 30);
for (int i = 0; i < coluCount; i++)
{
dt.Columns.Add(RandomHelper.RandomValue<string>(false), typeof(object));
}
int rowCount = Rand.Next(20, 50);
for (int i = 0; i < rowCount; i++)
{
var row = new object[coluCount];
for (int zi = 0; zi < coluCount; zi++)
{
row[zi] = RandomHelper.RandomValue<object>();
}
dt.Rows.Add(row);
}
return dt;
}
if (t.IsNullable())
{
// leave it unset
if (Rand.Next(2) == 0)
{
// null!
return Activator.CreateInstance(t);
}
var underlying = Nullable.GetUnderlyingType(t);
var val = underlying.RandomValue(stringValueAllowEmpty);
var cons = t.GetConstructor(new[] { underlying });
return cons.Invoke(new object[] { val });
}
if (t.IsEnum)
{
var allValues = Enum.GetValues(t);
var ix = Rand.Next(allValues.Length);
return allValues.GetValue(ix);
}
if (t.IsArray)
{
var valType = t.GetElementType();
var len = Rand.Next(20, 50);
var ret = Array.CreateInstance(valType, len);
//var add = t.GetMethod("SetValue");
for (var i = 0; i < len; i++)
{
var elem = valType.RandomValue(stringValueAllowEmpty);
ret.SetValue(elem, i);
}
return ret;
}
if (t.IsGenericType)
{
var defind = t.GetGenericTypeDefinition();
if (defind == typeof(HashSet<>))
{
var valType = t.GetGenericArguments()[0];
var ret = Activator.CreateInstance(t);
var add = t.GetMethod("Add");
var contains = t.GetMethod("Contains");
var len = Rand.Next(20, 50);
for (var i = 0; i < len; i++)
{
var elem = valType.RandomValue(stringValueAllowEmpty);
while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
elem = valType.RandomValue(stringValueAllowEmpty);
add.Invoke(ret, new object[] { elem });
}
return ret;
}
if (defind == typeof(Dictionary<,>))
{
var keyType = t.GetGenericArguments()[0];
var valType = t.GetGenericArguments()[1];
var ret = Activator.CreateInstance(t);
var add = t.GetMethod("Add");
var contains = t.GetMethod("ContainsKey");
var len = Rand.Next(20, 50);
if (keyType == typeof(Boolean))
len = 2;
for (var i = 0; i < len; i++)
{
var val = valType.RandomValue(stringValueAllowEmpty);
var key = keyType.RandomValue(stringValueAllowEmpty);
while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
key = keyType.RandomValue(stringValueAllowEmpty);
add.Invoke(ret, new object[] { key, val });
}
return ret;
}
if (defind == typeof(List<>))
{
var valType = t.GetGenericArguments()[0];
var ret = Activator.CreateInstance(t);
var add = t.GetMethod("Add");
var len = Rand.Next(20, 50);
for (var i = 0; i < len; i++)
{
var elem = valType.RandomValue(stringValueAllowEmpty);
add.Invoke(ret, new object[] { elem });
}
return ret;
}
if (defind == typeof(ArraySegment<>))
{
var valType = t.GetGenericArguments()[0];
var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
var lenT = ary.GetType().GetProperty("Length");
var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
var len = (int)lenT.GetValue(ary) - offset;
return Activator.CreateInstance(t, ary, offset, len);
}
}
if (t == typeof(Guid))
return Guid.NewGuid();
if (t == typeof(object))
{
var code = Rand.Next(0, 9);
switch (code)
{
case 0:
return RandomValue<int>();
case 1:
return RandomValue<long>();
case 2:
return RandomValue<Char>();
case 3:
return RandomValue<DateTime>();
case 4:
return RandomValue<string>(stringValueAllowEmpty);
case 5:
return RandomValue<Guid>();
case 6:
return RandomValue<decimal>();
case 7:
return RandomValue<double>();
case 8:
return RandomValue<float>();
default:
return RandomValue<short>();
}
}
//model
var retObj = Activator.CreateInstance(t);
foreach (var p in t.GetFields())
{
//if (Rand.Next(5) == 0) continue;
var fieldType = p.FieldType;
p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
}
foreach (var p in t.GetProperties())
{
//if (Rand.Next(5) == 0) continue;
if (p.CanWrite && p.CanRead)
{
var fieldType = p.PropertyType;
p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
}
}
return retObj;
}
19
View Source File : Serializer.cs
License : MIT License
Project Creator : 2881099
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 : QueryableExtension.cs
License : GNU General Public License v3.0
Project Creator : 2dust
License : GNU General Public License v3.0
Project Creator : 2dust
static IOrderedQueryable<T> _OrderBy<T>(IQueryable<T> query, string propertyName, bool isDesc)
{
string methodname = (isDesc) ? "OrderByDescendingInternal" : "OrderByInternal";
var memberProp = typeof(T).GetProperty(propertyName);
var method = typeof(QueryableExtension).GetMethod(methodname)
.MakeGenericMethod(typeof(T), memberProp.PropertyType);
return (IOrderedQueryable<T>)method.Invoke(null, new object[] { query, memberProp });
}
19
View Source File : MetaprogrammingTests.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
[Fact]
public void ShouldRunSelfModifyingEditor()
{
typeof(MetaprogrammingTests).GetProperty("Answer").GetValue(null).ShouldBe(42);
}
19
View Source File : EntityExtension.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
public static TSource ToCreate<TSource>(this TSource source, UserSessionVM userSession)
{
var types = source.GetType();
if (types.GetProperty("ID") != null)
{
types.GetProperty("ID").SetValue(source, Guid.NewGuid().ToString().ToUpper(), null);
}
if (types.GetProperty("CreateTime") != null)
{
types.GetProperty("CreateTime").SetValue(source, DateTime.Now, null);
}
if (types.GetProperty("UpdateTime") != null)
{
types.GetProperty("UpdateTime").SetValue(source, DateTime.Now, null);
}
if (types.GetProperty("CreateID") != null)
{
types.GetProperty("CreateID").SetValue(source, userSession.UserID, null);
types.GetProperty("CreateName").SetValue(source, userSession.UserName, null);
}
if (types.GetProperty("UpdateID") != null)
{
types.GetProperty("UpdateID").SetValue(source, userSession.UserID, null);
types.GetProperty("UpdateName").SetValue(source, userSession.UserName, null);
}
return source;
}
19
View Source File : EntityExtension.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
public static TSource ToUpdate<TSource>(this TSource source, UserSessionVM userSession)
{
var types = source.GetType();
if (types.GetProperty("UpdateTime") != null)
{
types.GetProperty("UpdateTime").SetValue(source, DateTime.Now, null);
}
if (types.GetProperty("UpdateID") != null)
{
types.GetProperty("UpdateID").SetValue(source, userSession.UserID, null);
}
if (types.GetProperty("UpdateName") != null)
{
types.GetProperty("UpdateName").SetValue(source, userSession.UserName, null);
}
return source;
}
19
View Source File : PropertyExtension.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
public static string ComparisonTo<T1, T2>(this T1 source, T2 current)
{
string diff = "";
try
{
Type t1 = source.GetType();
Type t2 = current.GetType();
PropertyInfo[] property2 = t2.GetProperties();
//排除主键和基础字段
List<string> exclude = new List<string>() { "Id" };
foreach (PropertyInfo p in property2)
{
string name = p.Name;
if (exclude.Contains(name)) { continue; }
var value1 = t1.GetProperty(name)?.GetValue(source, null)?.ToString();
var value2 = p.GetValue(current, null)?.ToString();
if (value1 != value2)
{
diff += $"[{name}]:'{value1}'=>'{value2}';\r\n";
}
}
}
catch(Exception)
{
}
return diff;
}
19
View Source File : Amf3Reader.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
public bool TryGetVectorObject(Span<byte> buffer, out object value, out int consumed)
{
value = default;
consumed = default;
if (!DataIsType(buffer, Amf3Type.VectorObject))
{
return false;
}
buffer = buffer.Slice(Amf3CommonValues.MARKER_LENGTH);
int arrayConsumed = 0;
if (!ReadVectorHeader(ref buffer, ref value, ref arrayConsumed, out var itemCount, out var isFixedSize, out var isRef))
{
return false;
}
if (isRef)
{
consumed = arrayConsumed;
return true;
}
if (!ReadVectorTypeName(ref buffer, out var typeName, out var typeNameConsumed))
{
return false;
}
var arrayBodyBuffer = buffer;
object resultVector = null;
Type elementType = null;
Action<object> addAction = null;
if (typeName == "*")
{
elementType = typeof(object);
var v = new Vector<object>();
_objectReferenceTable.Add(v);
v.IsFixedSize = isFixedSize;
resultVector = v;
addAction = v.Add;
}
else
{
if (!_registeredTypedObejectStates.TryGetValue(typeName, out var state))
{
return false;
}
elementType = state.Type;
var vectorType = typeof(Vector<>).MakeGenericType(elementType);
resultVector = Activator.CreateInstance(vectorType);
_objectReferenceTable.Add(resultVector);
vectorType.GetProperty("IsFixedSize").SetValue(resultVector, isFixedSize);
var addMethod = vectorType.GetMethod("Add");
addAction = o => addMethod.Invoke(resultVector, new object[] { o });
}
for (int i = 0; i < itemCount; i++)
{
if (!TryGetValue(arrayBodyBuffer, out var item, out var itemConsumed))
{
return false;
}
addAction(item);
arrayBodyBuffer = arrayBodyBuffer.Slice(itemConsumed);
arrayConsumed += itemConsumed;
}
value = resultVector;
consumed = typeNameConsumed + arrayConsumed;
return true;
}
19
View Source File : RtmpSession.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
internal void CommandHandler(RtmpController controller, CommandMessage command)
{
MethodInfo method = null;
object[] arguments = null;
try
{
_rpcService.PrepareMethod(controller, command, out method, out arguments);
var result = method.Invoke(controller, arguments);
if (result != null)
{
var resType = method.ReturnType;
if (resType.IsGenericType && resType.GetGenericTypeDefinition() == typeof(Task<>))
{
var tsk = result as Task;
tsk.ContinueWith(t =>
{
var taskResult = resType.GetProperty("Result").GetValue(result);
var retCommand = new ReturnResultCommandMessage(command.AmfEncodingVersion);
retCommand.IsSuccess = true;
retCommand.TranscationID = command.TranscationID;
retCommand.CommandObject = null;
retCommand.ReturnValue = taskResult;
_ = controller.MessageStream.SendMessageAsync(controller.ChunkStream, retCommand);
}, TaskContinuationOptions.OnlyOnRanToCompletion);
tsk.ContinueWith(t =>
{
var exception = tsk.Exception;
var retCommand = new ReturnResultCommandMessage(command.AmfEncodingVersion);
retCommand.IsSuccess = false;
retCommand.TranscationID = command.TranscationID;
retCommand.CommandObject = null;
retCommand.ReturnValue = exception.Message;
_ = controller.MessageStream.SendMessageAsync(controller.ChunkStream, retCommand);
}, TaskContinuationOptions.OnlyOnFaulted);
}
else if (resType == typeof(Task))
{
var tsk = result as Task;
tsk.ContinueWith(t =>
{
var exception = tsk.Exception;
var retCommand = new ReturnResultCommandMessage(command.AmfEncodingVersion);
retCommand.IsSuccess = false;
retCommand.TranscationID = command.TranscationID;
retCommand.CommandObject = null;
retCommand.ReturnValue = exception.Message;
_ = controller.MessageStream.SendMessageAsync(controller.ChunkStream, retCommand);
}, TaskContinuationOptions.OnlyOnFaulted);
}
else if (resType != typeof(void))
{
var retCommand = new ReturnResultCommandMessage(command.AmfEncodingVersion);
retCommand.IsSuccess = true;
retCommand.TranscationID = command.TranscationID;
retCommand.CommandObject = null;
retCommand.ReturnValue = result;
_ = controller.MessageStream.SendMessageAsync(controller.ChunkStream, retCommand);
}
}
}
catch (Exception e)
{
var retCommand = new ReturnResultCommandMessage(command.AmfEncodingVersion);
retCommand.IsSuccess = false;
retCommand.TranscationID = command.TranscationID;
retCommand.CommandObject = null;
retCommand.ReturnValue = e.Message;
_ = controller.MessageStream.SendMessageAsync(controller.ChunkStream, retCommand);
return;
}
}
19
View Source File : Config.cs
License : Apache License 2.0
Project Creator : aadreja
License : Apache License 2.0
Project Creator : aadreja
static ColumnAttribute ParseColumn(string propertyName, string columnName, DbType columnDbType, string replacedle)
{
PropertyInfo property = typeof(EnreplacedyDefault).GetProperty(propertyName);
ColumnAttribute column = new ColumnAttribute()
{
Name = columnName,
ColumnDbType = columnDbType,
IsColumnDbTypeDefined = true,
replacedle = replacedle,
};
column.SetPropertyInfo(property, typeof(EnreplacedyDefault));
return column;
}
19
View Source File : Helper.cs
License : Apache License 2.0
Project Creator : aadreja
License : Apache License 2.0
Project Creator : aadreja
internal static Func<object, object> CreateGetProperty(Type enreplacedyType, string propertyName)
{
MethodInfo mi = enreplacedyType.GetProperty(propertyName).GetMethod;
if (mi == null) return null; //no get property
Type[] args = new Type[] { typeof(object) };
DynamicMethod method = new DynamicMethod("Get_" + enreplacedyType.Name + "_" + propertyName, typeof(object), args, enreplacedyType.Module, true);
ILGenerator getIL = method.GetILGenerator();
getIL.DeclareLocal(typeof(object));
getIL.Emit(OpCodes.Ldarg_0); //Load the first argument
//(target object)
//Cast to the source type
getIL.Emit(OpCodes.Castclreplaced, enreplacedyType);
//Get the property value
getIL.EmitCall(OpCodes.Call, mi, null);
if (mi.ReturnType.IsValueType)
{
getIL.Emit(OpCodes.Box, mi.ReturnType);
//Box if necessary
}
getIL.Emit(OpCodes.Stloc_0); //Store it
getIL.Emit(OpCodes.Ldloc_0);
getIL.Emit(OpCodes.Ret);
var funcType = System.Linq.Expressions.Expression.GetFuncType(typeof(object), typeof(object));
return (Func<object, object>)method.CreateDelegate(funcType);
}
19
View Source File : Helper.cs
License : Apache License 2.0
Project Creator : aadreja
License : Apache License 2.0
Project Creator : aadreja
internal static Action<object, object> CreateSetProperty(Type enreplacedyType, string propertyName)
{
MethodInfo mi = enreplacedyType.GetProperty(propertyName).SetMethod;
if (mi == null) return null; //no set property
Type[] args = new Type[] { typeof(object), typeof(object) };
DynamicMethod method = new DynamicMethod("Set_" + enreplacedyType.Name + "_" + propertyName, null, args, enreplacedyType.Module, true);
ILGenerator setIL = method.GetILGenerator();
Type paramType = mi.GetParameters()[0].ParameterType;
//setIL.DeclareLocal(typeof(object));
setIL.Emit(OpCodes.Ldarg_0); //Load the first argument [Enreplacedy]
//(target object)
//Cast to the source type
setIL.Emit(OpCodes.Castclreplaced, enreplacedyType);
setIL.Emit(OpCodes.Ldarg_1); //Load the second argument [Value]
//(value object)
if (paramType.IsValueType)
{
setIL.Emit(OpCodes.Unbox, paramType); //Unbox it
if (mTypeHash[paramType] != null) //and load
{
OpCode load = (OpCode)mTypeHash[paramType];
setIL.Emit(load);
}
else
{
setIL.Emit(OpCodes.Ldobj, paramType);
}
}
else
{
setIL.Emit(OpCodes.Castclreplaced, paramType); //Cast clreplaced
}
setIL.EmitCall(OpCodes.Callvirt, mi, null); //Set the property value
setIL.Emit(OpCodes.Ret);
var actionType = System.Linq.Expressions.Expression.GetActionType(typeof(object), typeof(object));
return (Action<object, object>)method.CreateDelegate(actionType);
}
19
View Source File : VxFormGroup.cs
License : MIT License
Project Creator : Aaltuj
License : MIT License
Project Creator : Aaltuj
internal static void Add(string fieldIdentifier, VxFormGroup group, object modelInstance, VxFormLayoutOptions options)
{
// TODO: EXPANDO switch
var prop = modelInstance.GetType().GetProperty(fieldIdentifier);
var layoutAttr = prop.GetCustomAttribute<VxFormElementLayoutAttribute>();
var allRowLayoutAttributes = VxHelpers.GetAllAttributes<VxFormRowLayoutAttribute>(prop.DeclaringType);
// If no attribute is found use the name of the property
if (layoutAttr == null)
layoutAttr = new VxFormElementLayoutAttribute()
{
Label = GetLabel(fieldIdentifier, modelInstance)
};
PatchLayoutWithBuiltInAttributes(layoutAttr, prop);
// Check if row already exists
var foundRow = group.Rows.Find(value => value.Id == layoutAttr.RowId.ToString());
if (foundRow == null)
{
foundRow = VxFormRow.Create(layoutAttr, allRowLayoutAttributes.Find(x => x.Id == layoutAttr.RowId), options);
group.Rows.Add(foundRow); ;
}
var formColumn = VxFormElementDefinition.Create(fieldIdentifier, layoutAttr, modelInstance, options);
VxFormRow.AddColumn(foundRow, formColumn, options);
// WHen there is a VxFormRowLayout found use the name if specified, this also sets the row to combined labels
if (options.LabelOrientation == LabelOrientation.LEFT && foundRow.RowLayoutAttribute?.Label == null)
foundRow.Label = string.Join(", ", foundRow.Columns.ConvertAll(x => x.RenderOptions.Label));
}
19
View Source File : VxFormGroup.cs
License : MIT License
Project Creator : Aaltuj
License : MIT License
Project Creator : Aaltuj
private static string GetLabel(string fieldIdentifier, object modelInstance)
{
var modelType = modelInstance.GetType();
if (modelType == typeof(ExpandoObject))
{
return fieldIdentifier;
}
else
{
var prop = modelInstance
.GetType()
.GetProperty(fieldIdentifier);
var displayAttribute = prop
.GetCustomAttributes(typeof(DisplayAttribute), false)
.FirstOrDefault() as DisplayAttribute;
return displayAttribute != null ? displayAttribute.Name : fieldIdentifier;
}
}
19
View Source File : ValueReference.cs
License : MIT License
Project Creator : Aaltuj
License : MIT License
Project Creator : Aaltuj
public static void SetValue(object model, string key, TValue value)
{
var modelType = model.GetType();
if (modelType == typeof(ExpandoObject))
{
var accessor = ((IDictionary<string, object>)model);
accessor[key] = value;
}
else
{
var propertyInfo = modelType.GetProperty(key);
propertyInfo.SetValue(model, value);
}
}
19
View Source File : ValueReference.cs
License : MIT License
Project Creator : Aaltuj
License : MIT License
Project Creator : Aaltuj
public static TValue GetValue(object model, string key)
{
var modelType = model.GetType();
if (modelType == typeof(ExpandoObject))
{
var accessor = ((IDictionary<string, object>)model);
return (TValue)accessor[key];
}
else
{
var propertyInfo = modelType.GetProperty(key);
return (TValue) propertyInfo.GetValue(model);
}
}
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 : ActivationConfigurationTests.cs
License : MIT License
Project Creator : ababik
License : MIT License
Project Creator : ababik
[TestMethod]
public void ConfigureByConstructorAndParameters_InvalidParameter_Fail()
{
var user = new User(1, "Joe", "Doe");
var constructor = user.GetType().GetConstructor(new[] { typeof(string), typeof(string) });
var type = typeof(Employee);
var firstNameParameter = type.GetConstructor(new[] { typeof(Guid), typeof(string), typeof(string) }).GetParameters().Single(x => x.Name == "firstName");
var firstNameProperty = type.GetProperty("FirstName");
try
{
var config = new ActivationConfiguration()
.Configure(constructor, new Dictionary<ParameterInfo, PropertyInfo>() { [firstNameParameter] = firstNameProperty });
}
catch (Exception ex) when (ex.Message == $"Invalid parameter '{firstNameParameter.Name}'. Parameter must be a member of '{constructor.DeclaringType}' constructor.")
{
return;
}
replacedert.Fail();
}
19
View Source File : ActivationConfigurationTests.cs
License : MIT License
Project Creator : ababik
License : MIT License
Project Creator : ababik
[TestMethod]
public void ConfigureByConstructorAndParameters_InvalidProperty_Fail()
{
var user = new User(1, "Joe", "Doe");
var constructor = user.GetType().GetConstructor(new[] { typeof(int), typeof(string), typeof(string) });
var firstNameParameter = constructor.GetParameters().Single(x => x.Name == "firstName");
var firstNameProperty = typeof(Employee).GetProperty("FirstName");
try
{
var config = new ActivationConfiguration()
.Configure(constructor, new Dictionary<ParameterInfo, PropertyInfo>() { [firstNameParameter] = firstNameProperty });
}
catch (Exception ex) when (ex.Message == $"Invalid property '{firstNameProperty.Name}'. Must be a member of '{constructor.DeclaringType}'.")
{
return;
}
replacedert.Fail();
}
19
View Source File : V2Loader.cs
License : MIT License
Project Creator : Abdesol
License : MIT License
Project Creator : Abdesol
internal static SystemColorHighlightingBrush GetSystemColorBrush(IXmlLineInfo lineInfo, string name)
{
Debug.replacedert(name.StartsWith("SystemColors.", StringComparison.Ordinal));
string shortName = name.Substring(13);
var property = typeof(SystemColors).GetProperty(shortName + "Brush");
if (property == null)
throw Error(lineInfo, "Cannot find '" + name + "'.");
return new SystemColorHighlightingBrush(property);
}
19
View Source File : SupportMethods.cs
License : MIT License
Project Creator : abvogel
License : MIT License
Project Creator : abvogel
public static void SetSealedPropertyValue(this Enreplacedy enreplacedy, string sPropertyName, object value)
{
enreplacedy.GetType().GetProperty(sPropertyName).SetValue(enreplacedy, value, null);
}
19
View Source File : SupportMethods.cs
License : MIT License
Project Creator : abvogel
License : MIT License
Project Creator : abvogel
public static void SetSealedPropertyValue(this EnreplacedyMetadata enreplacedyMetadata, string sPropertyName, object value)
{
enreplacedyMetadata.GetType().GetProperty(sPropertyName).SetValue(enreplacedyMetadata, value, null);
}
19
View Source File : SupportMethods.cs
License : MIT License
Project Creator : abvogel
License : MIT License
Project Creator : abvogel
public static void SetSealedPropertyValue(this AttributeMetadata attributeMetadata, string sPropertyName, object value)
{
attributeMetadata.GetType().GetProperty(sPropertyName).SetValue(attributeMetadata, value, null);
}
19
View Source File : SupportMethods.cs
License : MIT License
Project Creator : abvogel
License : MIT License
Project Creator : abvogel
public static void SetSealedPropertyValue(this Microsoft.Xrm.Sdk.Metadata.ManyToManyRelationshipMetadata manyToManyRelationshipMetadata, string sPropertyName, object value)
{
manyToManyRelationshipMetadata.GetType().GetProperty(sPropertyName).SetValue(manyToManyRelationshipMetadata, value, null);
}
19
View Source File : PropertyObserverNode.cs
License : MIT License
Project Creator : Accelerider
License : MIT License
Project Creator : Accelerider
private static Func<T> GetPropertyGetter<T>(object owner, string propertyName)
{
var propertyInfo = owner.GetType().GetProperty(propertyName);
if (propertyInfo == null)
throw new InvalidOperationException($"No the property named \"{propertyName}\" in the {owner.GetType()} type. ");
var method = propertyInfo.GetGetMethod();
return method.ReturnType != typeof(T) && method.ReturnType.IsValueType
// Warning: Boxes the Value Type.
? Lambda<Func<T>>(Convert(Call(Constant(owner), method), typeof(T))).Compile()
: (Func<T>)Delegate.CreateDelegate(typeof(Func<T>), owner, propertyInfo.GetGetMethod());
}
19
View Source File : SheetFilter.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
public Predicate<object> GetFilter()
{
string properyName = FilterPropertyName;
switch (FilterPropertyName)
{
case "Export Name":
var m = FirstDigitOfLastNumberInString(FilterValue);
if (m == null)
{
return null;
}
return item => m == FirstDigitOfLastNumberInString((item as ExportSheet).FullExportName);
case "Number":
var n = FirstDigitOfLastNumberInString(FilterValue);
if (n == null)
{
return null;
}
return item => n == FirstDigitOfLastNumberInString((item as ExportSheet).SheetNumber);
case "Name":
properyName = "SheetDescription";
var noNumbers = Regex.Replace(FilterValue, "[0-9-]", @" ");
string[] parts = noNumbers.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
return item => parts.Any(item.GetType().GetProperty(properyName).GetValue(item, null).ToString().Contains);
case "Revision":
properyName = "SheetRevision";
break;
case "Revision Description":
properyName = "SheetRevisionDescription";
break;
case "Revision Date":
properyName = "SheetRevisionDate";
break;
case "Scale":
properyName = "Scale";
break;
case "North Point":
properyName = "NorthPointVisibilityString";
break;
default:
return null;
}
return item => item.GetType().GetProperty(properyName).GetValue(item, null).ToString().Equals(FilterValue, StringComparison.InvariantCulture);
}
19
View Source File : NeuralLearner.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence
private static object GetObjectPropertyValue(object src, string propName)
{
var result = src.GetType().GetProperty(propName).GetValue(src, null);
return result;
}
19
View Source File : RoslynDiagnosticService.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
private static PropertyInfo GetTaskResultPropertyInfo(Type diagnosticDataType)
{
Type genericIEnumerableType = typeof(IEnumerable<>).MakeGenericType(diagnosticDataType);
if (genericIEnumerableType == null)
return null;
Type genericTask = typeof(Task<>).MakeGenericType(genericIEnumerableType);
return genericTask?.GetProperty(nameof(Task<object>.Result));
}
19
View Source File : AnonymousTypeWrapper.cs
License : MIT License
Project Creator : adoconnection
License : MIT License
Project Creator : adoconnection
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
PropertyInfo propertyInfo = this.model.GetType().GetProperty(binder.Name);
if (propertyInfo == null)
{
result = null;
return false;
}
result = propertyInfo.GetValue(this.model, null);
if (result == null)
{
return true;
}
var type = result.GetType();
if (result.IsAnonymous())
{
result = new AnonymousTypeWrapper(result);
}
bool isEnumerable = typeof(IEnumerable).IsreplacedignableFrom(type);
if (isEnumerable && !(result is string))
{
result = ((IEnumerable<object>) result)
.Select(e =>
{
if (e.IsAnonymous())
{
return new AnonymousTypeWrapper(e);
}
return e;
})
.ToList();
}
return true;
}
19
View Source File : ConfigurationElementCollection.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected override object GetElementKey(ConfigurationElement element)
{
var pi = element.GetType().GetProperty("Name");
return pi.GetValue(element, null);
}
19
View Source File : CrmOrganizationServiceContext.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
object IUpdatable.GetValue(object targetResource, string propertyName)
{
Tracing.FrameworkInformation("CrmOrganizationServiceContext", "GetValue", "targetResource={0}, propertyName={1}", targetResource, propertyName);
var type = targetResource.GetType();
var pi = type.GetProperty(propertyName);
if (pi == null)
{
throw new DataServiceException("The target resource of type '{0}' does not contain a property named '{1}'.".FormatWith(type, propertyName));
}
return pi.GetValue(targetResource, null);
}
19
View Source File : EntityInfo.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private AttributeInfo LoadPrimaryKeyProperty()
{
var dataServiceKey = EnreplacedyType.GetFirstOrDefaultCustomAttribute<DataServiceKeyAttribute>();
var property = EnreplacedyType.GetProperty(dataServiceKey.KeyNames.First());
var crmPropertyAttribute = property.GetFirstOrDefaultCustomAttribute<AttributeLogicalNameAttribute>();
var pi = new AttributeInfo(property, crmPropertyAttribute);
return pi;
}
19
View Source File : CrmOrganizationServiceContext.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static Relationship GetRelationship(object targetResource, string propertyName)
{
var enreplacedyType = targetResource.GetType();
// find the relationship schema name
var propertyInfo = enreplacedyType.GetProperty(propertyName);
if (propertyInfo != null)
{
var relnAttribute = propertyInfo.GetFirstOrDefaultCustomAttribute<RelationshipSchemaNameAttribute>();
if (relnAttribute != null)
{
var relationship = relnAttribute.SchemaName.ToRelationship(relnAttribute.PrimaryEnreplacedyRole);
return relationship;
}
}
return propertyName.ToRelationship();
}
19
View Source File : SignUpAttributeElementCollection.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected override object GetElementKey(ConfigurationElement element)
{
var pi = element.GetType().GetProperty("LogicalName");
return pi.GetValue(element, null);
}
19
View Source File : IExpressionBuilderProvider.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected static Type GetReturnType(Type controlType, string propertyName)
{
return controlType.GetProperty(propertyName).PropertyType;
}
19
View Source File : CrmOrganizationServiceContext.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
void IUpdatable.SetValue(object targetResource, string propertyName, object propertyValue)
{
Tracing.FrameworkInformation("CrmOrganizationServiceContext", "SetValue", "targetResource={0}, propertyName={1}, propertyValue={2}", targetResource, propertyName, propertyValue);
var type = targetResource.GetType();
var pi = type.GetProperty(propertyName);
if (pi == null)
{
throw new DataServiceException("The target resource of type '{0}' does not contain a property named '{1}'.".FormatWith(type, propertyName));
}
if (pi.CanWrite && IsReadOnlyEnreplacedyProperty(targetResource, propertyName))
{
var value = ParseValue(propertyValue);
pi.SetValue(targetResource, value, null);
var target = targetResource as Enreplacedy;
if (target != null)
{
UpdateObject(target);
}
}
}
19
View Source File : Hotkeys.cs
License : MIT License
Project Creator : adrenak
License : MIT License
Project Creator : adrenak
[MenuItem("Edit/HotKeys/Toggle Lock &q")]
static void ToggleInspectorLock() {
if (_mouseOverWindow == null) {
if (!EditorPrefs.HasKey("LockableInspectorIndex"))
EditorPrefs.SetInt("LockableInspectorIndex", 0);
int i = EditorPrefs.GetInt("LockableInspectorIndex");
Type type = replacedembly.Getreplacedembly(typeof(Editor)).GetType("UnityEditor.InspectorWindow");
Object[] findObjectsOfTypeAll = Resources.FindObjectsOfTypeAll(type);
_mouseOverWindow = (EditorWindow)findObjectsOfTypeAll[i];
}
if (_mouseOverWindow != null && _mouseOverWindow.GetType().Name == "InspectorWindow") {
Type type = replacedembly.Getreplacedembly(typeof(Editor)).GetType("UnityEditor.InspectorWindow");
PropertyInfo propertyInfo = type.GetProperty("isLocked");
bool value = (bool)propertyInfo.GetValue(_mouseOverWindow, null);
propertyInfo.SetValue(_mouseOverWindow, !value, null);
_mouseOverWindow.Repaint();
}
}
19
View Source File : AutoFileSaver.cs
License : MIT License
Project Creator : adrianmteo
License : MIT License
Project Creator : adrianmteo
private void Model_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (ReadOnly)
{
return;
}
object[] attributes = typeof(T).GetProperty(e.PropertyName).GetCustomAttributes(typeof(XmlIgnoreAttribute), false);
if (attributes.Length > 0)
{
return;
}
Logger.Debug("Writing XML for '{0}' to file '{1}'", typeof(T).Name, Path);
if (sender is T model)
{
try
{
ObjectSerializer.SerializeObjectToFile(Path, model);
}
catch (Exception ex)
{
Logger.Error(ex.Message);
}
}
}
19
View Source File : Configuration.cs
License : MIT License
Project Creator : AdrianWilczynski
License : MIT License
Project Creator : AdrianWilczynski
public void Override(CommandBase command)
{
foreach (var property in typeof(Configuration).GetProperties())
{
if (property.GetValue(this) is object value)
{
typeof(CommandBase).GetProperty(property.Name).SetValue(command, value);
}
}
}
19
View Source File : EditorGUIHelper.cs
License : MIT License
Project Creator : AdultLink
License : MIT License
Project Creator : AdultLink
public static bool Header(string replacedle, SerializedProperty group, SerializedProperty enabledField, Action resetAction)
{
var field = ReflectionUtils.GetFieldInfoFromPath(enabledField.serializedObject.targetObject, enabledField.propertyPath);
object parent = null;
PropertyInfo prop = null;
if (field != null && field.IsDefined(typeof(GetSetAttribute), false))
{
var attr = (GetSetAttribute)field.GetCustomAttributes(typeof(GetSetAttribute), false)[0];
parent = ReflectionUtils.GetParentObject(enabledField.propertyPath, enabledField.serializedObject.targetObject);
prop = parent.GetType().GetProperty(attr.name);
}
var display = group == null || group.isExpanded;
var enabled = enabledField.boolValue;
var rect = GUILayoutUtility.GetRect(16f, 22f, FxStyles.header);
GUI.Box(rect, replacedle, FxStyles.header);
var toggleRect = new Rect(rect.x + 4f, rect.y + 4f, 13f, 13f);
var e = Event.current;
var popupRect = new Rect(rect.x + rect.width - FxStyles.paneOptionsIcon.width - 5f, rect.y + FxStyles.paneOptionsIcon.height / 2f + 1f, FxStyles.paneOptionsIcon.width, FxStyles.paneOptionsIcon.height);
GUI.DrawTexture(popupRect, FxStyles.paneOptionsIcon);
if (e.type == EventType.Repaint)
FxStyles.headerCheckbox.Draw(toggleRect, false, false, enabled, false);
if (e.type == EventType.MouseDown)
{
const float kOffset = 2f;
toggleRect.x -= kOffset;
toggleRect.y -= kOffset;
toggleRect.width += kOffset * 2f;
toggleRect.height += kOffset * 2f;
if (toggleRect.Contains(e.mousePosition))
{
enabledField.boolValue = !enabledField.boolValue;
if (prop != null)
prop.SetValue(parent, enabledField.boolValue, null);
e.Use();
}
else if (popupRect.Contains(e.mousePosition))
{
var popup = new GenericMenu();
popup.AddItem(GetContent("Reset"), false, () => resetAction());
popup.AddSeparator(string.Empty);
popup.AddItem(GetContent("Copy Settings"), false, () => CopySettings(group));
if (CanPaste(group))
popup.AddItem(GetContent("Paste Settings"), false, () => PasteSettings(group));
else
popup.AddDisabledItem(GetContent("Paste Settings"));
popup.ShowAsContext();
}
else if (rect.Contains(e.mousePosition) && group != null)
{
display = !display;
group.isExpanded = !group.isExpanded;
e.Use();
}
}
return display;
}
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
public override void Entry(IModHelper helper)
{
config = Helper.ReadConfig<ModConfig>();
if (!config.EnableMod)
return;
PMonitor = Monitor;
PHelper = helper;
mp = helper.Reflection.GetField<Multiplayer>(typeof(Game1), "multiplayer").GetValue();
myRand = new Random();
helper.Events.GameLoop.GameLaunched += HelperEvents.GameLoop_GameLaunched;
helper.Events.GameLoop.SaveLoaded += HelperEvents.GameLoop_SaveLoaded;
helper.Events.GameLoop.DayStarted += HelperEvents.GameLoop_DayStarted;
helper.Events.GameLoop.OneSecondUpdateTicked += HelperEvents.GameLoop_OneSecondUpdateTicked;
PathFindControllerPatches.Initialize(Monitor, config, helper);
Integrations.Initialize(Monitor, config, helper);
Divorce.Initialize(Monitor, config, helper);
NPCPatches.Initialize(Monitor, config, helper);
LocationPatches.Initialize(Monitor, config, helper);
FarmerPatches.Initialize(Monitor, config, helper);
UIPatches.Initialize(Monitor, config, helper);
EventPatches.Initialize(Monitor, config, helper);
HelperEvents.Initialize(Monitor, config, helper);
Misc.Initialize(Monitor, config, helper);
var harmony = new Harmony(ModManifest.UniqueID);
// npc patches
harmony.Patch(
original: AccessTools.Method(typeof(NPC), nameof(NPC.marriageDuties)),
postfix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_marriageDuties_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(NPC), nameof(NPC.getSpouse)),
prefix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_getSpouse_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(NPC), nameof(NPC.isRoommate)),
prefix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_isRoommate_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(NPC), nameof(NPC.isMarried)),
prefix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_isMarried_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(NPC), nameof(NPC.isMarriedOrEngaged)),
prefix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_isMarriedOrEngaged_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(NPC), nameof(NPC.tryToReceiveActiveObject)),
prefix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_tryToReceiveActiveObject_Prefix)),
transpiler: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_tryToReceiveActiveObject_Transpiler))
);
harmony.Patch(
original: AccessTools.Method(typeof(NPC), "engagementResponse"),
prefix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_engagementResponse_Prefix)),
postfix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_engagementResponse_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(NPC), nameof(NPC.playSleepingAnimation)),
postfix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_playSleepingAnimation_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(NPC), nameof(NPC.GetDispositionModifiedString)),
prefix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_GetDispositionModifiedString_Prefix)),
postfix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_GetDispositionModifiedString_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(NPC), "loadCurrentDialogue"),
prefix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_loadCurrentDialogue_Prefix)),
postfix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_loadCurrentDialogue_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(NPC), nameof(NPC.tryToRetrieveDialogue)),
prefix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_tryToRetrieveDialogue_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(NPC), nameof(NPC.checkAction)),
prefix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_checkAction_Prefix))
);
// Child patches
harmony.Patch(
original: typeof(Character).GetProperty("displayName").GetMethod,
postfix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.Character_displayName_Getter_Postfix))
);
// Path patches
harmony.Patch(
original: AccessTools.Constructor(typeof(PathFindController), new Type[] { typeof(Character), typeof(GameLocation), typeof(Point), typeof(int), typeof(bool), typeof(bool) }),
prefix: new HarmonyMethod(typeof(PathFindControllerPatches), nameof(PathFindControllerPatches.PathFindController_Prefix))
);
harmony.Patch(
original: AccessTools.Constructor(typeof(PathFindController), new Type[] { typeof(Character), typeof(GameLocation), typeof(Point), typeof(int), typeof(PathFindController.endBehavior) }),
prefix: new HarmonyMethod(typeof(PathFindControllerPatches), nameof(PathFindControllerPatches.PathFindController_Prefix))
);
harmony.Patch(
original: AccessTools.Constructor(typeof(PathFindController), new Type[] { typeof(Character), typeof(GameLocation), typeof(Point), typeof(int) }),
prefix: new HarmonyMethod(typeof(PathFindControllerPatches), nameof(PathFindControllerPatches.PathFindController_Prefix))
);
// Location patches
harmony.Patch(
original: AccessTools.Method(typeof(FarmHouse), nameof(FarmHouse.GetSpouseBed)),
postfix: new HarmonyMethod(typeof(LocationPatches), nameof(LocationPatches.FarmHouse_GetSpouseBed_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(FarmHouse), nameof(FarmHouse.getSpouseBedSpot)),
prefix: new HarmonyMethod(typeof(LocationPatches), nameof(LocationPatches.FarmHouse_getSpouseBedSpot_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(Beach), nameof(Beach.checkAction)),
prefix: new HarmonyMethod(typeof(LocationPatches), nameof(LocationPatches.Beach_checkAction_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(Beach), "resetLocalState"),
postfix: new HarmonyMethod(typeof(LocationPatches), nameof(LocationPatches.Beach_resetLocalState_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(GameLocation), "checkEventPrecondition"),
prefix: new HarmonyMethod(typeof(LocationPatches), nameof(LocationPatches.GameLocation_checkEventPrecondition_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(Desert), nameof(Desert.getDesertMerchantTradeStock)),
postfix: new HarmonyMethod(typeof(LocationPatches), nameof(LocationPatches.Desert_getDesertMerchantTradeStock_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(ManorHouse), nameof(ManorHouse.performAction)),
prefix: new HarmonyMethod(typeof(LocationPatches), nameof(LocationPatches.ManorHouse_performAction_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(GameLocation), nameof(GameLocation.answerDialogue)),
prefix: new HarmonyMethod(typeof(LocationPatches), nameof(LocationPatches.GameLocation_answerDialogue_prefix))
);
// pregnancy patches
harmony.Patch(
original: AccessTools.Method(typeof(Utility), nameof(Utility.pickPersonalFarmEvent)),
prefix: new HarmonyMethod(typeof(Pregnancy), nameof(Pregnancy.Utility_pickPersonalFarmEvent_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(QuestionEvent), nameof(QuestionEvent.setUp)),
prefix: new HarmonyMethod(typeof(Pregnancy), nameof(Pregnancy.QuestionEvent_setUp_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(BirthingEvent), nameof(BirthingEvent.setUp)),
prefix: new HarmonyMethod(typeof(Pregnancy), nameof(Pregnancy.BirthingEvent_setUp_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(BirthingEvent), nameof(BirthingEvent.tickUpdate)),
prefix: new HarmonyMethod(typeof(Pregnancy), nameof(Pregnancy.BirthingEvent_tickUpdate_Prefix))
);
// Farmer patches
harmony.Patch(
original: AccessTools.Method(typeof(Farmer), nameof(Farmer.doDivorce)),
prefix: new HarmonyMethod(typeof(FarmerPatches), nameof(FarmerPatches.Farmer_doDivorce_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(Farmer), nameof(Farmer.isMarried)),
prefix: new HarmonyMethod(typeof(FarmerPatches), nameof(FarmerPatches.Farmer_isMarried_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(Farmer), nameof(Farmer.getSpouse)),
prefix: new HarmonyMethod(typeof(FarmerPatches), nameof(FarmerPatches.Farmer_getSpouse_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(Farmer), nameof(Farmer.checkAction)),
prefix: new HarmonyMethod(typeof(FarmerPatches), nameof(FarmerPatches.Farmer_checkAction_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(Farmer), nameof(Farmer.GetSpouseFriendship)),
prefix: new HarmonyMethod(typeof(FarmerPatches), nameof(FarmerPatches.Farmer_GetSpouseFriendship_Prefix))
);
// UI patches
harmony.Patch(
original: AccessTools.Method(typeof(SocialPage), "drawNPCSlot"),
prefix: new HarmonyMethod(typeof(UIPatches), nameof(UIPatches.SocialPage_drawNPCSlot_prefix)),
transpiler: new HarmonyMethod(typeof(UIPatches), nameof(UIPatches.SocialPage_drawSlot_transpiler))
);
harmony.Patch(
original: AccessTools.Method(typeof(SocialPage), "drawFarmerSlot"),
transpiler: new HarmonyMethod(typeof(UIPatches), nameof(UIPatches.SocialPage_drawSlot_transpiler))
);
harmony.Patch(
original: typeof(DialogueBox).GetConstructor(new Type[] { typeof(List<string>) }),
prefix: new HarmonyMethod(typeof(UIPatches), nameof(UIPatches.DialogueBox_Prefix))
);
// Event patches
harmony.Patch(
original: AccessTools.Method(typeof(Event), nameof(Event.answerDialogueQuestion)),
prefix: new HarmonyMethod(typeof(EventPatches), nameof(EventPatches.Event_answerDialogueQuestion_Prefix))
);
}
19
View Source File : FileIO.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
public static void LoadTMXSpouseRooms()
{
try
{
Maps.tmxSpouseRooms.Clear();
var tmxlAPI = Helper.ModRegistry.GetApi("Platonymous.TMXLoader");
var tmxlreplacedembly = tmxlAPI?.GetType()?.replacedembly;
var tmxlModType = tmxlreplacedembly?.GetType("TMXLoader.TMXLoaderMod");
var tmxlEditorType = tmxlreplacedembly?.GetType("TMXLoader.TMXreplacedetEditor");
if (tmxlModType == null)
return;
var tmxlHelper = Helper.Reflection.GetField<IModHelper>(tmxlModType, "helper").GetValue();
foreach (var editor in tmxlHelper.Content.replacedetEditors)
{
try
{
if (editor == null)
continue;
if (!ReferenceEquals(editor.GetType(),tmxlEditorType)) continue;
if (editor.GetType().GetField("type", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(editor).ToString() != "SpouseRoom") continue;
string name = (string)tmxlEditorType.GetField("replacedetName").GetValue(editor);
if (name != "FarmHouse1_marriage") continue;
object edit = tmxlEditorType.GetField("edit", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(editor);
string info = (string)edit.GetType().GetProperty("info").GetValue(edit);
Map map = Helper.Reflection.GetField<Map>(editor, "newMap").GetValue();
if (map != null && !Maps.tmxSpouseRooms.ContainsKey(info))
{
Monitor.Log("Adding TMX spouse room for " + info, LogLevel.Debug);
Maps.tmxSpouseRooms.Add(info, map);
}
}
catch (Exception ex)
{
Monitor.Log($"Failed getting TMX spouse room data. Exception: {ex}", LogLevel.Debug);
}
}
}
catch (Exception ex)
{
Monitor.Log($"Failed getting TMX spouse room data. Exception: {ex}", LogLevel.Debug);
}
}
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
public override void Entry(IModHelper helper)
{
config = Helper.ReadConfig<ModConfig>();
if (!config.EnableMod)
return;
PMonitor = Monitor;
PHelper = helper;
mp = helper.Reflection.GetField<Multiplayer>(typeof(Game1), "multiplayer").GetValue();
myRand = new Random();
helper.Events.GameLoop.GameLaunched += HelperEvents.GameLoop_GameLaunched;
helper.Events.GameLoop.SaveLoaded += HelperEvents.GameLoop_SaveLoaded;
helper.Events.Input.ButtonPressed += HelperEvents.Input_ButtonPressed;
helper.Events.GameLoop.DayStarted += HelperEvents.GameLoop_DayStarted;
helper.Events.GameLoop.DayEnding += HelperEvents.GameLoop_DayEnding;
helper.Events.GameLoop.ReturnedToreplacedle += HelperEvents.GameLoop_ReturnedToreplacedle;
NPCPatches.Initialize(Monitor, config);
LocationPatches.Initialize(Monitor);
FarmerPatches.Initialize(Monitor, Helper);
Maps.Initialize(Monitor);
Kissing.Initialize(Monitor);
UIPatches.Initialize(Monitor, Helper);
EventPatches.Initialize(Monitor, Helper);
HelperEvents.Initialize(Monitor, Helper);
FileIO.Initialize(Monitor, Helper);
Misc.Initialize(Monitor, Helper, config);
Divorce.Initialize(Monitor, Helper);
FurniturePatches.Initialize(Monitor, Helper, config);
ObjectPatches.Initialize(Monitor, Helper, config);
NetWorldStatePatches.Initialize(Monitor, Helper, config);
var harmony = new Harmony(ModManifest.UniqueID);
// npc patches
harmony.Patch(
original: AccessTools.Method(typeof(NPC), nameof(NPC.marriageDuties)),
postfix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_marriageDuties_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(NPC), nameof(NPC.getSpouse)),
prefix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_getSpouse_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(NPC), nameof(NPC.isRoommate)),
prefix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_isRoommate_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(NPC), nameof(NPC.isMarried)),
prefix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_isMarried_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(NPC), nameof(NPC.isMarriedOrEngaged)),
prefix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_isMarriedOrEngaged_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(NPC), nameof(NPC.tryToReceiveActiveObject)),
prefix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_tryToReceiveActiveObject_Prefix)),
transpiler: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_tryToReceiveActiveObject_Transpiler)),
postfix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_tryToReceiveActiveObject_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(NPC), nameof(NPC.checkAction)),
prefix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_checkAction_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(NPC), nameof(NPC.spouseObstacleCheck)),
postfix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_spouseObstacleCheck_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(NPC), "engagementResponse"),
prefix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_engagementResponse_Prefix)),
postfix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_engagementResponse_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(NPC), nameof(NPC.playSleepingAnimation)),
postfix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_playSleepingAnimation_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(NPC), nameof(NPC.GetDispositionModifiedString)),
prefix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_GetDispositionModifiedString_Prefix)),
postfix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_GetDispositionModifiedString_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(NPC), "loadCurrentDialogue"),
prefix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_loadCurrentDialogue_Prefix)),
postfix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_loadCurrentDialogue_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(NPC), nameof(NPC.tryToRetrieveDialogue)),
prefix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_tryToRetrieveDialogue_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(NPC), nameof(NPC.setSpouseRoomMarriageDialogue)),
prefix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_setSpouseRoomMarriageDialogue_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(NPC), nameof(NPC.setRandomAfternoonMarriageDialogue)),
prefix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.NPC_setRandomAfternoonMarriageDialogue_Prefix))
);
// Child patches
harmony.Patch(
original: typeof(Character).GetProperty("displayName").GetMethod,
postfix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.Character_displayName_Getter_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(Child), nameof(Child.reloadSprite)),
postfix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.Child_reloadSprite_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(Child), nameof(Child.resetForPlayerEntry)),
postfix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.Child_resetForPlayerEntry_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(Child), nameof(Child.dayUpdate)),
prefix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.Child_dayUpdate_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(Child), nameof(Child.isInCrib)),
prefix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.Child_isInCrib_Prefix))
);
/*
harmony.Patch(
original: AccessTools.Method(typeof(Child), nameof(Child.tenMinuteUpdate)),
postfix: new HarmonyMethod(typeof(NPCPatches), nameof(NPCPatches.Child_tenMinuteUpdate_Postfix))
);
*/
// Location patches
harmony.Patch(
original: AccessTools.Method(typeof(Beach), nameof(Beach.checkAction)),
prefix: new HarmonyMethod(typeof(LocationPatches), nameof(LocationPatches.Beach_checkAction_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(ManorHouse), nameof(ManorHouse.performAction)),
prefix: new HarmonyMethod(typeof(LocationPatches), nameof(LocationPatches.ManorHouse_performAction_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(FarmHouse), nameof(FarmHouse.checkAction)),
postfix: new HarmonyMethod(typeof(LocationPatches), nameof(LocationPatches.FarmHouse_checkAction_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(FarmHouse), nameof(FarmHouse.updateFarmLayout)),
postfix: new HarmonyMethod(typeof(LocationPatches), nameof(LocationPatches.FarmHouse_updateFarmLayout_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(FarmHouse), nameof(FarmHouse.getWalls)),
postfix: new HarmonyMethod(typeof(LocationPatches), nameof(LocationPatches.FarmHouse_getWalls_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(FarmHouse), nameof(FarmHouse.getFloors)),
postfix: new HarmonyMethod(typeof(LocationPatches), nameof(LocationPatches.FarmHouse_getFloors_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(GameLocation), nameof(GameLocation.performAction)),
prefix: new HarmonyMethod(typeof(LocationPatches), nameof(LocationPatches.GameLocation_performAction_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(GameLocation), nameof(GameLocation.answerDialogue)),
prefix: new HarmonyMethod(typeof(LocationPatches), nameof(LocationPatches.GameLocation_answerDialogue_prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(FarmHouse), "resetLocalState"),
postfix: new HarmonyMethod(typeof(LocationPatches), nameof(LocationPatches.FarmHouse_resetLocalState_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(Beach), "resetLocalState"),
postfix: new HarmonyMethod(typeof(LocationPatches), nameof(LocationPatches.Beach_resetLocalState_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(GameLocation), "checkEventPrecondition"),
prefix: new HarmonyMethod(typeof(LocationPatches), nameof(LocationPatches.GameLocation_checkEventPrecondition_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(FarmHouse), nameof(FarmHouse.performTenMinuteUpdate)),
postfix: new HarmonyMethod(typeof(LocationPatches), nameof(LocationPatches.FarmHouse_performTenMinuteUpdate_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(Desert), nameof(Desert.getDesertMerchantTradeStock)),
postfix: new HarmonyMethod(typeof(LocationPatches), nameof(LocationPatches.Desert_getDesertMerchantTradeStock_Postfix))
);
// pregnancy patches
harmony.Patch(
original: AccessTools.Method(typeof(Utility), nameof(Utility.pickPersonalFarmEvent)),
prefix: new HarmonyMethod(typeof(Pregnancy), nameof(Pregnancy.Utility_pickPersonalFarmEvent_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(QuestionEvent), nameof(QuestionEvent.setUp)),
prefix: new HarmonyMethod(typeof(Pregnancy), nameof(Pregnancy.QuestionEvent_setUp_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(BirthingEvent), nameof(BirthingEvent.setUp)),
prefix: new HarmonyMethod(typeof(Pregnancy), nameof(Pregnancy.BirthingEvent_setUp_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(BirthingEvent), nameof(BirthingEvent.tickUpdate)),
prefix: new HarmonyMethod(typeof(Pregnancy), nameof(Pregnancy.BirthingEvent_tickUpdate_Prefix))
);
// Farmer patches
harmony.Patch(
original: AccessTools.Method(typeof(Farmer), nameof(Farmer.doDivorce)),
prefix: new HarmonyMethod(typeof(FarmerPatches), nameof(FarmerPatches.Farmer_doDivorce_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(Farmer), nameof(Farmer.isMarried)),
prefix: new HarmonyMethod(typeof(FarmerPatches), nameof(FarmerPatches.Farmer_isMarried_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(Farmer), nameof(Farmer.getSpouse)),
prefix: new HarmonyMethod(typeof(FarmerPatches), nameof(FarmerPatches.Farmer_getSpouse_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(Farmer), nameof(Farmer.checkAction)),
prefix: new HarmonyMethod(typeof(FarmerPatches), nameof(FarmerPatches.Farmer_checkAction_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(Farmer), nameof(Farmer.GetSpouseFriendship)),
prefix: new HarmonyMethod(typeof(FarmerPatches), nameof(FarmerPatches.Farmer_GetSpouseFriendship_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(Farmer), nameof(Farmer.getChildren)),
prefix: new HarmonyMethod(typeof(FarmerPatches), nameof(FarmerPatches.Farmer_getChildren_Prefix))
);
// UI patches
harmony.Patch(
original: AccessTools.Method(typeof(SocialPage), "drawNPCSlot"),
prefix: new HarmonyMethod(typeof(UIPatches), nameof(UIPatches.SocialPage_drawNPCSlot_prefix)),
transpiler: new HarmonyMethod(typeof(UIPatches), nameof(UIPatches.SocialPage_drawSlot_transpiler))
);
harmony.Patch(
original: AccessTools.Method(typeof(SocialPage), "drawFarmerSlot"),
transpiler: new HarmonyMethod(typeof(UIPatches), nameof(UIPatches.SocialPage_drawSlot_transpiler))
);
harmony.Patch(
original: typeof(DialogueBox).GetConstructor(new Type[] { typeof(List<string>) }),
prefix: new HarmonyMethod(typeof(UIPatches), nameof(UIPatches.DialogueBox_Prefix))
);
// Event patches
harmony.Patch(
original: AccessTools.Method(typeof(Event), nameof(Event.answerDialogueQuestion)),
prefix: new HarmonyMethod(typeof(EventPatches), nameof(EventPatches.Event_answerDialogueQuestion_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(Event), "setUpCharacters"),
postfix: new HarmonyMethod(typeof(EventPatches), nameof(EventPatches.Event_setUpCharacters_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(Event), nameof(Event.command_playSound)),
prefix: new HarmonyMethod(typeof(EventPatches), nameof(EventPatches.Event_command_playSound_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(Event), nameof(Event.command_loadActors)),
prefix: new HarmonyMethod(typeof(EventPatches), nameof(EventPatches.Event_command_loadActors_Prefix)),
postfix: new HarmonyMethod(typeof(EventPatches), nameof(EventPatches.Event_command_loadActors_Postfix))
);
// Object patches
harmony.Patch(
original: AccessTools.Method(typeof(Object), nameof(Object.draw), new Type[] { typeof(SpriteBatch), typeof(int), typeof(int), typeof(float) }),
prefix: new HarmonyMethod(typeof(ObjectPatches), nameof(ObjectPatches.Object_draw_Prefix))
);
// Furniture patches
harmony.Patch(
original: AccessTools.Method(typeof(BedFurniture), nameof(BedFurniture.draw), new Type[] { typeof(SpriteBatch), typeof(int), typeof(int), typeof(float) }),
prefix: new HarmonyMethod(typeof(FurniturePatches), nameof(FurniturePatches.BedFurniture_draw_Prefix))
);
// Game1 patches
harmony.Patch(
original: AccessTools.Method(typeof(Game1), nameof(Game1.prepareSpouseForWedding)),
prefix: new HarmonyMethod(typeof(Game1Patches), nameof(Game1Patches.prepareSpouseForWedding_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(Game1), nameof(Game1.getCharacterFromName), new Type[] { typeof(string), typeof(bool), typeof(bool) }),
prefix: new HarmonyMethod(typeof(Game1Patches), nameof(Game1Patches.getCharacterFromName_Prefix))
);
// NetWorldState patch
harmony.Patch(
original: AccessTools.Method(typeof(NetWorldState), nameof(NetWorldState.hasWorldStateID)),
prefix: new HarmonyMethod(typeof(NetWorldStatePatches), nameof(NetWorldStatePatches.hasWorldStateID_Prefix))
);
}
19
View Source File : IRCompiler.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a
License : GNU General Public License v3.0
Project Creator : Aekras1a
void ReadType(Node node, ref ASTType type, ref TypeSig rawType) {
for (int i = 0; i < node.Count; i++) {
var child = node[i];
if (child.Id == (int)IRConstants.ASTTYPE) {
type = (ASTType)Enum.Parse(typeof(ASTType), ((Token)child).Image);
}
else if (child.Id == (int)IRConstants.RAW_TYPE) {
var propertyName = ((Token)child[0]).Image;
var property = typeof(ICorLibTypes).GetProperty(propertyName);
rawType = (TypeSig)property.GetValue(module.CorLibTypes, null);
}
}
}
19
View Source File : IStateWrittenInstructionInjector.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
public void InjectInstruction(ILProcessor ilProcessor, Instruction originInstruction,
ModuleDefinition moduleDefinition)
{
ilProcessor.Body.SimplifyMacros();
var localValCount = ilProcessor.Body.Variables.Count;
ilProcessor.Body.Variables.Add(new VariableDefinition(moduleDefinition.ImportReference(typeof(object))));
var stocInstruction =
ilProcessor.Create(OpCodes.Stloc_S, ilProcessor.Body.Variables[localValCount]); // pop to local val
ilProcessor.InsertBefore(originInstruction, stocInstruction);
var ldThisInstruction = ilProcessor.Create(OpCodes.Ldarg_0); // this
ilProcessor.InsertAfter(stocInstruction, ldThisInstruction);
var getContextInstruction = ilProcessor.Create(OpCodes.Call,
moduleDefinition.ImportReference(typeof(CSharpSmartContractAbstract).GetProperty("Context")
.GetMethod)); // get_Context
ilProcessor.InsertAfter(ldThisInstruction, getContextInstruction);
var ldlocInstruction =
ilProcessor.Create(OpCodes.Ldloc_S, ilProcessor.Body.Variables[localValCount]); // load local val
ilProcessor.InsertAfter(getContextInstruction, ldlocInstruction);
var callInstruction = ilProcessor.Create(OpCodes.Callvirt, moduleDefinition.ImportReference(
typeof(CSharpSmartContractContext).GetMethod(nameof(CSharpSmartContractContext.ValidateStateSize))));
ilProcessor.InsertAfter(ldlocInstruction, callInstruction);
ilProcessor.Body.OptimizeMacros();
}
See More Examples