Here are the examples of the csharp api System.Reflection.FieldInfo.GetValue(object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
3506 Examples
19
View Source File : CelesteNetDebugMapComponent.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
private void VerifyArea() {
AreaKey area = (AreaKey) f_MapEditor_area.GetValue(null);
if (LastArea == null || LastArea.Value.ID != area.ID || LastArea.Value.Mode != area.Mode) {
lock (Ghosts) {
LastArea = area;
Cleanup();
foreach (DataPlayerFrame frame in Context.Main.LastFrames.Values.ToArray())
Handle(null, frame);
}
}
}
19
View Source File : CelesteNetDebugMapComponent.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
private void OnMapEditorRender(On.Celeste.Editor.MapEditor.orig_Render orig, MapEditor self) {
orig(self);
AreaKey? area = LastArea;
string sid = area?.SID;
AreaMode mode = area?.Mode ?? (AreaMode) (-1);
Camera camera = (Camera) f_MapEditor_Camera.GetValue(null);
// Adapted from Everest key rendering code.
lock (Ghosts) {
MDraw.SpriteBatch.Begin(
SpriteSortMode.Deferred,
BlendState.AlphaBlend,
SamplerState.PointClamp,
DepthStencilState.None,
RasterizerState.CullNone,
null,
camera.Matrix * Engine.ScreenMatrix
);
foreach (DebugMapGhost ghost in Ghosts.Values)
if (ghost.SID == sid && ghost.Mode == mode)
MDraw.Rect(ghost.Position.X / 8f, ghost.Position.Y / 8f - 1f, 1f, 1f, Color.HotPink);
MDraw.SpriteBatch.End();
MDraw.SpriteBatch.Begin(
SpriteSortMode.Deferred,
BlendState.AlphaBlend,
SamplerState.LinearClamp,
DepthStencilState.None,
RasterizerState.CullNone,
null,
Engine.ScreenMatrix
);
foreach (DebugMapGhost ghost in Ghosts.Values) {
if (ghost.SID != sid || ghost.Mode != mode)
continue;
Vector2 pos = new(ghost.Position.X / 8f + 0.5f, ghost.Position.Y / 8f - 1.5f);
pos -= camera.Position;
pos = new((float) Math.Round(pos.X), (float) Math.Round(pos.Y));
pos *= camera.Zoom;
pos += new Vector2(960f, 540f);
CelesteNetClientFont.DrawOutline(
ghost.Name,
pos,
new(0.5f, 1f),
Vector2.One * 0.5f,
Color.White * 0.8f,
2f, Color.Black * 0.5f
);
}
MDraw.SpriteBatch.End();
}
}
19
View Source File : CelesteNetKillGhostNetComponent.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public override void Update(GameTime gameTime) {
base.Update(gameTime);
if (m_GhostNetModule_Client?.GetValue(GhostNetModule) != null) {
Context.Status.Set("Disconnected from CelesteNet, connected to GhostNet", 10, false);
Settings.Connected = false;
}
}
19
View Source File : CelesteNetClientUtils.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public static bool GetWasDashB(this Player self)
=> (bool) f_Player_wasDashB.GetValue(self);
19
View Source File : CelesteNetClientUtils.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public static bool GetUpdateHair(this Level self)
=> (bool) f_Level_updateHair.GetValue(self);
19
View Source File : CelesteNetClientUtils.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public static TrailManager.Snapshot[] GetSnapshots(this TrailManager self)
=> (TrailManager.Snapshot[]) f_TrailManager_shapshots.GetValue(self);
19
View Source File : CelesteNetClientUtils.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public static int AddState(this StateMachine machine, Func<int> onUpdate, Func<IEnumerator> coroutine = null, Action begin = null, Action end = null) {
Action[] begins = (Action[]) f_StateMachine_begins.GetValue(machine);
Func<int>[] updates = (Func<int>[]) f_StateMachine_updates.GetValue(machine);
Action[] ends = (Action[]) f_StateMachine_ends.GetValue(machine);
Func<IEnumerator>[] coroutines = (Func<IEnumerator>[]) f_StateMachine_coroutines.GetValue(machine);
int nextIndex = begins.Length;
Array.Resize(ref begins, begins.Length + 1);
Array.Resize(ref updates, begins.Length + 1);
Array.Resize(ref ends, begins.Length + 1);
Array.Resize(ref coroutines, coroutines.Length + 1);
f_StateMachine_begins.SetValue(machine, begins);
f_StateMachine_updates.SetValue(machine, updates);
f_StateMachine_ends.SetValue(machine, ends);
f_StateMachine_coroutines.SetValue(machine, coroutines);
machine.SetCallbacks(nextIndex, onUpdate, coroutine, begin, end);
return nextIndex;
}
19
View Source File : DataContext.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public void RescanDataTypes(Type[] types) {
foreach (Type type in types) {
if (type.IsAbstract)
continue;
if (typeof(DataType).IsreplacedignableFrom(type)) {
RuntimeHelpers.RunClreplacedConstructor(type.TypeHandle);
string? id = null;
string? source = null;
for (Type parent = type; parent != typeof(object) && id.IsNullOrEmpty() && source.IsNullOrEmpty(); parent = parent.BaseType ?? typeof(object)) {
id = parent.GetField("DataID", BindingFlags.Public | BindingFlags.Static)?.GetValue(null) as string;
source = parent.GetField("DataSource", BindingFlags.Public | BindingFlags.Static)?.GetValue(null) as string;
}
if (id.IsNullOrEmpty()) {
Logger.Log(LogLevel.WRN, "data", $"Found data type {type.FullName} but no DataID");
continue;
}
if (source.IsNullOrEmpty()) {
Logger.Log(LogLevel.WRN, "data", $"Found data type {type.FullName} but no DataSource");
continue;
}
if (IDToDataType.ContainsKey(id)) {
Logger.Log(LogLevel.WRN, "data", $"Found data type {type.FullName} but conflicting ID {id}");
continue;
}
Logger.Log(LogLevel.INF, "data", $"Found data type {type.FullName} with ID {id}");
IDToDataType[id] = type;
DataTypeToID[type] = id;
DataTypeToSource[type] = source;
} else if (typeof(MetaType).IsreplacedignableFrom(type)) {
RuntimeHelpers.RunClreplacedConstructor(type.TypeHandle);
string? id = null;
for (Type parent = type; parent != typeof(object) && id.IsNullOrEmpty(); parent = parent.BaseType ?? typeof(object)) {
id = parent.GetField("MetaID", BindingFlags.Public | BindingFlags.Static)?.GetValue(null) as string;
}
if (id.IsNullOrEmpty()) {
Logger.Log(LogLevel.WRN, "data", $"Found meta type {type.FullName} but no MetaID");
continue;
}
if (IDToMetaType.ContainsKey(id)) {
Logger.Log(LogLevel.WRN, "data", $"Found meta type {type.FullName} but conflicting ID {id}");
continue;
}
Logger.Log(LogLevel.INF, "data", $"Found meta type {type.FullName} with ID {id}");
IDToMetaType[id] = type;
MetaTypeToID[type] = id;
}
}
}
19
View Source File : XnaToFnaHelper.cs
License : zlib License
Project Creator : 0x0ade
License : zlib License
Project Creator : 0x0ade
public static void PlatformHook(string name) {
Type t_Helper = typeof(XnaToFnaHelper);
replacedembly fna = replacedembly.Getreplacedembly(typeof(Game));
FieldInfo field = fna.GetType("Microsoft.Xna.Framework.FNAPlatform").GetField(name);
// Store the original delegate into fna_name.
t_Helper.GetField($"fna_{name}").SetValue(null, field.GetValue(null));
// Replace the value with the new method.
field.SetValue(null, Delegate.CreateDelegate(fna.GetType($"Microsoft.Xna.Framework.FNAPlatform+{name}Func"), t_Helper.GetMethod(name)));
}
19
View Source File : XnaToFnaUtil.Processor.cs
License : zlib License
Project Creator : 0x0ade
License : zlib License
Project Creator : 0x0ade
public OpCode ShortToLongOp(OpCode op) {
string name = Enum.GetName(typeof(Code), op.Code);
if (!name.EndsWith("_S"))
return op;
return (OpCode?) typeof(OpCodes).GetField(name.Substring(0, name.Length - 2))?.GetValue(null) ?? op;
}
19
View Source File : XnaToFnaUtil.Processor.cs
License : zlib License
Project Creator : 0x0ade
License : zlib License
Project Creator : 0x0ade
public OpCode LongToShortOp(OpCode op) {
string name = Enum.GetName(typeof(Code), op.Code);
if (name.EndsWith("_S"))
return op;
return (OpCode?) typeof(OpCodes).GetField(name + "_S")?.GetValue(null) ?? op;
}
19
View Source File : SequenceLevel.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 0xC0000054
private static IReadOnlyDictionary<byte, SequenceLevel> CreateSequenceLevelMap()
{
FieldInfo[] fieldInfos = typeof(SequenceLevel).GetFields(BindingFlags.Public | BindingFlags.Static);
Dictionary<byte, SequenceLevel> map = new Dictionary<byte, SequenceLevel>(fieldInfos.Length);
for (int i = 0; i < fieldInfos.Length; i++)
{
FieldInfo fieldInfo = fieldInfos[i];
if (fieldInfo.FieldType == typeof(SequenceLevel))
{
SequenceLevel item = (SequenceLevel)fieldInfo.GetValue(null);
map.Add(item.Value, item);
}
}
return map;
}
19
View Source File : ExpressionResovle.cs
License : Apache License 2.0
Project Creator : 1448376744
License : Apache License 2.0
Project Creator : 1448376744
public object VisitConstantValue(Expression expression)
{
var names = new Stack<string>();
var exps = new Stack<Expression>();
var mifs = new Stack<MemberInfo>();
if (expression is ConstantExpression constant)
return constant.Value;
else if (expression is MemberExpression)
{
var temp = expression;
object value = null;
while (temp is MemberExpression memberExpression)
{
names.Push(memberExpression.Member.Name);
exps.Push(memberExpression.Expression);
mifs.Push(memberExpression.Member);
temp = memberExpression.Expression;
}
foreach (var name in names)
{
var exp = exps.Pop();
var mif = mifs.Pop();
if (exp is ConstantExpression cex)
value = cex.Value;
if (mif is PropertyInfo pif)
value = pif.GetValue(value);
else if (mif is FieldInfo fif)
value = fif.GetValue(value);
}
return value;
}
else
{
return Expression.Lambda(expression).Compile().DynamicInvoke();
}
}
19
View Source File : TypeUtils.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static IEnumerable<KeyValuePair<string, object>> GetPublicMembersWithDynamicObject(this object value)
{
DEBUG.replacedert(value != null);
Type t = value.GetType();
foreach (FieldInfo p in t.GetFields(BindingFlags.Public | BindingFlags.Instance))
{
yield return new KeyValuePair<string, object>(p.Name, p.GetValue(value));
}
foreach (PropertyInfo p in t.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (p.GetIndexParameters().Length == 0 && p.CanRead && p.CanWrite)
{
yield return new KeyValuePair<string, object>(p.Name, p.GetValue(value));
}
}
}
19
View Source File : DbSetSync.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
void AddOrUpdateNavigateList(TEnreplacedy item) {
Type itemType = null;
foreach (var prop in _table.Properties) {
if (_table.ColumnsByCsIgnore.ContainsKey(prop.Key)) continue;
if (_table.ColumnsByCs.ContainsKey(prop.Key)) continue;
object propVal = null;
if (itemType == null) itemType = item.GetType();
if (_table.TypeLazy != null && itemType == _table.TypeLazy) {
var lazyField = _dicLazyIsSetField.GetOrAdd(_table.TypeLazy, tl => new ConcurrentDictionary<string, FieldInfo>()).GetOrAdd(prop.Key, propName =>
_table.TypeLazy.GetField($"__lazy__{propName}", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance));
if (lazyField != null) {
var lazyFieldValue = (bool)lazyField.GetValue(item);
if (lazyFieldValue == false) continue;
}
propVal = prop.Value.GetValue(item);
} else {
propVal = prop.Value.GetValue(item);
if (propVal == null) continue;
}
var tref = _table.GetTableRef(prop.Key, true);
if (tref == null) continue;
switch(tref.RefType) {
case Internal.Model.TableRefType.OneToOne:
case Internal.Model.TableRefType.ManyToOne:
case Internal.Model.TableRefType.ManyToMany:
continue;
case Internal.Model.TableRefType.OneToMany:
var propValEach = propVal as IEnumerable;
if (propValEach == null) continue;
object dbset = null;
MethodInfo dbsetAddOrUpdate = null;
foreach (var propValItem in propValEach) {
if (dbset == null) {
dbset = _ctx.Set(tref.RefEnreplacedyType);
dbsetAddOrUpdate = dbset.GetType().GetMethod("AddOrUpdate", new Type[] { tref.RefEnreplacedyType });
}
for (var colidx = 0; colidx < tref.Columns.Count; colidx++) {
tref.RefColumns[colidx].Table.Properties[tref.RefColumns[colidx].CsName]
.SetValue(propValItem, tref.Columns[colidx].Table.Properties[tref.Columns[colidx].CsName].GetValue(item));
}
dbsetAddOrUpdate.Invoke(dbset, new object[] { propValItem });
}
break;
}
}
}
19
View Source File : TransformCopyTest.cs
License : MIT License
Project Creator : 39M
License : MIT License
Project Creator : 39M
private void replacedertObjectsEqual(object a, object b) {
if ((a == null) != (b == null)) {
replacedert.Fail("One object was null an the other was not.");
return;
}
Type typeA = a.GetType();
Type typeB = b.GetType();
if (typeA != typeB) {
replacedert.Fail("Type " + typeA + " is not equal to type " + typeB + ".");
}
if (typeA.IsValueType) {
replacedert.That(a, Is.EqualTo(b));
return;
}
if (a is IList) {
IList aList = a as IList;
IList bList = b as IList;
replacedert.That(aList.Count, Is.EqualTo(bList.Count));
for (int i = 0; i < aList.Count; i++) {
replacedertObjectsEqual(aList[i], bList[i]);
}
} else {
FieldInfo[] fields = typeA.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields) {
replacedertObjectsEqual(field.GetValue(a), field.GetValue(b));
}
PropertyInfo[] properties = typeA.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties) {
if (property.GetIndexParameters().Length == 0) {
object propA;
try {
propA = property.GetValue(a, null);
} catch (Exception exceptionA) {
try {
property.GetValue(b, null);
replacedert.Fail("One property threw an exception where the other did not.");
return;
} catch (Exception exceptionB) {
replacedert.That(exceptionA.GetType(), Is.EqualTo(exceptionB.GetType()), "Both properties threw exceptions but their types were different.");
return;
}
}
object propB = property.GetValue(b, null);
replacedertObjectsEqual(propA, propB);
}
}
}
}
19
View Source File : CommandManager.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public void AddCommand(CommandData commandData)
{
if (commandData == null) return;
CommandData target;
switch (commandData.dataType)
{
default:
target = new CommandData();
break;
}
FieldInfo[] fieldInfos = target.GetType().GetFields();
foreach (FieldInfo item in fieldInfos)
{
item.SetValue(target, item.GetValue(commandData));
}
commandDataList.Add(target);
}
19
View Source File : LogConfigUtil.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public static string GetStackTrace()
{
Type consoleWindowType = typeof(EditorWindow).replacedembly.GetType("UnityEditor.ConsoleWindow");
FieldInfo fieldInfo = consoleWindowType.GetField("ms_ConsoleWindow", BindingFlags.Static | BindingFlags.NonPublic);
object obj = fieldInfo.GetValue(null);
if (obj != null)
{
if (obj == (object)EditorWindow.focusedWindow)
{
fieldInfo = consoleWindowType.GetField("m_ActiveText", BindingFlags.Instance | BindingFlags.NonPublic);
return fieldInfo.GetValue(obj).ToString();
}
}
return string.Empty;
}
19
View Source File : ObjectTypeUtil.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public static void Draw(object obj, int indentLevel)
{
EditorGUILayout.BeginVertical();
EditorGUI.indentLevel = indentLevel;
string replacedemblyName = string.Empty;
switch (Path.GetFileNameWithoutExtension(obj.GetType().replacedembly.ManifestModule.Name))
{
case "Unity.Model":
replacedemblyName = "Unity.Model";
break;
case "Unity.Hotfix":
replacedemblyName = "Unity.Hotfix";
break;
case "ILRuntime":
replacedemblyName = "Unity.Hotfix";
break;
}
if (replacedemblyName == "Unity.Model")
{
FieldInfo[] fieldInfos = obj.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
foreach (FieldInfo item in fieldInfos)
{
object value = item.GetValue(obj);
Type type = item.FieldType;
if (item.IsDefined(typeof(HideInInspector), false))
{
continue;
}
if (type.IsDefined(typeof(HideInInspector), false))
{
continue;
}
if (objectObjectTypes.ContainsKey((obj, item)))
{
ObjectObjectType objectObjectType = (ObjectObjectType)objectObjectTypes[(obj, item)];
objectObjectType.Draw(type, item.Name, value, null, indentLevel);
continue;
}
if ((item.IsDefined(typeof(SerializeField), false) || type.IsDefined(typeof(SerializeField), false)) && type.replacedembly.ManifestModule.Name == "Unity.Model.dll")
{
ObjectObjectType objectObjectType = new ObjectObjectType();
if (value == null)
{
object instance = Activator.CreateInstance(type);
objectObjectType.Draw(type, item.Name, instance, null, indentLevel);
item.SetValue(obj, instance);
}
else
{
objectObjectType.Draw(type, item.Name, value, null, indentLevel);
}
objectObjectTypes.Add((obj, item), objectObjectType);
continue;
}
if (listObjectTypes.ContainsKey((obj, item)))
{
ListObjectType listObjectType = (ListObjectType)listObjectTypes[(obj, item)];
listObjectType.Draw(type, item.Name, value, null, indentLevel);
continue;
}
if (type.GetInterface("IList") != null)
{
ListObjectType listObjectType = new ListObjectType();
if (value == null)
{
continue;
}
listObjectType.Draw(type, item.Name, value, null, indentLevel);
listObjectTypes.Add((obj, item), listObjectType);
continue;
}
foreach (IObjectType objectTypeItem in objectList)
{
if (!objectTypeItem.IsType(type))
{
continue;
}
string fieldName = item.Name;
if (fieldName.Contains("clrInstance") || fieldName.Contains("Boxed"))
{
continue;
}
if (fieldName.Length > 17 && fieldName.Contains("k__BackingField"))
{
fieldName = fieldName.Substring(1, fieldName.Length - 17);
}
value = objectTypeItem.Draw(type, fieldName, value, null);
item.SetValue(obj, value);
}
}
}
else
{
#if ILRuntime
FieldInfo[] fieldInfos = ILRuntimeManager.Instance.appdomain.LoadedTypes[obj.ToString()].ReflectionType.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
foreach (FieldInfo item in fieldInfos)
{
object value = item.GetValue(obj);
if (item.FieldType is ILRuntimeWrapperType)
{
//基础类型绘制
Type type = ((ILRuntimeWrapperType)item.FieldType).RealType;
if (item.IsDefined(typeof(HideInInspector), false))
{
continue;
}
if (type.IsDefined(typeof(HideInInspector), false))
{
continue;
}
if (listObjectTypes.ContainsKey((obj, item)))
{
ListObjectType listObjectType = (ListObjectType)listObjectTypes[(obj, item)];
listObjectType.Draw(type, item.Name, value, null, indentLevel);
continue;
}
if (type.GetInterface("IList") != null)
{
ListObjectType listObjectType = new ListObjectType();
if (value == null)
{
continue;
}
listObjectType.Draw(type, item.Name, value, null, indentLevel);
listObjectTypes.Add((obj, item), listObjectType);
continue;
}
foreach (IObjectType objectTypeItem in objectList)
{
if (!objectTypeItem.IsType(type))
{
continue;
}
string fieldName = item.Name;
if (fieldName.Contains("clrInstance") || fieldName.Contains("Boxed"))
{
continue;
}
if (fieldName.Length > 17 && fieldName.Contains("k__BackingField"))
{
fieldName = fieldName.Substring(1, fieldName.Length - 17);
}
value = objectTypeItem.Draw(type, fieldName, value, null);
item.SetValue(obj, value);
}
}
else
{
//自定义类型绘制
Type type = item.FieldType;
if (item.IsDefined(typeof(HideInInspector), false))
{
continue;
}
if (type.IsDefined(typeof(HideInInspector), false))
{
continue;
}
if (objectObjectTypes.ContainsKey((obj, item)))
{
ObjectObjectType objectObjectType = (ObjectObjectType)objectObjectTypes[(obj, item)];
objectObjectType.Draw(type, item.Name, value, null, indentLevel);
continue;
}
if ((item.IsDefined(typeof(SerializeField), false) || type.IsDefined(typeof(SerializeField), false)) && type.replacedembly.ManifestModule.Name == "ILRuntime.dll")
{
ObjectObjectType objectObjectType = new ObjectObjectType();
if (value == null)
{
object instance = ILRuntimeManager.Instance.appdomain.Instantiate(type.ToString());
objectObjectType.Draw(type, item.Name, instance, null, indentLevel);
item.SetValue(obj, instance);
}
else
{
objectObjectType.Draw(type, item.Name, value, null, indentLevel);
}
objectObjectTypes.Add((obj, item), objectObjectType);
continue;
}
}
}
#else
FieldInfo[] fieldInfos = obj.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
foreach (FieldInfo item in fieldInfos)
{
object value = item.GetValue(obj);
Type type = item.FieldType;
if (item.IsDefined(typeof(HideInInspector), false))
{
continue;
}
if (type.IsDefined(typeof(HideInInspector), false))
{
continue;
}
if (objectObjectTypes.ContainsKey((obj, item)))
{
ObjectObjectType objectObjectType = (ObjectObjectType)objectObjectTypes[(obj, item)];
objectObjectType.Draw(type, item.Name, value, null, indentLevel);
continue;
}
if ((item.IsDefined(typeof(SerializeField), false) || type.IsDefined(typeof(SerializeField), false)) && type.replacedembly.ManifestModule.Name == "Unity.Hotfix.dll")
{
ObjectObjectType objectObjectType = new ObjectObjectType();
if (value == null)
{
object instance = Activator.CreateInstance(type);
objectObjectType.Draw(type, item.Name, instance, null, indentLevel);
item.SetValue(obj, instance);
}
else
{
objectObjectType.Draw(type, item.Name, value, null, indentLevel);
}
objectObjectTypes.Add((obj, item), objectObjectType);
continue;
}
if (listObjectTypes.ContainsKey((obj, item)))
{
ListObjectType listObjectType = (ListObjectType)listObjectTypes[(obj, item)];
listObjectType.Draw(type, item.Name, value, null, indentLevel);
continue;
}
if (type.GetInterface("IList") != null)
{
ListObjectType listObjectType = new ListObjectType();
if (value == null)
{
continue;
}
listObjectType.Draw(type, item.Name, value, null, indentLevel);
listObjectTypes.Add((obj, item), listObjectType);
continue;
}
foreach (IObjectType objectTypeItem in objectList)
{
if (!objectTypeItem.IsType(type))
{
continue;
}
string fieldName = item.Name;
if (fieldName.Contains("clrInstance") || fieldName.Contains("Boxed"))
{
continue;
}
if (fieldName.Length > 17 && fieldName.Contains("k__BackingField"))
{
fieldName = fieldName.Substring(1, fieldName.Length - 17);
}
value = objectTypeItem.Draw(type, fieldName, value, null);
item.SetValue(obj, value);
}
}
#endif
EditorGUI.indentLevel = indentLevel;
EditorGUILayout.EndVertical();
}
}
19
View Source File : ViewModelBinding.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public Binding<TProperty> GetPropertyValue<TProperty>(T viewModel, FieldInfo fieldInfo)
{
return (Binding<TProperty>)fieldInfo.GetValue(viewModel);
}
19
View Source File : AttributeMap.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public override bool TryGet(string key, bool publicOnly, out object value)
{
MemberInfo[] members = Helpers.GetInstanceFieldsAndProperties(attribute.GetType(), publicOnly);
foreach (MemberInfo member in members)
{
#if FX11
if (member.Name.ToUpper() == key.ToUpper())
#else
if (string.Equals(member.Name, key, StringComparison.OrdinalIgnoreCase))
#endif
{
PropertyInfo prop = member as PropertyInfo;
if (prop != null) {
//value = prop.GetValue(attribute, null);
value = prop.GetGetMethod(true).Invoke(attribute, null);
return true;
}
FieldInfo field = member as FieldInfo;
if (field != null) {
value = field.GetValue(attribute);
return true;
}
throw new NotSupportedException(member.GetType().Name);
}
}
value = null;
return false;
}
19
View Source File : FieldDecorator.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public override void Write(object value, ProtoWriter dest)
{
Helpers.Debugreplacedert(value != null);
value = field.GetValue(value);
if(value != null) Tail.Write(value, dest);
}
19
View Source File : FieldDecorator.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public override object Read(object value, ProtoReader source)
{
Helpers.Debugreplacedert(value != null);
object newValue = Tail.Read((Tail.RequiresOldValue ? field.GetValue(value) : null), source);
if(newValue != null) field.SetValue(value,newValue);
return null;
}
19
View Source File : CommandManager.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public void AddCommands(CommandData[] commandDatas)
{
if (commandDatas == null) return;
List<CommandData> targetList = new List<CommandData>();
foreach (CommandData item in commandDatas)
{
CommandData target;
switch (item.dataType)
{
default:
target = new CommandData();
break;
}
FieldInfo[] fieldInfos = target.GetType().GetFields();
foreach (FieldInfo fieldinfoitem in fieldInfos)
{
fieldinfoitem.SetValue(target, fieldinfoitem.GetValue(item));
}
targetList.Add(target);
}
commandDataList.AddRange(targetList.ToArray());
}
19
View Source File : JsonMapper.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
private static void WriteValue (object obj, JsonWriter writer,
bool writer_is_private,
int depth)
{
if (depth > max_nesting_depth)
throw new JsonException (
String.Format ("Max allowed object depth reached while " +
"trying to export from type {0}",
obj.GetType ()));
if (obj == null) {
writer.Write (null);
return;
}
Type obj_type;
if (obj is ILRuntime.Runtime.Intepreter.ILTypeInstance)
{
obj_type = ((ILRuntime.Runtime.Intepreter.ILTypeInstance)obj).Type.ReflectionType;
}
else if(obj is ILRuntime.Runtime.Enviorment.CrossBindingAdaptorType)
{
obj_type = ((ILRuntime.Runtime.Enviorment.CrossBindingAdaptorType)obj).ILInstance.Type.ReflectionType;
}
else
obj_type = obj.GetType();
// See if there's a custom exporter for the object
if (custom_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = custom_exporters_table[obj_type];
exporter (obj, writer);
return;
}
// If not, maybe there's a base exporter
if (base_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = base_exporters_table[obj_type];
exporter (obj, writer);
return;
}
if (obj is IJsonWrapper) {
if (writer_is_private)
writer.TextWriter.Write (((IJsonWrapper) obj).ToJson ());
else
((IJsonWrapper) obj).ToJson (writer);
return;
}
if (obj is String) {
writer.Write ((string) obj);
return;
}
if (obj is Double) {
writer.Write ((double) obj);
return;
}
if (obj is Int64) {
writer.Write ((long) obj);
return;
}
if (obj is Int32) {
writer.Write ((int) obj);
return;
}
if (obj is Boolean) {
writer.Write ((bool) obj);
return;
}
if (obj is Array) {
writer.WriteArrayStart ();
foreach (object elem in (Array) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd ();
return;
}
if (obj is IList) {
writer.WriteArrayStart ();
foreach (object elem in (IList) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd ();
return;
}
if (obj is IDictionary) {
writer.WriteObjectStart ();
foreach (DictionaryEntry entry in (IDictionary) obj) {
writer.WritePropertyName (entry.Key.ToString());
WriteValue (entry.Value, writer, writer_is_private,
depth + 1);
}
writer.WriteObjectEnd ();
return;
}
// Last option, let's see if it's an enum
if (obj is Enum) {
Type e_type = Enum.GetUnderlyingType (obj_type);
if (e_type == typeof (long)
|| e_type == typeof (uint)
|| e_type == typeof (ulong))
writer.Write ((ulong) obj);
else
writer.Write ((int) obj);
return;
}
// Okay, so it looks like the input should be exported as an
// object
AddTypeProperties (obj_type);
IList<PropertyMetadata> props = type_properties[obj_type];
writer.WriteObjectStart ();
foreach (PropertyMetadata p_data in props) {
if (p_data.IsField) {
writer.WritePropertyName (p_data.Info.Name);
WriteValue (((FieldInfo) p_data.Info).GetValue (obj),
writer, writer_is_private, depth + 1);
}
else {
PropertyInfo p_info = (PropertyInfo) p_data.Info;
if (p_info.CanRead) {
writer.WritePropertyName (p_data.Info.Name);
WriteValue (p_info.GetValue (obj, null),
writer, writer_is_private, depth + 1);
}
}
}
writer.WriteObjectEnd ();
}
19
View Source File : TupleSerializer.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
private object GetValue(object obj, int index)
{
PropertyInfo prop;
FieldInfo field;
if ((prop = members[index] as PropertyInfo) != null)
{
if (obj == null)
return Helpers.IsValueType(prop.PropertyType) ? Activator.CreateInstance(prop.PropertyType) : null;
//return prop.GetValue(obj, null);
return prop.GetGetMethod(true).Invoke(obj, null);
}
else if ((field = members[index] as FieldInfo) != null)
{
if (obj == null)
return Helpers.IsValueType(field.FieldType) ? Activator.CreateInstance(field.FieldType) : null;
return field.GetValue(obj);
}
else
{
throw new InvalidOperationException();
}
}
19
View Source File : GameObjectExamples.cs
License : MIT License
Project Creator : 5minlab
License : MIT License
Project Creator : 5minlab
[Command("object print", "lists properties of the object")]
public static void PrintGameObject(string[] args) {
if (args.Length < 1) {
Shell.Log("expected : object print <Object Name>");
return;
}
GameObject obj = GameObject.Find(args[0]);
if (obj == null) {
Shell.Log("GameObject not found : " + args[0]);
} else {
Shell.Log("Game Object : " + obj.name);
foreach (Component component in obj.GetComponents(typeof(Component))) {
Shell.Log(" Component : " + component.GetType());
foreach (FieldInfo f in component.GetType().GetFields()) {
Shell.Log(" " + f.Name + " : " + f.GetValue(component));
}
}
}
}
19
View Source File : AssignIconTool.cs
License : MIT License
Project Creator : 5argon
License : MIT License
Project Creator : 5argon
[MenuItem("replacedets/Minefield/Auto-replacedign all script icons")]
public static void replacedignIcons()
{
var beaconClreplacedes = MonoImporter.GetAllRuntimeMonoScripts().Where((x) =>
{
//There are null returning from GetClreplaced as well (why?)
var cls = x.GetClreplaced();
return cls == null ? false : typeof(ILabelBeacon).IsreplacedignableFrom(cls);
});
Texture2D navigationBeaconIcon = replacedetDatabase.LoadreplacedetAtPath<Texture2D>(replacedetDatabase.GUIDToreplacedetPath("3d6634608b55541ddac251be41744121"));
Texture2D testBeaconIcon = replacedetDatabase.LoadreplacedetAtPath<Texture2D>(replacedetDatabase.GUIDToreplacedetPath("d99be7b16603541eebc812d11bb2edf4"));
foreach (var bc in beaconClreplacedes)
{
Debug.Log($"[Minefield] replacedigning a new script icon to {bc.name}");
SetIconForObject.Invoke(null, new object[] { bc,
typeof(IHandlerBeacon).IsreplacedignableFrom(bc.GetClreplaced()) ?
navigationBeaconIcon : testBeaconIcon });
CopyMonoScriptIconToImporters.Invoke(null, new object[] { bc });
}
//Disable the icon in gizmos annotation.
Array annotations = (Array)GetAnnotations.Invoke(null, null);
foreach (var bc in beaconClreplacedes)
{
foreach (var a in annotations)
{
string scriptClreplaced = (string)AnnotationScriptClreplaced.GetValue(a);
if (scriptClreplaced == bc.name)
{
int clreplacedId = (int)AnnotationClreplacedId.GetValue(a);
SetIconEnabled.Invoke(null, new object[] { clreplacedId, scriptClreplaced, 0 });
}
}
}
}
19
View Source File : LyricsComponent.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
public IEnumerator Start()
{
// The goal now is to find the clip this scene will be playing.
// For this, we find the single root gameObject (which is the gameObject
// to which we are attached),
// then we get its GameSongController to find the audio clip,
// and its FlyingTextSpawner to display the lyrics.
if (Settings.VerboseLogging)
{
Debug.Log( "[Beat Singer] Attached to scene.");
Debug.Log($"[Beat Singer] Lyrics are enabled: {Settings.DisplayLyrics}.");
}
textSpawner = FindObjectOfType<FlyingTextSpawner>();
songController = FindObjectOfType<GameSongController>();
var sceneSetup = FindObjectOfType<GameplayCoreSceneSetup>();
if (songController == null || sceneSetup == null)
yield break;
if (textSpawner == null)
{
var installer = FindObjectOfType<EffectPoolsInstaller>();
var container = (Zenject.DiContainer)ContainerField.GetValue(installer);
textSpawner = container.InstantiateComponentOnNewGameObject<FlyingTextSpawner>();
}
var sceneSetupData = (GameplayCoreSceneSetupData)SceneSetupDataField.GetValue(sceneSetup);
if (sceneSetupData == null)
yield break;
audio = (AudioTimeSyncController)AudioTimeSyncField.GetValue(songController);
IBeatmapLevel level = sceneSetupData.difficultyBeatmap.level;
List<Subreplacedle> subreplacedles = new List<Subreplacedle>();
Debug.Log($"[Beat Singer] Corresponding song data found: {level.songName} by {level.songAuthorName} ({(level.songSubName != null ? level.songSubName : "No sub-name")}).");
if (LyricsFetcher.GetLocalLyrics(sceneSetupData.difficultyBeatmap.level.levelID, subreplacedles))
{
Debug.Log( "[Beat Singer] Found local lyrics.");
Debug.Log($"[Beat Singer] These lyrics can be uploaded online using the ID: \"{level.GetLyricsHash()}\".");
// Lyrics found locally, continue with them.
SpawnText("Lyrics found locally", 3f);
}
else
{
Debug.Log("[Beat Singer] Did not find local lyrics, trying online lyrics...");
// When this coroutine ends, it will call the given callback with a list
// of all the subreplacedles we found, and allow us to react.
// If no subs are found, the callback is not called.
yield return StartCoroutine(LyricsFetcher.GetOnlineLyrics(level, subreplacedles));
if (subreplacedles.Count != 0)
goto FoundOnlineLyrics;
yield return StartCoroutine(LyricsFetcher.GetMusixmatchLyrics(level.songName, level.songAuthorName, subreplacedles));
if (subreplacedles.Count != 0)
goto FoundOnlineLyrics;
yield return StartCoroutine(LyricsFetcher.GetMusixmatchLyrics(level.songName, level.songSubName, subreplacedles));
if (subreplacedles.Count != 0)
goto FoundOnlineLyrics;
yield break;
FoundOnlineLyrics:
SpawnText("Lyrics found online", 3f);
}
StartCoroutine(DisplayLyrics(subreplacedles));
}
19
View Source File : Helpers.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
internal static void CopyTo<T>(this T from, T to) where T : clreplaced
{
// Find base type of both compilations
TypeInfo fromType = from.GetType().GetTypeInfo();
TypeInfo toType = to.GetType().GetTypeInfo();
Type baseType;
if (fromType.IsreplacedignableFrom(toType))
{
// ToCompilation inherits FromCompilation
baseType = fromType.AsType();
}
else if (toType.IsreplacedignableFrom(fromType))
{
// FromCompilation inherits ToCompilation
baseType = toType.AsType();
}
else
{
// No common type: find first common type
baseType = FindCommonType(fromType.AsType(), toType.AsType());
}
// Copy fields from one compilation to the other
foreach (FieldInfo field in baseType.GetAllFields())
{
if (field.IsStatic)
continue;
field.SetValue(to, field.GetValue(from));
}
}
19
View Source File : CompilationProcessor.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
public bool TryEditCompilation(CSharpCompilation compilation, CancellationToken cancellationToken, out CSharpCompilation modified, out object outputBuilder)
{
modified = compilation;
if (!IsInitialized && !TryInitialize(compilation, cancellationToken) ||
IsInitialized && !IsInitializationSuccessful)
{
outputBuilder = null;
return false;
}
// Recompute compilation if needed
if (SharedStorage.TryGet(Helpers.RecomputeKey, out Pipeline<Func<CSharpParseOptions, CSharpParseOptions>> pipeline))
{
Func<CSharpParseOptions, CSharpParseOptions> del = pipeline.MakeDelegate(opts => opts);
modified = modified.RecomputeCompilationWithOptions(del, cancellationToken);
}
List<CompilationEditor> editors = Editors;
string step = "NotifyCompilationStart";
// Run the compilation
try
{
// Run the compilation
for (int i = 0; i < editors.Count; i++)
editors[i].TriggerCompilationStart(compilation);
step = "Preprocessing";
foreach (var edit in CompilationPipeline)
modified = edit(modified, cancellationToken) ?? modified;
step = "NotifyCompilationEnd";
// Notify of end of compilation, and start of emission
for (int i = 0; i < editors.Count; i++)
editors[i].TriggerCompilationEnd(compilation);
step = "NotifyEmissionStart";
for (int i = 0; i < editors.Count; i++)
editors[i].TriggerEmissionStart();
step = "Processing";
// Emit the replacedembly, and notify of start of emission
object moduleBuilder = getModuleBuilder(modified);
Type replacedemblySymbolInterf = typeof(IreplacedemblySymbol);
FieldInfo replacedemblyField = moduleBuilder.GetType().GetAllFields()
.First(x => x.FieldType.GetInterfaces().Contains(replacedemblySymbolInterf));
ISourcereplacedemblySymbol replacedemblySymbol = replacedemblyField.GetValue(moduleBuilder) as ISourcereplacedemblySymbol;
ISourcereplacedemblySymbol originalreplacedembly = replacedemblySymbol;
foreach (var edit in replacedemblyPipeline)
replacedemblySymbol = edit(replacedemblySymbol, cancellationToken) ?? replacedemblySymbol;
step = "NotifyEmissionEnd";
// Notify of overall end
for (int i = 0; i < editors.Count; i++)
editors[i].TriggerEmissionEnd();
step = "Continuing";
// Copy modified replacedembly to builder
if (!ReferenceEquals(originalreplacedembly, replacedemblySymbol))
replacedemblyField.SetValue(moduleBuilder, replacedemblySymbol);
outputBuilder = moduleBuilder;
return true;
}
catch (Exception e)
{
do
{
if (e is DiagnosticException de)
{
AddDiagnostic(de.Diagnostic);
}
else if (e is AggregateException ae)
{
foreach (Exception ex in ae.InnerExceptions)
{
ReportDiagnostic(step, ex.Message, ex.Source);
}
}
else
{
ReportDiagnostic(step, e.Message, e.Source);
}
}
while ((e = e.InnerException) != null);
}
outputBuilder = null;
return false;
}
19
View Source File : ExpressionPipeline.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
public static Expression ReplaceBoundVariableFields(Expression expr)
{
MemberExpression mx = expr as MemberExpression;
FieldInfo accessedField = mx?.Member as FieldInfo;
if (accessedField == null || !accessedField.DeclaringType.Name.StartsWith("<>c__"))
return expr;
ConstantExpression displayClreplacedConstant = mx.Expression as ConstantExpression;
if (displayClreplacedConstant == null)
return expr;
return Expression.Constant(
accessedField.GetValue(displayClreplacedConstant.Value),
displayClreplacedConstant.Type);
}
19
View Source File : ExtendableEnums.cs
License : MIT License
Project Creator : 7ark
License : MIT License
Project Creator : 7ark
static T GetBaseProperty<T>(SerializedProperty prop)
{
string[] separatedPaths = prop.propertyPath.Split('.');
System.Object reflectionTarget = prop.serializedObject.targetObject as object;
foreach (var path in separatedPaths)
{
FieldInfo fieldInfo = reflectionTarget.GetType().GetField(path, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
reflectionTarget = fieldInfo.GetValue(reflectionTarget);
}
return (T)reflectionTarget;
}
19
View Source File : FsmUtil.cs
License : GNU General Public License v3.0
Project Creator : a2659802
License : GNU General Public License v3.0
Project Creator : a2659802
public static void ReplaceStringVariable(PlayMakerFSM fsm, string state, Dictionary<string, string> dict)
{
foreach (FsmState t in fsm.FsmStates)
{
bool found = false;
if (t.Name != state && state != "") continue;
foreach (FsmString str in (List<FsmString>) FsmStringParamsField.GetValue(t.ActionData))
{
List<FsmString> val = new List<FsmString>();
if (dict.ContainsKey(str.Value))
{
val.Add(dict[str.Value]);
found = true;
}
else
{
val.Add(str);
}
if (val.Count > 0)
{
FsmStringParamsField.SetValue(t.ActionData, val);
}
}
if (found)
{
t.LoadActions();
}
}
}
19
View Source File : FsmUtil.cs
License : GNU General Public License v3.0
Project Creator : a2659802
License : GNU General Public License v3.0
Project Creator : a2659802
public static void ReplaceStringVariable(PlayMakerFSM fsm, List<string> states, Dictionary<string, string> dict)
{
foreach (FsmState t in fsm.FsmStates)
{
bool found = false;
if (!states.Contains(t.Name)) continue;
foreach (FsmString str in (List<FsmString>) FsmStringParamsField.GetValue(t.ActionData))
{
List<FsmString> val = new List<FsmString>();
if (dict.ContainsKey(str.Value))
{
val.Add(dict[str.Value]);
found = true;
}
else
{
val.Add(str);
}
if (val.Count > 0)
{
FsmStringParamsField.SetValue(t.ActionData, val);
}
}
if (found)
{
t.LoadActions();
}
}
}
19
View Source File : FsmUtil.cs
License : GNU General Public License v3.0
Project Creator : a2659802
License : GNU General Public License v3.0
Project Creator : a2659802
public static void ReplaceStringVariable(PlayMakerFSM fsm, string state, string src, string dst)
{
Log("Replacing FSM Strings");
foreach (FsmState t in fsm.FsmStates)
{
bool found = false;
if (t.Name != state && state != "") continue;
Log($"Found FsmState with name \"{t.Name}\" ");
foreach (FsmString str in (List<FsmString>) FsmStringParamsField.GetValue(t.ActionData))
{
List<FsmString> val = new List<FsmString>();
Log($"Found FsmString with value \"{str}\" ");
if (str.Value.Contains(src))
{
val.Add(dst);
found = true;
Log($"Found FsmString with value \"{str}\", changing to \"{dst}\" ");
}
else
{
val.Add(str);
}
if (val.Count > 0)
{
FsmStringParamsField.SetValue(t.ActionData, val);
}
}
if (found)
{
t.LoadActions();
}
}
}
19
View Source File : UMAUtils.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
public static TElement[] GetBackingArray<TElement>(this List<TElement> list)
{
// Check if the FieldInfo is already in the cache
var listType = typeof(List<TElement>);
FieldInfo fieldInfo;
if (itemsFields.TryGetValue(listType, out fieldInfo) == false)
{
// Generate the FieldInfo and add it to the cache
fieldInfo = listType.GetField(FieldName, GetFieldFlags);
itemsFields.Add(listType, fieldInfo);
}
// Get the backing array of the given List
var items = (TElement[])fieldInfo.GetValue(list);
return items;
}
19
View Source File : GameUtils.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public static XmlWriter GetWriter(this ScribeSaver scribeSaver)
{
FieldInfo fieldInfo = typeof(ScribeSaver).GetField("writer", BindingFlags.Instance | BindingFlags.NonPublic);
XmlWriter result = (XmlWriter)fieldInfo.GetValue(scribeSaver);
return result;
}
19
View Source File : ServerInformation.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public ModelInfo GetInfo(ModelInt packet, ServiceContext context)
{
lock (context.Player)
{
switch (packet.Value)
{
case (long)ServerInfoType.Full:
{
var result = GetModelInfo(context.Player);
return result;
}
case (long)ServerInfoType.SendSave:
{
if (context.PossiblyIntruder)
{
context.Disconnect("Possibly intruder");
return null;
}
var result = new ModelInfo();
//передача файла игры, для загрузки WorldLoad();
// файл передать можно только в том случае если файлы прошли проверку
//!Для Pvp проверка нужна всегда, в PvE нет
if (ServerManager.ServerSettings.IsModsWhitelisted)
{
if ((int)context.Player.ApproveLoadWorldReason > 0)
{
context.Player.ExitReason = DisconnectReason.FilesMods;
Loger.Log($"Login : {context.Player.Public.Login} not all files checked,{context.Player.ApproveLoadWorldReason.ToString() } Disconnect");
result.SaveFileData = null;
return result;
}
}
result.SaveFileData = Repository.GetSaveData.LoadPlayerData(context.Player.Public.Login, 1);
if (result.SaveFileData != null)
{
if (context.Player.MailsConfirmationSave.Count > 0)
{
for (int i = 0; i < context.Player.MailsConfirmationSave.Count; i++)
context.Player.MailsConfirmationSave[i].NeedSaveGame = false;
Loger.Log($"MailsConfirmationSave add {context.Player.MailsConfirmationSave.Count} (mails={context.Player.Mails.Count})");
//Ого! Игрок не сохранился после приема письма, с обязательным сохранением после получения
//Отправляем письма ещё раз
if (context.Player.Mails.Count == 0)
{
context.Player.Mails = context.Player.MailsConfirmationSave.ToList();
}
else
{
var ms = context.Player.MailsConfirmationSave
.Where(mcs => context.Player.Mails.Any(m => m.GetHashBase() != mcs.GetHashBase()))
.ToList();
context.Player.Mails.AddRange(ms);
}
Loger.Log($"MailsConfirmationSave (mails={context.Player.Mails.Count})");
}
}
Loger.Log($"Load World for {context.Player.Public.Login}. (mails={context.Player.Mails.Count}, fMails={context.Player.FunctionMails.Count})");
return result;
}
case (long)ServerInfoType.FullWithDescription:
{
var result = GetModelInfo(context.Player);
//result.Description = "";
var displayAttributes = new List<Tuple<int, string>>();
foreach (var prop in typeof(ServerSettings).GetFields())
{
var attribute = prop.GetCustomAttributes(typeof(DisplayAttribute)).FirstOrDefault();
if (attribute is null || !prop.IsPublic)
{
continue;
}
var dispAtr = (DisplayAttribute)attribute;
var strvalue = string.IsNullOrEmpty(dispAtr.GetDescription()) ? prop.Name : dispAtr.GetDescription();
strvalue = strvalue + "=" + prop.GetValue(ServerManager.ServerSettings).ToString();
var order = dispAtr.GetOrder().HasValue ? dispAtr.GetOrder().Value : 0;
displayAttributes.Add(Tuple.Create(order, strvalue));
}
var sb = new StringBuilder();
var sorte = new List<string>(displayAttributes.OrderBy(x => x.Item1).Select(y => y.Item2)).AsReadOnly();
foreach (var prop in sorte)
{
sb.AppendLine(prop);
}
//result.Description = sb.ToString();
return result;
}
case (long)ServerInfoType.Short:
default:
{
// краткая (зарезервированно, пока не используется) fullInfo = false
var result = new ModelInfo();
return result;
}
}
}
}
19
View Source File : CommonUtils.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
static string Process(object obj, int level, string prefLine, Dictionary<object, int> forParentLink, HashSet<string> excludeTypes)
{
try
{
if (obj == null) return "";
Type type = obj.GetType();
if (excludeTypes.Contains(type.Name)) return "<skip>";
if (type == typeof(DateTime))
{
return ((DateTime)obj).ToString("g");
}
else if (type.IsValueType || type == typeof(string))
{
return obj.ToString();
}
else if (type.IsArray || obj is IEnumerable)
{
string elementType = null;
Array array = null;
if (type.IsArray)
{
var tt = Type.GetType(type.FullName.Replace("[]", string.Empty));
if (tt != null)
{
elementType = tt.ToString();
if (excludeTypes.Contains(tt.Name)) return "<skips>";
}
//else return "<EEEEEEE" + type.FullName;
array = obj as Array;
}
else
{
//как лучше узнать кол-во и тип?
int cnt = 0;
foreach (var o in obj as IEnumerable) cnt++;
array = Array.CreateInstance(typeof(object), cnt);
int i = 0;
foreach (var o in obj as IEnumerable)
{
if (elementType == null && o != null)
{
var tt = o.GetType();
if (excludeTypes.Contains(tt.Name)) return "<skips>";
elementType = tt.ToString();
}
array.SetValue(o, i++);
}
}
if (elementType == null) elementType = "Object";
if (excludeTypes.Contains(elementType)) return "<skips>";
var info = "<" + elementType + "[" + array.Length.ToString() + "]" + ">";
if (level == 0)
{
return info + "[...]";
}
if (array.Length > 0)
{
var ress = new string[array.Length];
var resl = 0;
for (int i = 0; i < array.Length; i++)
{
ress[i] = Process(array.GetValue(i), level - 1, prefLine + PrefLineTab, forParentLink, excludeTypes);
resl += ress[i].Length;
}
if (resl < LineLength)
{
var res = info + "[" + ress[0];
for (int i = 1; i < ress.Length; i++)
{
res += ", " + ress[i];
}
return res + "]";
}
else
{
var res = info + "["
+ Environment.NewLine + prefLine + ress[0];
for (int i = 1; i < ress.Length; i++)
{
res += ", "
+ Environment.NewLine + prefLine + ress[i];
}
return res + Environment.NewLine + prefLine + "]";
}
}
return info + "[]";
}
else if (obj is Type) return "<Type>" + obj.ToString();
else if (type.IsClreplaced)
{
var info = "<" + type.Name + ">";
if (forParentLink.ContainsKey(obj))
{
if (forParentLink[obj] >= level)
return info + "{duplicate}";
else
forParentLink[obj] = level;
}
else
forParentLink.Add(obj, level);
if (level == 0)
{
return info + "{...}";
}
FieldInfo[] fields = type.GetFields(BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.Instance);
if (fields.Length > 0)
{
var ress = new string[fields.Length];
var resl = 0;
for (int i = 0; i < fields.Length; i++)
{
object fieldValue = fields[i].GetValue(obj);
ress[i] = fieldValue == null
? fields[i].Name + ": null"
: fields[i].Name + ": " + Process(fieldValue, level - 1, prefLine + PrefLineTab, forParentLink, excludeTypes);
resl += ress[i].Length;
}
if (resl < LineLength)
{
var res = info + "{" + ress[0];
for (int i = 1; i < ress.Length; i++)
{
res += ", " + ress[i];
}
return res + "}";
}
else
{
var res = info + "{"
+ Environment.NewLine + prefLine + ress[0];
for (int i = 1; i < ress.Length; i++)
{
res += ", "
+ Environment.NewLine + prefLine + ress[i];
}
return res + Environment.NewLine + prefLine + "}";
}
}
return info + "{}";
}
else
throw new ArgumentException("Unknown type");
}
catch
{
return "<exception>";
}
}
19
View Source File : InspectorFieldsUtility.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
public static List<InspectorFieldData> GetInspectorFields(System.Object target)
{
List<InspectorFieldData> fields = new List<InspectorFieldData>();
Type myType = target.GetType();
foreach (PropertyInfo prop in myType.GetProperties())
{
var attrs = (InspectorField[])prop.GetCustomAttributes(typeof(InspectorField), false);
foreach (var attr in attrs)
{
fields.Add(new InspectorFieldData() { Name = prop.Name, Attributes = attr, Value = prop.GetValue(target, null) });
}
}
foreach (FieldInfo field in myType.GetFields())
{
var attrs = (InspectorField[])field.GetCustomAttributes(typeof(InspectorField), false);
foreach (var attr in attrs)
{
fields.Add(new InspectorFieldData() { Name = field.Name, Attributes = attr, Value = field.GetValue(target) });
}
}
return fields;
}
19
View Source File : MixedRealityInspectorUtility.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
public static Rect GetEditorMainWindowPos()
{
var containerWinType = AppDomain.CurrentDomain.GetAllDerivedTypes(typeof(ScriptableObject)).FirstOrDefault(t => t.Name == "ContainerWindow");
if (containerWinType == null)
{
throw new MissingMemberException("Can't find internal type ContainerWindow. Maybe something has changed inside Unity");
}
var showModeField = containerWinType.GetField("m_ShowMode", BindingFlags.NonPublic | BindingFlags.Instance);
var positionProperty = containerWinType.GetProperty("position", BindingFlags.Public | BindingFlags.Instance);
if (showModeField == null || positionProperty == null)
{
throw new MissingFieldException("Can't find internal fields 'm_ShowMode' or 'position'. Maybe something has changed inside Unity");
}
var windows = Resources.FindObjectsOfTypeAll(containerWinType);
foreach (var win in windows)
{
var showMode = (int)showModeField.GetValue(win);
if (showMode == 4) // main window
{
var pos = (Rect)positionProperty.GetValue(win, null);
return pos;
}
}
throw new NotSupportedException("Can't find internal main window. Maybe something has changed inside Unity");
}
19
View Source File : AwaiterExtensions.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
private static List<Type> GenerateObjectTrace(IEnumerable<IEnumerator> enumerators)
{
var objTrace = new List<Type>();
foreach (var enumerator in enumerators)
{
// NOTE: This only works with scripting engine 4.6
// And could easily stop working with unity updates
var field = enumerator.GetType().GetField("$this", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
if (field == null)
{
continue;
}
var obj = field.GetValue(enumerator);
if (obj == null)
{
continue;
}
var objType = obj.GetType();
if (!objTrace.Any() || objType != objTrace.Last())
{
objTrace.Add(objType);
}
}
objTrace.Reverse();
return objTrace;
}
19
View Source File : InspectorGenericFields.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
public static List<InspectorPropertySetting> GetSettings(T source)
{
Type myType = source.GetType();
List<InspectorPropertySetting> settings = new List<InspectorPropertySetting>();
List<PropertyInfo> propInfoList = new List<PropertyInfo>(myType.GetProperties());
for (int i = 0; i < propInfoList.Count; i++)
{
PropertyInfo propInfo = propInfoList[i];
var attrs = (InspectorField[])propInfo.GetCustomAttributes(typeof(InspectorField), false);
foreach (var attr in attrs)
{
settings.Add(InspectorField.FieldToProperty(attr, propInfo.GetValue(source, null), propInfo.Name));
}
}
List<FieldInfo> fieldInfoList = new List<FieldInfo>(myType.GetFields());
for (int i = 0; i < fieldInfoList.Count; i++)
{
FieldInfo fieldInfo = fieldInfoList[i];
var attrs = (InspectorField[])fieldInfo.GetCustomAttributes(typeof(InspectorField), false);
foreach (var attr in attrs)
{
settings.Add(InspectorField.FieldToProperty(attr, fieldInfo.GetValue(source), fieldInfo.Name));
}
}
return settings;
}
19
View Source File : OVRSystemProfilerPanel.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
float? GetMaxPerfValueFloat(string propertyName)
{
FieldInfo baseFieldInfo, validalityFieldInfo;
GetMetricsField(propertyName, out baseFieldInfo, out validalityFieldInfo);
if (baseFieldInfo == null || baseFieldInfo.FieldType != typeof(float) ||
(validalityFieldInfo != null && validalityFieldInfo.FieldType != typeof(bool)))
{
Debug.LogWarning("[OVRSystemProfilerPanel] GetMaxPerfValueFloat(): Type mismatch");
return null;
}
OVRSystemPerfMetrics.PerfMetrics lastMetrics = null;
int metricsIndex;
for (metricsIndex = receivedMetricsList.Count - 1; metricsIndex >= 0; --metricsIndex)
{
var metrics = receivedMetricsList[metricsIndex];
if (validalityFieldInfo != null && !(bool)validalityFieldInfo.GetValue(metrics))
{
continue;
}
lastMetrics = metrics;
break;
}
if (lastMetrics == null)
{
return null;
}
float? result = null;
for (; metricsIndex >= 0; --metricsIndex)
{
var metrics = receivedMetricsList[metricsIndex];
if (metrics.frameTime < lastMetrics.frameTime - metricsHistoryDuration)
{
break;
}
if (validalityFieldInfo != null && !(bool)validalityFieldInfo.GetValue(metrics))
{
continue;
}
else
{
float value = (float)baseFieldInfo.GetValue(metrics);
if (!result.HasValue || result.Value < value)
{
result = value;
}
}
}
return result;
}
19
View Source File : OVRSystemProfilerPanel.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
bool HasValidPerfMetrics(string propertyName)
{
FieldInfo baseFieldInfo, validalityFieldInfo;
GetMetricsField(propertyName, out baseFieldInfo, out validalityFieldInfo);
if (baseFieldInfo == null || (validalityFieldInfo != null && validalityFieldInfo.FieldType != typeof(bool)))
{
Debug.LogWarning("[OVRSystemProfilerPanel] Unable to find property " + propertyName);
return false;
}
if (validalityFieldInfo == null)
{
return true;
}
for (int i = receivedMetricsList.Count - 1; i >= 0; --i)
{
var metrics = receivedMetricsList[i];
if (validalityFieldInfo != null && (bool)validalityFieldInfo.GetValue(metrics))
{
return true;
}
}
return false;
}
19
View Source File : OVRSystemProfilerPanel.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
int? GetLatestPerfValueInt(string propertyName)
{
FieldInfo baseFieldInfo, validalityFieldInfo;
GetMetricsField(propertyName, out baseFieldInfo, out validalityFieldInfo);
if (baseFieldInfo == null || baseFieldInfo.FieldType != typeof(int) ||
(validalityFieldInfo != null && validalityFieldInfo.FieldType != typeof(bool)))
{
Debug.LogWarning("[OVRSystemProfilerPanel] GetLatestPerfValueInt(): Type mismatch");
return null;
}
if (receivedMetricsList.Count == 0)
{
return null;
}
for (int i = receivedMetricsList.Count - 1; i >= 0; --i)
{
var metrics = receivedMetricsList[i];
if (validalityFieldInfo == null || (validalityFieldInfo != null && (bool)validalityFieldInfo.GetValue(metrics)))
{
return (int)baseFieldInfo.GetValue(metrics);
}
}
return null;
}
19
View Source File : OVRSystemProfilerPanel.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
float? GetLatestPerfValueFloat(string propertyName)
{
FieldInfo baseFieldInfo, validalityFieldInfo;
GetMetricsField(propertyName, out baseFieldInfo, out validalityFieldInfo);
if (baseFieldInfo == null || baseFieldInfo.FieldType != typeof(float) ||
(validalityFieldInfo != null && validalityFieldInfo.FieldType != typeof(bool)))
{
Debug.LogWarning("[OVRSystemProfilerPanel] GetLatestPerfValueFloat(): Type mismatch");
return null;
}
if (receivedMetricsList.Count == 0)
{
return null;
}
for (int i = receivedMetricsList.Count - 1; i >= 0; --i)
{
var metrics = receivedMetricsList[i];
if (validalityFieldInfo == null || (validalityFieldInfo != null && (bool)validalityFieldInfo.GetValue(metrics)))
{
return (float)baseFieldInfo.GetValue(metrics);
}
}
return null;
}
19
View Source File : OVRSystemProfilerPanel.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
float? GetAveragePerfValueFloat(string propertyName)
{
FieldInfo baseFieldInfo, validalityFieldInfo;
GetMetricsField(propertyName, out baseFieldInfo, out validalityFieldInfo);
if (baseFieldInfo == null || baseFieldInfo.FieldType != typeof(float) ||
(validalityFieldInfo != null && validalityFieldInfo.FieldType != typeof(bool)))
{
Debug.LogWarning("[OVRSystemProfilerPanel] GetAveragePerfValueFloat(): Type mismatch");
return null;
}
int count = 0;
float sum = 0;
OVRSystemPerfMetrics.PerfMetrics lastMetrics = null;
int metricsIndex;
for (metricsIndex = receivedMetricsList.Count - 1; metricsIndex >= 0; --metricsIndex)
{
var metrics = receivedMetricsList[metricsIndex];
if (validalityFieldInfo != null && !(bool)validalityFieldInfo.GetValue(metrics))
{
continue;
}
lastMetrics = metrics;
break;
}
if (lastMetrics == null)
{
return null;
}
for (; metricsIndex >=0; -- metricsIndex)
{
var metrics = receivedMetricsList[metricsIndex];
if (metrics.frameTime < lastMetrics.frameTime - metricsHistoryDuration)
{
break;
}
if (validalityFieldInfo != null && !(bool)validalityFieldInfo.GetValue(metrics))
{
continue;
}
sum += (float)baseFieldInfo.GetValue(metrics);
count++;
}
if (count == 0)
{
return null;
}
else
{
return sum / count;
}
}
19
View Source File : QueryableExtensions.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public static string ToSql<TEnreplacedy>(this IQueryable<TEnreplacedy> query)
{
var enumerator = query.Provider.Execute<IEnumerable<TEnreplacedy>>(query.Expression).GetEnumerator();
var enumeratorType = enumerator.GetType();
var selectFieldInfo = enumeratorType.GetField("_selectExpression", BindingFlags.NonPublic | BindingFlags.Instance) ?? throw new InvalidOperationException($"cannot find field _selectExpression on type {enumeratorType.Name}");
var sqlGeneratorFieldInfo = enumeratorType.GetField("_querySqlGeneratorFactory", BindingFlags.NonPublic | BindingFlags.Instance) ?? throw new InvalidOperationException($"cannot find field _querySqlGeneratorFactory on type {enumeratorType.Name}");
var selectExpression = selectFieldInfo.GetValue(enumerator) as SelectExpression ?? throw new InvalidOperationException($"could not get SelectExpression");
var factory = sqlGeneratorFieldInfo.GetValue(enumerator) as IQuerySqlGeneratorFactory ?? throw new InvalidOperationException($"could not get IQuerySqlGeneratorFactory");
var sqlGenerator = factory.Create();
var command = sqlGenerator.GetCommand(selectExpression);
var sql = command.CommandText;
return sql;
}
See More Examples