Here are the examples of the csharp api System.Reflection.MemberInfo.IsDefined(System.Type, bool) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
581 Examples
19
View Source File : EnumObjectType.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public object Draw(Type memberType, string memberName, object value, object target)
{
if (memberType.IsDefined(typeof(FlagsAttribute), false))
{
return EditorGUILayout.EnumFlagsField(memberName, (Enum)value);
}
else
{
return EditorGUILayout.EnumPopup(memberName, (Enum)value);
}
}
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 : SurrogateSerializer.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
private static bool HasCast(TypeModel model, Type type, Type from, Type to, out MethodInfo op)
{
#if WINRT || PROFILE259
System.Collections.Generic.List<MethodInfo> list = new System.Collections.Generic.List<MethodInfo>();
foreach (var item in type.GetRuntimeMethods())
{
if (item.IsStatic) list.Add(item);
}
MethodInfo[] found = list.ToArray();
#else
const BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
MethodInfo[] found = type.GetMethods(flags);
#endif
ParameterInfo[] paramTypes;
Type convertAttributeType = null;
for (int i = 0; i < found.Length; i++)
{
MethodInfo m = found[i];
if (m.ReturnType != to) continue;
paramTypes = m.GetParameters();
if(paramTypes.Length == 1 && paramTypes[0].ParameterType == from)
{
if (convertAttributeType == null)
{
convertAttributeType = model.MapType(typeof(ProtoConverterAttribute), false);
if (convertAttributeType == null)
{ // attribute isn't defined in the source replacedembly: stop looking
break;
}
}
if (m.IsDefined(convertAttributeType, true))
{
op = m;
return true;
}
}
}
for(int i = 0 ; i < found.Length ; i++)
{
MethodInfo m = found[i];
if ((m.Name != "op_Implicit" && m.Name != "op_Explicit") || m.ReturnType != to)
{
continue;
}
paramTypes = m.GetParameters();
if(paramTypes.Length == 1 && paramTypes[0].ParameterType == from)
{
op = m;
return true;
}
}
op = null;
return false;
}
19
View Source File : PostProcessingInspector.cs
License : MIT License
Project Creator : AdultLink
License : MIT License
Project Creator : AdultLink
void OnEnable()
{
if (target == null)
return;
// Aggregate custom post-fx editors
var replacedembly = replacedembly.Getreplacedembly(typeof(PostProcessingInspector));
var editorTypes = replacedembly.GetTypes()
.Where(x => x.IsDefined(typeof(PostProcessingModelEditorAttribute), false));
var customEditors = new Dictionary<Type, PostProcessingModelEditor>();
foreach (var editor in editorTypes)
{
var attr = (PostProcessingModelEditorAttribute)editor.GetCustomAttributes(typeof(PostProcessingModelEditorAttribute), false)[0];
var effectType = attr.type;
var alwaysEnabled = attr.alwaysEnabled;
var editorInst = (PostProcessingModelEditor)Activator.CreateInstance(editor);
editorInst.alwaysEnabled = alwaysEnabled;
editorInst.profile = target as PostProcessingProfile;
editorInst.inspector = this;
customEditors.Add(effectType, editorInst);
}
// ... and corresponding models
var baseType = target.GetType();
var property = serializedObject.Gereplacederator();
while (property.Next(true))
{
if (!property.hasChildren)
continue;
var type = baseType;
var srcObject = ReflectionUtils.GetFieldValueFromPath(serializedObject.targetObject, ref type, property.propertyPath);
if (srcObject == null)
continue;
PostProcessingModelEditor editor;
if (customEditors.TryGetValue(type, out editor))
{
var effect = (PostProcessingModel)srcObject;
if (editor.alwaysEnabled)
effect.enabled = editor.alwaysEnabled;
m_CustomEditors.Add(editor, effect);
editor.target = effect;
editor.serializedProperty = property.Copy();
editor.OnPreEnable();
}
}
// Prepare monitors
m_Monitors = new List<PostProcessingMonitor>();
var monitors = new List<PostProcessingMonitor>
{
new HistogramMonitor(),
new WaveformMonitor(),
new ParadeMonitor(),
new VectorscopeMonitor()
};
var monitorNames = new List<GUIContent>();
foreach (var monitor in monitors)
{
if (monitor.IsSupported())
{
monitor.Init(m_ConcreteTarget.monitors, this);
m_Monitors.Add(monitor);
monitorNames.Add(monitor.GetMonitorreplacedle());
}
}
m_MonitorNames = monitorNames.ToArray();
if (m_Monitors.Count > 0)
m_ConcreteTarget.monitors.onFrameEndEditorOnly = OnFrameEnd;
}
19
View Source File : SteamVR_Camera.cs
License : MIT License
Project Creator : ajayyy
License : MIT License
Project Creator : ajayyy
public void ForceLast()
{
if (values != null)
{
// Restore values on new instance
foreach (DictionaryEntry entry in values)
{
var f = entry.Key as FieldInfo;
f.SetValue(this, entry.Value);
}
values = null;
}
else
{
// Make sure it's the last component
var components = GetComponents<Component>();
// But first make sure there aren't any other SteamVR_Cameras on this object.
for (int i = 0; i < components.Length; i++)
{
var c = components[i] as SteamVR_Camera;
if (c != null && c != this)
{
DestroyImmediate(c);
}
}
components = GetComponents<Component>();
if (this != components[components.Length - 1])
{
// Store off values to be restored on new instance
values = new Hashtable();
var fields = GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
foreach (var f in fields)
if (f.IsPublic || f.IsDefined(typeof(SerializeField), true))
values[f] = f.GetValue(this);
var go = gameObject;
DestroyImmediate(this);
go.AddComponent<SteamVR_Camera>().ForceLast();
}
}
}
19
View Source File : DefaultContractResolver.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
private MemberInfo GetExtensionDataMemberForType(Type type)
{
IEnumerable<MemberInfo> members = GetClreplacedHierarchyForType(type).SelectMany(baseType =>
{
IList<MemberInfo> m = new List<MemberInfo>();
m.AddRange(baseType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));
m.AddRange(baseType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));
return m;
});
MemberInfo extensionDataMember = members.LastOrDefault(m =>
{
MemberTypes memberType = m.MemberType();
if (memberType != MemberTypes.Property && memberType != MemberTypes.Field)
{
return false;
}
// last instance of attribute wins on type if there are multiple
if (!m.IsDefined(typeof(JsonExtensionDataAttribute), false))
{
return false;
}
if (!ReflectionUtils.CanReadMemberValue(m, true))
{
throw new JsonException("Invalid extension data attribute on '{0}'. Member '{1}' must have a getter.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(m.DeclaringType), m.Name));
}
Type t = ReflectionUtils.GetMemberUnderlyingType(m);
Type dictionaryType;
if (ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out dictionaryType))
{
Type keyType = dictionaryType.GetGenericArguments()[0];
Type valueType = dictionaryType.GetGenericArguments()[1];
if (keyType.IsreplacedignableFrom(typeof(string)) && valueType.IsreplacedignableFrom(typeof(JToken)))
{
return true;
}
}
throw new JsonException("Invalid extension data attribute on '{0}'. Member '{1}' type must implement IDictionary<string, JToken>.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(m.DeclaringType), m.Name));
});
return extensionDataMember;
}
19
View Source File : DefaultContractResolver.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
private ConstructorInfo GetAttributeConstructor(Type objectType)
{
IList<ConstructorInfo> markedConstructors = objectType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(c => c.IsDefined(typeof(JsonConstructorAttribute), true)).ToList();
if (markedConstructors.Count > 1)
{
throw new JsonException("Multiple constructors with the JsonConstructorAttribute.");
}
else if (markedConstructors.Count == 1)
{
return markedConstructors[0];
}
// little hack to get Version objects to deserialize correctly
if (objectType == typeof(Version))
{
return objectType.GetConstructor(new[] { typeof(int), typeof(int), typeof(int), typeof(int) });
}
return null;
}
19
View Source File : DefaultContractResolver.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameters, Type attributeType, MethodInfo currentCallback, ref Type prevAttributeType)
{
if (!method.IsDefined(attributeType, false))
{
return false;
}
if (currentCallback != null)
{
throw new JsonException("Invalid attribute. Both '{0}' and '{1}' in type '{2}' have '{3}'.".FormatWith(CultureInfo.InvariantCulture, method, currentCallback, GetClrTypeFullName(method.DeclaringType), attributeType));
}
if (prevAttributeType != null)
{
throw new JsonException("Invalid Callback. Method '{3}' in type '{2}' has both '{0}' and '{1}'.".FormatWith(CultureInfo.InvariantCulture, prevAttributeType, attributeType, GetClrTypeFullName(method.DeclaringType), method));
}
if (method.IsVirtual)
{
throw new JsonException("Virtual Method '{0}' of type '{1}' cannot be marked with '{2}' attribute.".FormatWith(CultureInfo.InvariantCulture, method, GetClrTypeFullName(method.DeclaringType), attributeType));
}
if (method.ReturnType != typeof(void))
{
throw new JsonException("Serialization Callback '{1}' in type '{0}' must return void.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method));
}
if (attributeType == typeof(OnErrorAttribute))
{
if (parameters == null || parameters.Length != 2 || parameters[0].ParameterType != typeof(StreamingContext) || parameters[1].ParameterType != typeof(ErrorContext))
{
throw new JsonException("Serialization Error Callback '{1}' in type '{0}' must have two parameters of type '{2}' and '{3}'.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method, typeof(StreamingContext), typeof(ErrorContext)));
}
}
else
{
if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != typeof(StreamingContext))
{
throw new JsonException("Serialization Callback '{1}' in type '{0}' must have a single parameter of type '{2}'.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method, typeof(StreamingContext)));
}
}
prevAttributeType = attributeType;
return true;
}
19
View Source File : EnumUtils.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
public static IList<T> GetFlagsValues<T>(T value) where T : struct
{
Type enumType = typeof(T);
if (!enumType.IsDefined(typeof(FlagsAttribute), false))
{
throw new ArgumentException("Enum type {0} is not a set of flags.".FormatWith(CultureInfo.InvariantCulture, enumType));
}
Type underlyingType = Enum.GetUnderlyingType(value.GetType());
ulong num = Convert.ToUInt64(value, CultureInfo.InvariantCulture);
IList<EnumValue<ulong>> enumNameValues = GetNamesAndValues<T>();
IList<T> selectedFlagsValues = new List<T>();
foreach (EnumValue<ulong> enumNameValue in enumNameValues)
{
if ((num & enumNameValue.Value) == enumNameValue.Value && enumNameValue.Value != 0)
{
selectedFlagsValues.Add((T)Convert.ChangeType(enumNameValue.Value, underlyingType, CultureInfo.CurrentCulture));
}
}
if (selectedFlagsValues.Count == 0 && enumNameValues.SingleOrDefault(v => v.Value == 0) != null)
{
selectedFlagsValues.Add(default(T));
}
return selectedFlagsValues;
}
19
View Source File : JsonSchemaGenerator.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required)
{
ValidationUtils.ArgumentNotNull(type, nameof(type));
string resolvedId = GetTypeId(type, false);
string explicitId = GetTypeId(type, true);
if (!string.IsNullOrEmpty(resolvedId))
{
JsonSchema resolvedSchema = _resolver.GetSchema(resolvedId);
if (resolvedSchema != null)
{
// resolved schema is not null but referencing member allows nulls
// change resolved schema to allow nulls. hacky but what are ya gonna do?
if (valueRequired != Required.Always && !HasFlag(resolvedSchema.Type, JsonSchemaType.Null))
{
resolvedSchema.Type |= JsonSchemaType.Null;
}
if (required && resolvedSchema.Required != true)
{
resolvedSchema.Required = true;
}
return resolvedSchema;
}
}
// test for unresolved circular reference
if (_stack.Any(tc => tc.Type == type))
{
throw new JsonException("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type));
}
JsonContract contract = ContractResolver.ResolveContract(type);
JsonConverter converter;
if ((converter = contract.Converter) != null || (converter = contract.InternalConverter) != null)
{
JsonSchema converterSchema = converter.GetSchema();
if (converterSchema != null)
{
return converterSchema;
}
}
Push(new TypeSchema(type, new JsonSchema()));
if (explicitId != null)
{
CurrentSchema.Id = explicitId;
}
if (required)
{
CurrentSchema.Required = true;
}
CurrentSchema.replacedle = Getreplacedle(type);
CurrentSchema.Description = GetDescription(type);
if (converter != null)
{
// todo: Add GetSchema to JsonConverter and use here?
CurrentSchema.Type = JsonSchemaType.Any;
}
else
{
switch (contract.ContractType)
{
case JsonContractType.Object:
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
CurrentSchema.Id = GetTypeId(type, false);
GenerateObjectSchema(type, (JsonObjectContract)contract);
break;
case JsonContractType.Array:
CurrentSchema.Type = AddNullType(JsonSchemaType.Array, valueRequired);
CurrentSchema.Id = GetTypeId(type, false);
JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetCachedAttribute<JsonArrayAttribute>(type);
bool allowNullItem = (arrayAttribute == null || arrayAttribute.AllowNullItems);
Type collectionItemType = ReflectionUtils.GetCollectionItemType(type);
if (collectionItemType != null)
{
CurrentSchema.Items = new List<JsonSchema>();
CurrentSchema.Items.Add(GenerateInternal(collectionItemType, (!allowNullItem) ? Required.Always : Required.Default, false));
}
break;
case JsonContractType.Primitive:
CurrentSchema.Type = GetJsonSchemaType(type, valueRequired);
if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum() && !type.IsDefined(typeof(FlagsAttribute), true))
{
CurrentSchema.Enum = new List<JToken>();
IList<EnumValue<long>> enumValues = EnumUtils.GetNamesAndValues<long>(type);
foreach (EnumValue<long> enumValue in enumValues)
{
JToken value = JToken.FromObject(enumValue.Value);
CurrentSchema.Enum.Add(value);
}
}
break;
case JsonContractType.String:
JsonSchemaType schemaType = (!ReflectionUtils.IsNullable(contract.UnderlyingType))
? JsonSchemaType.String
: AddNullType(JsonSchemaType.String, valueRequired);
CurrentSchema.Type = schemaType;
break;
case JsonContractType.Dictionary:
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
Type keyType;
Type valueType;
ReflectionUtils.GetDictionaryKeyValueTypes(type, out keyType, out valueType);
if (keyType != null)
{
JsonContract keyContract = ContractResolver.ResolveContract(keyType);
// can be converted to a string
if (keyContract.ContractType == JsonContractType.Primitive)
{
CurrentSchema.AdditionalProperties = GenerateInternal(valueType, Required.Default, false);
}
}
break;
#if !(DOTNET || PORTABLE || PORTABLE40)
case JsonContractType.Serializable:
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
CurrentSchema.Id = GetTypeId(type, false);
GenerateISerializableContract(type, (JsonISerializableContract)contract);
break;
#endif
#if !(NET35 || NET20 || PORTABLE40)
case JsonContractType.Dynamic:
#endif
case JsonContractType.Linq:
CurrentSchema.Type = JsonSchemaType.Any;
break;
default:
throw new JsonException("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract));
}
}
return Pop().Schema;
}
19
View Source File : DefaultContractResolver.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
protected virtual List<MemberInfo> GetSerializableMembers(Type objectType)
{
bool ignoreSerializableAttribute;
#if !(DOTNET || PORTABLE || PORTABLE40)
ignoreSerializableAttribute = IgnoreSerializableAttribute;
#else
ignoreSerializableAttribute = true;
#endif
MemberSerialization memberSerialization = JsonTypeReflector.GetObjectMemberSerialization(objectType, ignoreSerializableAttribute);
List<MemberInfo> allMembers = ReflectionUtils.GetFieldsAndProperties(objectType, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)
.Where(m => !ReflectionUtils.IsIndexedProperty(m)).ToList();
List<MemberInfo> serializableMembers = new List<MemberInfo>();
if (memberSerialization != MemberSerialization.Fields)
{
#if !NET20
DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(objectType);
#endif
#pragma warning disable 618
List<MemberInfo> defaultMembers = ReflectionUtils.GetFieldsAndProperties(objectType, DefaultMembersSearchFlags)
.Where(m => !ReflectionUtils.IsIndexedProperty(m)).ToList();
#pragma warning restore 618
foreach (MemberInfo member in allMembers)
{
// exclude members that are compiler generated if set
if (SerializeCompilerGeneratedMembers || !member.IsDefined(typeof(CompilerGeneratedAttribute), true))
{
if (defaultMembers.Contains(member))
{
// add all members that are found by default member search
serializableMembers.Add(member);
}
else
{
// add members that are explicitly marked with JsonProperty/DataMember attribute
// or are a field if serializing just fields
if (JsonTypeReflector.GetAttribute<JsonPropertyAttribute>(member) != null)
{
serializableMembers.Add(member);
}
else if (JsonTypeReflector.GetAttribute<JsonRequiredAttribute>(member) != null)
{
serializableMembers.Add(member);
}
#if !NET20
else if (dataContractAttribute != null && JsonTypeReflector.GetAttribute<DataMemberAttribute>(member) != null)
{
serializableMembers.Add(member);
}
#endif
else if (memberSerialization == MemberSerialization.Fields && member.MemberType() == MemberTypes.Field)
{
serializableMembers.Add(member);
}
}
}
}
#if !NET20
Type match;
// don't include EnreplacedyKey on enreplacedies objects... this is a bit hacky
if (objectType.replacedignableToTypeName("System.Data.Objects.DataClreplacedes.EnreplacedyObject", out match))
{
serializableMembers = serializableMembers.Where(ShouldSerializeEnreplacedyMember).ToList();
}
#endif
}
else
{
// serialize all fields
foreach (MemberInfo member in allMembers)
{
FieldInfo field = member as FieldInfo;
if (field != null && !field.IsStatic)
{
serializableMembers.Add(member);
}
}
}
return serializableMembers;
}
19
View Source File : RuntimeUtilities.cs
License : MIT License
Project Creator : alelievr
License : MIT License
Project Creator : alelievr
public static T GetAttribute<T>(this Type type) where T : Attribute
{
replacedert.IsTrue(type.IsDefined(typeof(T), false), "Attribute not found");
return (T)type.GetCustomAttributes(typeof(T), false)[0];
}
19
View Source File : Reflection.cs
License : MIT License
Project Creator : AlenToma
License : MIT License
Project Creator : AlenToma
internal static FieldInfo GetGetterBackingField(PropertyInfo autoProperty)
{
var getMethod = autoProperty.GetGetMethod();
// Restrict operation to auto properties to avoid risking errors if a getter does not contain exactly one field read instruction (such as with calculated properties).
if (!getMethod.IsDefined(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), false)) return null;
var byteCode = getMethod.GetMethodBody()?.GetILAsByteArray() ?? new byte[0];
//var byteCode = getMethod.GetMethodBody().GetILAsByteArray();
int pos = 0;
// Find the first LdFld instruction and parse its operand to a FieldInfo object.
while (pos < byteCode.Length)
{
// Read and parse the OpCode (it can be 1 or 2 bytes in size).
byte code = byteCode[pos++];
if (!(TryGetOpCode(code, out var opCode) || pos < byteCode.Length && TryGetOpCode((short)(code * 0x100 + byteCode[pos++]), out opCode)))
throw new NotSupportedException("Unknown IL code detected.");
// If it is a LdFld, read its operand, parse it to a FieldInfo and return it.
if (opCode == OpCodes.Ldfld && opCode.OperandType == OperandType.InlineField && pos + sizeof(int) <= byteCode.Length)
{
return getMethod.Module.ResolveMember(BitConverter.ToInt32(byteCode, pos), getMethod.DeclaringType?.GetGenericArguments(), null) as FieldInfo;
}
// Otherwise, set the current position to the start of the next instruction, if any (we need to know how much bytes are used by operands).
pos += opCode.OperandType == OperandType.InlineNone
? 0
: opCode.OperandType == OperandType.ShortInlineBrTarget ||
opCode.OperandType == OperandType.ShortInlineI ||
opCode.OperandType == OperandType.ShortInlineVar
? 1
: opCode.OperandType == OperandType.InlineVar
? 2
: opCode.OperandType == OperandType.InlineI8 ||
opCode.OperandType == OperandType.InlineR
? 8
: opCode.OperandType == OperandType.InlineSwitch
? 4 * (BitConverter.ToInt32(byteCode, pos) + 1)
: 4;
}
return null;
}
19
View Source File : Reflection.cs
License : MIT License
Project Creator : AlenToma
License : MIT License
Project Creator : AlenToma
internal static bool IsAnonymousType(Type type)
{
// may break in the future if compiler defined names change...
const string CS_ANONYMOUS_PREFIX = "<>f__AnonymousType";
const string VB_ANONYMOUS_PREFIX = "VB$AnonymousType";
const string Auto_ANONYMOUS_PREFIX = "AnonymousType";
if (type == null)
throw new ArgumentNullException("type");
if (type.Namespace == null && (type.Name.StartsWith(CS_ANONYMOUS_PREFIX, StringComparison.Ordinal)
|| type.Name.StartsWith(VB_ANONYMOUS_PREFIX, StringComparison.Ordinal) ||
type.Name.StartsWith(Auto_ANONYMOUS_PREFIX, StringComparison.Ordinal)))
{
return type.IsDefined(typeof(CompilerGeneratedAttribute), false);
}
return false;
}
19
View Source File : InspectorEditor.cs
License : Apache License 2.0
Project Creator : Algoryx
License : Apache License 2.0
Project Creator : Algoryx
public static bool ShouldBeShownInInspector( MemberInfo memberInfo )
{
if ( memberInfo == null )
return false;
// Override hidden in inspector.
var runtimeHide = EditorApplication.isPlayingOrWillChangePlaymode &&
memberInfo.IsDefined( typeof( HideInRuntimeInspectorAttribute ), true );
if ( memberInfo.IsDefined( typeof( HideInInspector ), true ) || runtimeHide )
return false;
// In general, don't show UnityEngine objects unless ShowInInspector is set.
bool show = memberInfo.IsDefined( typeof( ShowInInspector ), true ) ||
!( memberInfo.DeclaringType.Namespace != null &&
memberInfo.DeclaringType.Namespace.Contains( "UnityEngine" ) );
return show;
}
19
View Source File : TypeExtensions.cs
License : MIT License
Project Creator : aliencube
License : MIT License
Project Creator : aliencube
public static bool IsUnflaggedEnumType(this Type type)
{
var isEnum = typeof(Enum).IsreplacedignableFrom(type);
if (!isEnum)
{
return false;
}
var isFlagged = type.IsDefined(typeof(FlagsAttribute), false);
if (isFlagged)
{
return false;
}
return true;
}
19
View Source File : FrameworkTest.cs
License : MIT License
Project Creator : aljazsim
License : MIT License
Project Creator : aljazsim
private void TestMethodModifiers(MethodInfo method)
{
if (!method.IsStatic)
{
replacedert.Fail($"Method {method.Name} should be static.");
}
else if (!method.IsPublic)
{
replacedert.Fail($"Method {method.Name} should be public.");
}
else if (!method.IsDefined(typeof(ExtensionAttribute), false))
{
replacedert.Fail($"Method {method.Name} should be an extension method.");
}
}
19
View Source File : ReflectionExtensions.cs
License : Apache License 2.0
Project Creator : allenai
License : Apache License 2.0
Project Creator : allenai
public static bool IsAnonymous(this System.Reflection.TypeInfo type)
{
return type.Namespace == null
&& type.IsSealed
&& (type.Name.StartsWith("<>f__AnonymousType", StringComparison.Ordinal)
|| type.Name.StartsWith("<>__AnonType", StringComparison.Ordinal)
|| type.Name.StartsWith("VB$AnonymousType_", StringComparison.Ordinal))
&& type.IsDefined(typeof(CompilerGeneratedAttribute), false);
}
19
View Source File : TypeExtension.cs
License : MIT License
Project Creator : AlphaYu
License : MIT License
Project Creator : AlphaYu
public static bool IsAttributeDefined<T>([NotNull] this object @this, bool inherit = true) where T : Attribute
=> @this.GetType().IsDefined(typeof(T), inherit);
19
View Source File : ReflectionExtension.cs
License : MIT License
Project Creator : AlphaYu
License : MIT License
Project Creator : AlphaYu
public static bool IsAttributeDefined([NotNull] this object @this, Type attributeType, bool inherit = true)
{
return @this.GetType().IsDefined(attributeType, inherit);
}
19
View Source File : ReflectionExtension.cs
License : MIT License
Project Creator : AlphaYu
License : MIT License
Project Creator : AlphaYu
public static bool IsAttributeDefined<T>([NotNull] this object @this, bool inherit = true) where T : Attribute
{
return @this.GetType().IsDefined(typeof(T), inherit);
}
19
View Source File : TypeExtension.cs
License : MIT License
Project Creator : AlphaYu
License : MIT License
Project Creator : AlphaYu
public static bool IsAttributeDefined([NotNull] this object @this, Type attributeType, bool inherit = true)
=> @this.GetType().IsDefined(attributeType, inherit);
19
View Source File : RecurringJobBuilder.cs
License : MIT License
Project Creator : AlphaYu
License : MIT License
Project Creator : AlphaYu
public void Build(Func<IEnumerable<Type>> typesProvider)
{
if (typesProvider == null) throw new ArgumentNullException(nameof(typesProvider));
foreach (var type in typesProvider())
{
foreach (var method in type.GetTypeInfo().DeclaredMethods)
{
if (!method.IsDefined(typeof(RecurringJobAttribute), false)) continue;
var attribute = method.GetCustomAttribute<RecurringJobAttribute>(false);
if (attribute == null) continue;
if (string.IsNullOrWhiteSpace(attribute.RecurringJobId))
{
attribute.RecurringJobId = method.GetRecurringJobId();
}
if (!attribute.Enabled)
{
RecurringJob.RemoveIfExists(attribute.RecurringJobId);
continue;
}
_registry.Register(
attribute.RecurringJobId,
method,
attribute.Cron,
attribute.TimeZone,
attribute.Queue ?? EnqueuedState.DefaultQueue);
}
}
}
19
View Source File : MemberInfoExtensions.cs
License : MIT License
Project Creator : amolines
License : MIT License
Project Creator : amolines
public static List<TAttribute> GetAttributesOfMemberAndDeclaringType<TAttribute>(this MemberInfo memberInfo)
where TAttribute : Attribute
{
var attributeList = new List<TAttribute>();
//Add attributes on the member
if (memberInfo.IsDefined(typeof(TAttribute), true))
{
attributeList.AddRange(memberInfo.GetCustomAttributes(typeof(TAttribute), true).Cast<TAttribute>());
}
//Add attributes on the clreplaced
if (memberInfo.DeclaringType != null && memberInfo.DeclaringType.IsDefined(typeof(TAttribute), true))
{
attributeList.AddRange(memberInfo.DeclaringType.GetCustomAttributes(typeof(TAttribute), true).Cast<TAttribute>());
}
return attributeList;
}
19
View Source File : ContentManager.cs
License : MIT License
Project Creator : Aminator
License : MIT License
Project Creator : Aminator
public bool IsDefined(Type attributeType, bool inherit)
{
return type.IsDefined(attributeType, inherit);
}
19
View Source File : ContentManager.cs
License : MIT License
Project Creator : Aminator
License : MIT License
Project Creator : Aminator
public bool IsDefined(Type attributeType, bool inherit)
{
return memberInfo.IsDefined(attributeType, inherit);
}
19
View Source File : ContentManager.cs
License : MIT License
Project Creator : Aminator
License : MIT License
Project Creator : Aminator
private object[] GetAdditionalAttributes(object[] attributes, bool inherit)
{
if (!memberInfo.IsDefined(typeof(DesignerSerializationVisibilityAttribute), inherit) && memberInfo.IsDefined(typeof(IgnoreDataMemberAttribute), inherit))
{
return attributes.Concat(new[] { new DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden) }).ToArray();
}
return attributes;
}
19
View Source File : HotReloader.cs
License : MIT License
Project Creator : AndreiMisiukevich
License : MIT License
Project Creator : AndreiMisiukevich
private void SetupNamedChildren(object obj)
{
var element = obj as Element;
if (element == null)
{
return;
}
var fields = obj.GetType()
.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
.Where(f => f.IsDefined(typeof(GeneratedCodeAttribute), true));
foreach (var field in fields)
{
var value = element.FindByName<object>(field.Name);
field.SetValue(obj, value);
}
}
19
View Source File : EnumTypeDrawer.cs
License : MIT License
Project Creator : AnotherEnd15
License : MIT License
Project Creator : AnotherEnd15
public object DrawAndGetNewValue(Type memberType, string memberName, object value, object target)
{
if (memberType.IsDefined(typeof (FlagsAttribute), false))
{
return EditorGUILayout.EnumFlagsField(memberName, (Enum) value);
}
return EditorGUILayout.EnumPopup(memberName, (Enum) value);
}
19
View Source File : ComponentViewEditor.cs
License : MIT License
Project Creator : AnotherEnd15
License : MIT License
Project Creator : AnotherEnd15
public static void Draw(object obj)
{
try
{
FieldInfo[] fields = obj.GetType()
.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
EditorGUILayout.BeginVertical();
foreach (FieldInfo fieldInfo in fields)
{
Type type = fieldInfo.FieldType;
if (type.IsDefined(typeof (HideInInspector), false))
{
continue;
}
if (fieldInfo.IsDefined(typeof (HideInInspector), false))
{
continue;
}
object value = fieldInfo.GetValue(obj);
foreach (ITypeDrawer typeDrawer in typeDrawers)
{
if (!typeDrawer.HandlesType(type))
{
continue;
}
string fieldName = fieldInfo.Name;
if (fieldName.Length > 17 && fieldName.Contains("k__BackingField"))
{
fieldName = fieldName.Substring(1, fieldName.Length - 17);
}
value = typeDrawer.DrawAndGetNewValue(type, fieldName, value, null);
fieldInfo.SetValue(obj, value);
break;
}
}
EditorGUILayout.EndVertical();
}
catch (Exception e)
{
Log.Error($"component view error: {obj.GetType().FullName} {e}");
}
}
19
View Source File : SurrogateSerializer.cs
License : MIT License
Project Creator : AnotherEnd15
License : MIT License
Project Creator : AnotherEnd15
private static bool HasCast(TypeModel model, Type type, Type from, Type to, out MethodInfo op)
{
#if PROFILE259
System.Collections.Generic.List<MethodInfo> list = new System.Collections.Generic.List<MethodInfo>();
foreach (var item in type.GetRuntimeMethods())
{
if (item.IsStatic) list.Add(item);
}
MethodInfo[] found = list.ToArray();
#else
const BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
MethodInfo[] found = type.GetMethods(flags);
#endif
ParameterInfo[] paramTypes;
Type convertAttributeType = null;
for (int i = 0; i < found.Length; i++)
{
MethodInfo m = found[i];
if (m.ReturnType != to) continue;
paramTypes = m.GetParameters();
if (paramTypes.Length == 1 && paramTypes[0].ParameterType == from)
{
if (convertAttributeType == null)
{
convertAttributeType = model.MapType(typeof(ProtoConverterAttribute), false);
if (convertAttributeType == null)
{ // attribute isn't defined in the source replacedembly: stop looking
break;
}
}
if (m.IsDefined(convertAttributeType, true))
{
op = m;
return true;
}
}
}
for (int i = 0; i < found.Length; i++)
{
MethodInfo m = found[i];
if ((m.Name != "op_Implicit" && m.Name != "op_Explicit") || m.ReturnType != to)
{
continue;
}
paramTypes = m.GetParameters();
if (paramTypes.Length == 1 && paramTypes[0].ParameterType == from)
{
op = m;
return true;
}
}
op = null;
return false;
}
19
View Source File : ReflectMaster.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools
private static IEditorField GetEditorField(MemberData member, object owner)
{
if (!_isInitialized)
{
lock (_typedEditorFields)
{
if (!_isInitialized)
{
PopulateKnownEditorFields();
_isInitialized = true;
}
}
}
var forType = GetMemberType(member);
if (forType.IsGenericType)
{
forType = forType.GetGenericTypeDefinition();
}
else if (forType.IsEnum)
{
if (forType.IsDefined<FlagsAttribute>(false))
{
return new EnumMaskField(member, owner);
}
return new EnumSelectField(member, owner);
}
else if (forType.IsArray)
{
forType = typeof(Array);
}
Type result = null;
if (_typedEditorFields.TryGetValue(forType, out result))
{
return Activator.CreateInstance(result, member, owner) as IEditorField;
}
return new CustomField(member, owner);
}
19
View Source File : Implementor.cs
License : MIT License
Project Creator : apexsharp
License : MIT License
Project Creator : apexsharp
private static ConcurrentDictionary<Type, Type> DiscoverDefaultImplementations()
{
var result = new ConcurrentDictionary<Type, Type>();
var implementationTypes =
from t in typeof(Implementor).replacedembly.GetTypes()
where t.IsDefined(typeof(ImplementsAttribute), false)
select t;
foreach (var implementationType in implementationTypes)
{
var implements = implementationType.GetCustomAttribute<ImplementsAttribute>();
var apiType = implements.Type;
result[apiType] = implementationType;
}
return result;
}
19
View Source File : WrappedMethodInfo.cs
License : MIT License
Project Creator : Aragas
License : MIT License
Project Creator : Aragas
public override bool IsDefined(Type attributeType, bool inherit) => _methodInfoImplementation.IsDefined(attributeType, inherit);
19
View Source File : WrappedPropertyInfo.cs
License : MIT License
Project Creator : Aragas
License : MIT License
Project Creator : Aragas
public override bool IsDefined(Type attributeType, bool inherit) => _propertyInfoImplementation.IsDefined(attributeType, inherit);
19
View Source File : PhotonEditor.cs
License : MIT License
Project Creator : ArcturusZhang
License : MIT License
Project Creator : ArcturusZhang
public static void UpdateRpcList()
{
List<string> additionalRpcs = new List<string>();
HashSet<string> currentRpcs = new HashSet<string>();
var types = GetAllSubTypesInScripts(typeof(MonoBehaviour));
foreach (var mono in types)
{
MethodInfo[] methods = mono.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (MethodInfo method in methods)
{
if (method.IsDefined(typeof(PunRPC), false))
{
currentRpcs.Add(method.Name);
if (!additionalRpcs.Contains(method.Name) && !PhotonNetwork.PhotonServerSettings.RpcList.Contains(method.Name))
{
additionalRpcs.Add(method.Name);
}
}
}
}
if (additionalRpcs.Count > 0)
{
// LIMITS RPC COUNT
if (additionalRpcs.Count + PhotonNetwork.PhotonServerSettings.RpcList.Count >= byte.MaxValue)
{
if (currentRpcs.Count <= byte.MaxValue)
{
bool clearList = EditorUtility.DisplayDialog(CurrentLang.IncorrectRPCListreplacedle, CurrentLang.IncorrectRPCListLabel, CurrentLang.RemoveOutdatedRPCsLabel, CurrentLang.CancelButton);
if (clearList)
{
PhotonNetwork.PhotonServerSettings.RpcList.Clear();
PhotonNetwork.PhotonServerSettings.RpcList.AddRange(currentRpcs);
}
else
{
return;
}
}
else
{
EditorUtility.DisplayDialog(CurrentLang.FullRPCListreplacedle, CurrentLang.FullRPCListLabel, CurrentLang.SkipRPCListUpdateLabel);
return;
}
}
additionalRpcs.Sort();
Undo.RecordObject(PhotonNetwork.PhotonServerSettings, "Update PUN RPC-list");
PhotonNetwork.PhotonServerSettings.RpcList.AddRange(additionalRpcs);
PhotonEditor.SaveSettings();
}
}
19
View Source File : LocalStackFixture.cs
License : MIT License
Project Creator : armutcom
License : MIT License
Project Creator : armutcom
private static FieldInfo GetBackingField(PropertyInfo pi) {
if (!pi.CanRead || !pi.GetGetMethod(nonPublic:true).IsDefined(typeof(CompilerGeneratedAttribute), inherit:true))
return null;
var backingField = pi.DeclaringType.GetField($"<{pi.Name}>k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic);
if (backingField == null)
return null;
if (!backingField.IsDefined(typeof(CompilerGeneratedAttribute), inherit:true))
return null;
return backingField;
}
19
View Source File : UnityDebugViewerLogger.cs
License : Apache License 2.0
Project Creator : AsanCai
License : Apache License 2.0
Project Creator : AsanCai
[IgnoreStackTrace]
private static List<StackFrame> ParseSystemStackTrace(ref string extraInfo)
{
List<StackFrame> stackFrameList = new List<StackFrame>();
StackTrace stackTrace = new StackTrace(true);
StackFrame[] stackFrames = stackTrace.GetFrames();
for (int i = 0; i < stackFrames.Length; i++)
{
StackFrame stackFrame = stackFrames[i];
var method = stackFrame.GetMethod();
if (!method.IsDefined(typeof(IgnoreStackTrace), true))
{
/// ignore all the stack message generated by Unity internal method
if (method.Name.Equals("InternalInvoke"))
{
break;
}
stackFrameList.Add(stackFrame);
}
else
{
foreach (object attributes in method.GetCustomAttributes(false))
{
IgnoreStackTrace ignoreAttr = (IgnoreStackTrace)attributes;
/// check and display corresponding method as extraInfo
if (ignoreAttr != null && ignoreAttr.showAsExtraInfo)
{
string methodParam = string.Empty;
var paramArray = method.GetParameters();
if (paramArray != null)
{
string[] paramType = new string[paramArray.Length];
for (int index = 0; index < paramArray.Length; index++)
{
paramType[index] = paramArray[index].ParameterType.Name;
}
methodParam = string.Join(", ", paramType);
}
extraInfo = string.Format("{0}:{1}({2})", method.DeclaringType.FullName, method.Name, methodParam);
}
}
}
}
return stackFrameList;
}
19
View Source File : Export.cs
License : MIT License
Project Creator : atenfyr
License : MIT License
Project Creator : atenfyr
private static void InitAllFields()
{
if (_allFields != null) return;
_allFields = typeof(Export).GetFields().Where(fld => fld.IsDefined(typeof(FObjectExportFieldAttribute), true)).OrderBy(fld => ((FObjectExportFieldAttribute[])fld.GetCustomAttributes(typeof(FObjectExportFieldAttribute), true))[0].DisplayingIndex).ToArray();
}
19
View Source File : PageSettingsEnumTypes.cs
License : Microsoft Public License
Project Creator : atrenton
License : Microsoft Public License
Project Creator : atrenton
internal static string XmlEnumValue(this Enum e)
{
var info = e.GetType().GetField(e.ToString("G"));
var value = string.Empty;
if (info.IsDefined(s_xmlEnumType, false))
{
var obj = info.GetCustomAttributes(s_xmlEnumType, false);
var attrib = obj[0] as XmlEnumAttribute;
value = attrib.Name;
}
return value;
}
19
View Source File : VisitorExtensions.cs
License : MIT License
Project Creator : AutoMapper
License : MIT License
Project Creator : AutoMapper
public static ParameterExpression GetParameterExpression(this Expression expression)
{
if (expression == null)
return null;
//the node represents parameter of the expression
switch (expression.NodeType)
{
case ExpressionType.Parameter:
return (ParameterExpression)expression;
case ExpressionType.Quote:
return GetParameterExpression(((UnaryExpression)expression).Operand);
case ExpressionType.Lambda:
return GetParameterExpression(((LambdaExpression)expression).Body);
case ExpressionType.ConvertChecked:
case ExpressionType.Convert:
var ue = expression as UnaryExpression;
return GetParameterExpression(ue?.Operand);
case ExpressionType.TypeAs:
return ((UnaryExpression)expression).Operand.GetParameterExpression();
case ExpressionType.TypeIs:
return ((TypeBinaryExpression)expression).Expression.GetParameterExpression();
case ExpressionType.MemberAccess:
return GetParameterExpression(((MemberExpression)expression).Expression);
case ExpressionType.Call:
var methodExpression = expression as MethodCallExpression;
var parentExpression = methodExpression?.Object;//Method is an instance method
var isExtension = methodExpression != null && methodExpression.Method.IsDefined(typeof(ExtensionAttribute), true);
if (isExtension && parentExpression == null && methodExpression.Arguments.Count > 0)
parentExpression = methodExpression.Arguments[0];//Method is an extension method based on the type of methodExpression.Arguments[0].
return isExtension && parentExpression == null && methodExpression.Arguments.Count > 0
? GetParameterExpression(methodExpression.Arguments[0])
: GetParameterExpression(parentExpression);
}
return null;
}
19
View Source File : NullsafeQueryRewriter.cs
License : MIT License
Project Creator : AutoMapper
License : MIT License
Project Creator : AutoMapper
static bool IsExtensionMethod(MethodInfo element)
{
return element.IsDefined(typeof(ExtensionAttribute), false);
}
19
View Source File : PrependParentNameVisitor.cs
License : MIT License
Project Creator : AutoMapper
License : MIT License
Project Creator : AutoMapper
protected override Expression VisitMethodCall(MethodCallExpression node)
{
if (!IsParentParameterExpression())
return base.VisitMethodCall(node);
if (!object.ReferenceEquals(CurrentParameter, node.GetParameterExpression()))
return base.VisitMethodCall(node);
if (node.Method.IsStatic)
{
if (!IsExtentionMethod())
return base.VisitMethodCall(node);
if (node.Method.IsGenericMethod)
return Expression.Call
(
node.Method.DeclaringType,
node.Method.Name,
node.Method.GetGenericArguments(),
GetNewArgumentsForExtensionMethod()
);
else
return Expression.Call(node.Method, GetNewArgumentsForExtensionMethod());
}
//instance method
if (node.Method.IsGenericMethod)
{
return Expression.Call
(
GetNewParent(),
node.Method.Name,
node.Method.GetGenericArguments(),
node.Arguments.ToArray()
);
}
else
{
return Expression.Call
(
GetNewParent(),
node.Method,
node.Arguments
);
}
Expression[] GetNewArgumentsForExtensionMethod()
{
Expression[] arguments = node.Arguments.ToArray();
arguments[0] = GetNewParent();
return arguments.ToArray();
}
Expression GetNewParent()
=> string.IsNullOrEmpty(ParentFullName)
? NewParameter
: ExpressionHelpers.MemberAccesses(ParentFullName, NewParameter);
bool IsParentParameterExpression()
{
if (node.Method.IsStatic)
return node.Arguments[0] is ParameterExpression;
if (!node.Method.IsStatic)
return node.Object is ParameterExpression;
return false;
}
bool IsExtentionMethod()
=> node.Method.IsDefined(typeof(ExtensionAttribute), true);
}
19
View Source File : TypeExtensions.cs
License : MIT License
Project Creator : AutoMapper
License : MIT License
Project Creator : AutoMapper
public static bool Has<TAttribute>(this Type type) where TAttribute : Attribute => type.GetTypeInfo().IsDefined(typeof(TAttribute), inherit: false);
19
View Source File : ModelSpecification.cs
License : MIT License
Project Creator : Avanade
License : MIT License
Project Creator : Avanade
public JObject GetModelSpecification()
{
// Retrive the replacedemblies that contains the attribute ModelSpecificationAttribute
replacedembly[] replacedemblies = AppDomain.CurrentDomain.Getreplacedemblies();
var _clreplacedSigned = (from replacedembly in replacedemblies
where !replacedembly.IsDynamic
from type in replacedembly.ExportedTypes
where type.IsDefined(typeof(ModelSpecificationAttribute), false)
select type).FirstOrDefault();
JSchema schema;
//Check if some clreplaced contains the attribute ModelSpecificationAttribute
if (_clreplacedSigned != null)
{
//Create a instance of Jschema generator.
JSchemaGenerator generator = new JSchemaGenerator();
//Setting some configurations.
generator.DefaultRequired = Newtonsoft.Json.Required.Default;
generator.SchemaReferenceHandling = SchemaReferenceHandling.None;
generator.GenerationProviders.Add(new StringEnumGenerationProvider());
//Generate the schema.
schema = generator.Generate(_clreplacedSigned);
//Recovery the object already got based on the name clreplaced
var item = ModelSpecificationEngine.swaggerMetaDatas.Where(x => x.Name == _clreplacedSigned.Name).FirstOrDefault();
//Check if the root clreplaced contains the description.
if (!string.IsNullOrWhiteSpace(item.Description))
{
schema.Description = Regex.Replace(item.Description, ModelSpecificationEngine.PATTERN, string.Empty).Trim();
}
//Now its necessary check if have
foreach (var x in schema.Properties)
{
//Check if has more properties in this case will be necessary.
if (x.Value.Properties.Count > 0)
{
//Call the recursive tree for get all properties from this object
this.RecursiveTree(x.Key, x.Value.Properties);
}
//Now check if some properties have description. For type primite of the root parent write the descript without annotations.
if (item.PropertyRutime.TryGetValue(x.Key, out Tuple<string, bool> descriptionProp))
{
x.Value.Description = Regex.Replace(descriptionProp.Item1.Replace(ModelSpecificationEngine.REQUIRED, string.Empty).Trim(), ModelSpecificationEngine.PATTERN, "").Trim();
}
}
}
else
{
///If there isn't Custom Attribute, will be throw exception.
throw new LightException($"No Attribute ModelSpecification has been informed on the Model clreplaced");
}
JObject json = JObject.Parse(schema.ToString());
Dictionary<string, Tuple<string, bool>> requireds = ModelSpecificationEngine.swaggerMetaDatas.Where(x => x.Name == _clreplacedSigned.Name).FirstOrDefault().PropertyRutime;
List<string> variablesRequired = new List<string>();
foreach (KeyValuePair<string, Tuple<string, bool>> entry in requireds)
{
if (entry.Value.Item2)
{
variablesRequired.Add(entry.Key);
}
//Add format to the root parent.
if (Regex.Match(entry.Value.Item1, ModelSpecificationEngine.PATTERN).Success)
{
var retriveJsonProps = Regex.Match(entry.Value.Item1, ModelSpecificationEngine.PATTERN).Value.ToString();
JObject obj = JObject.Parse(retriveJsonProps);
var tokens = json.FindTokens(entry.Key).FirstOrDefault();
if (tokens != null)
{
tokens.Last.AddAfterSelf(new JProperty("format", obj));
}
}
}
//Populating the root
json.Property("properties").AddAfterSelf(new JProperty("required", variablesRequired.ToArray()));
ModelSpecificationEngine.projectMeta.project = _clreplacedSigned.replacedembly.FullName.Split(',').FirstOrDefault();
HubAttribute attribute = (HubAttribute)_clreplacedSigned.GetCustomAttributes(typeof(HubAttribute), false).FirstOrDefault();
ModelSpecificationEngine.projectMeta.hub = string.IsNullOrEmpty(attribute.HubName) ? string.Empty : attribute.HubName;
//Adding inside of meta.
json.Property("properties").AddAfterSelf(new JProperty("meta", JObject.FromObject(ModelSpecificationEngine.projectMeta)));
//Loop para adicionar required para cada elemento filho
foreach (SwaggerMetaData swaggerMeta in ModelSpecificationEngine.swaggerMetaDatas.Where(x => x.Name != _clreplacedSigned.Name))
{
List<string> childRequireds = new List<string>();
foreach (KeyValuePair<string, Tuple<string, bool>> props in swaggerMeta.PropertyRutime)
{
if (props.Value.Item2)
{
childRequireds.Add(props.Key);
}
//Loop for add in deep formats to childs
if (Regex.Match(props.Value.Item1, ModelSpecificationEngine.PATTERN).Success)
{
var retriveJsonProps = Regex.Match(props.Value.Item1, ModelSpecificationEngine.PATTERN).Value.ToString();
JObject obj = JObject.Parse(retriveJsonProps);
var tokens = json.FindTokens(props.Key).FirstOrDefault();
if (tokens != null)
{
tokens.Last.AddAfterSelf(new JProperty("format", obj));
}
}
}
if (childRequireds.Count > 0)
{
var tokens = json.FindTokens(swaggerMeta.Name).FirstOrDefault();
if (tokens != null)
{
tokens.Last.AddAfterSelf(new JProperty("required", childRequireds.ToArray()));
}
}
}
return json;
}
19
View Source File : PeriodicJobBuilder.cs
License : MIT License
Project Creator : bamotav
License : MIT License
Project Creator : bamotav
internal static void GetAllJobs()
{
var _registry = new RecurringJobRegistry();
foreach (var replacedembly in StoragereplacedemblySingleton.GetInstance().currentreplacedembly)
{
foreach (var type in replacedembly.GetTypes())
{
foreach (var method in type.GetTypeInfo().DeclaredMethods)
{
if (!method.IsDefined(typeof(RecurringJobAttribute), false)) continue;
var attribute = method.GetCustomAttribute<RecurringJobAttribute>(false);
if (attribute == null) continue;
if (method.GetCustomAttributes(true).OfType<RecurringJobAttribute>().Any())
{
var attr = method.GetCustomAttribute<RecurringJobAttribute>();
}
if(!JobAgent.IsValidJobId(attribute.RecurringJobId) && !JobAgent.IsValidJobId(attribute.RecurringJobId, JobAgent.tagStopJob))
{
_registry.Register(
attribute.RecurringJobId,
method,
attribute.Cron,
string.IsNullOrEmpty(attribute.TimeZone) ? TimeZoneInfo.Utc : TimeZoneInfo.FindSystemTimeZoneById(attribute.TimeZone),
attribute.Queue ?? EnqueuedState.DefaultQueue);
}
}
}
}
}
19
View Source File : ModuleBase.cs
License : The Unlicense
Project Creator : BAndysc
License : The Unlicense
Project Creator : BAndysc
protected void AutoRegisterByConvention(replacedembly replacedembly, IContainerRegistry containerRegistry)
{
IUnityContainer unityContainer = ((IContainerExtension<IUnityContainer>)containerRegistry).Instance;
var defaultRegisters = replacedembly.GetTypes().Where(t => !t.IsAbstract && t.IsDefined(typeof(AutoRegisterAttribute), true));
foreach (Type register in defaultRegisters)
{
bool singleton = register.IsDefined(typeof(SingleInstanceAttribute), false);
if (singleton)
containerRegistry.RegisterSingleton(register);
foreach (Type @interface in register.GetInterfaces())
{
bool isUnique = [email protected](typeof(NonUniqueProviderAttribute), false);
string name = register + @interface.ToString();
if (singleton && isUnique)
{
containerRegistry.RegisterSingleton(@interface, register);
// unityContainer.RegisterFactory(@interface, c => unityContainer.Resolve(register), new ContainerControlledLifetimeManager());
}
else
containerRegistry.Register(@interface, register, isUnique ? null : name);
}
}
}
19
View Source File : ScopedModuleBase.cs
License : The Unlicense
Project Creator : BAndysc
License : The Unlicense
Project Creator : BAndysc
public override void FinalizeRegistration(IContainerRegistry container)
{
var typesToRegisterInParent = GetType().replacedembly.GetTypes().Where(t => t.IsDefined(typeof(AutoRegisterToParentScopeAttribute), false) && !t.IsAbstract);
foreach (var register in typesToRegisterInParent)
{
var instance = moduleScope.Resolve(register);
foreach (Type @interface in register.GetInterfaces().Union(new[] {register}))
{
string name = register + @interface.ToString();
container.RegisterInstance(@interface, instance, name);
}
}
}
19
View Source File : InvokableFactory.cs
License : MIT License
Project Creator : Bannerlord-Coop-Team
License : MIT License
Project Creator : Bannerlord-Coop-Team
public static Func<TDeclaring, object> CreateCallWithReturn<TDeclaring>(MethodInfo method)
{
var instanceType = method.DeclaringType;
var arg0 = Expression.Parameter(typeof(TDeclaring), "arg0");
MethodCallExpression exCall;
// `TDeclaring` might be a base clreplaced or interface of `instanceType`.
if (instanceType == typeof(TDeclaring))
{
exCall = Expression.Call(arg0, method);
}
else if (method.IsDefined(typeof(ExtensionAttribute), false))
{
exCall = Expression.Call(null, method, arg0);
}
else
{
// The member resides in `targetType` => convert
var arg0Converted = Expression.Convert(arg0, instanceType);
exCall = Expression.Call(arg0Converted, method);
}
var body = Expression.Convert(exCall, typeof(object));
var lambda =
Expression.Lambda<Func<TDeclaring, object>>(body, arg0);
return lambda.Compile();
}
19
View Source File : InvokableFactory.cs
License : MIT License
Project Creator : Bannerlord-Coop-Team
License : MIT License
Project Creator : Bannerlord-Coop-Team
public static Action<TDeclaring, TParam> CreateCall<TDeclaring, TParam>(MethodInfo method)
{
var instanceType = method.DeclaringType;
var arg0 = Expression.Parameter(typeof(TDeclaring), "arg0");
var arg1 = Expression.Parameter(typeof(TParam), "arg1");
var exConvertToParam0 = Expression.Convert(
arg1,
method.GetParameters()[0].ParameterType);
MethodCallExpression exCall;
// `TDeclaring` might be a base clreplaced or interface of `instanceType`.
if (instanceType == typeof(TDeclaring))
{
exCall = Expression.Call(arg0, method, exConvertToParam0);
}
else if (method.IsDefined(typeof(ExtensionAttribute), false))
{
var exConvertToParam1 = Expression.Convert(
arg1,
method.GetParameters()[1].ParameterType);
exCall = Expression.Call(null, method, arg0, exConvertToParam1);
}
else
{
// The member resides in `targetType` => convert
var arg0Converted = Expression.Convert(arg0, instanceType);
exCall = Expression.Call(arg0Converted, method, exConvertToParam0);
}
var lambda =
Expression.Lambda<Action<TDeclaring, TParam>>(exCall, arg0, arg1);
return lambda.Compile();
}
See More Examples