Here are the examples of the csharp api System.Reflection.MemberInfo.GetCustomAttributes(bool) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
959 Examples
19
Source : ScenarioStep.cs
with GNU Lesser General Public License v3.0
from cnAbp
with GNU Lesser General Public License v3.0
from cnAbp
public virtual string GetDisplayText()
{
var displayNameAttr = GetType()
.GetCustomAttributes(true)
.OfType<DisplayNameAttribute>()
.FirstOrDefault();
if (displayNameAttr != null)
{
return displayNameAttr.DisplayName;
}
return GetType()
.Name
.RemovePostFix(nameof(ScenarioStep));
}
19
Source : ReflectionUtil.cs
with MIT License
from cocosip
with MIT License
from cocosip
public static List<object> GetAttributesOfMemberAndDeclaringType(MemberInfo memberInfo, bool inherit = true)
{
var attributeList = new List<object>();
attributeList.AddRange(memberInfo.GetCustomAttributes(inherit));
if (memberInfo.DeclaringType != null)
{
attributeList.AddRange(memberInfo.DeclaringType.GetTypeInfo().GetCustomAttributes(inherit));
}
return attributeList;
}
19
Source : ReflectionUtil.cs
with MIT License
from cocosip
with MIT License
from cocosip
public static List<object> GetAttributesOfMemberAndType(MemberInfo memberInfo, Type type, bool inherit = true)
{
var attributeList = new List<object>();
attributeList.AddRange(memberInfo.GetCustomAttributes(inherit));
attributeList.AddRange(type.GetTypeInfo().GetCustomAttributes(inherit));
return attributeList;
}
19
Source : ReflectionUtil.cs
with MIT License
from cocosip
with MIT License
from cocosip
public static TAttribute GetSingleAttributeOfMemberOrDeclaringTypeOrDefault<TAttribute>(MemberInfo memberInfo, TAttribute defaultValue = default(TAttribute), bool inherit = true)
where TAttribute : clreplaced
{
return memberInfo.GetCustomAttributes(true).OfType<TAttribute>().FirstOrDefault()
?? memberInfo.ReflectedType?.GetTypeInfo().GetCustomAttributes(true).OfType<TAttribute>().FirstOrDefault()
?? defaultValue;
}
19
Source : DistributedCache.cs
with MIT License
from cocosip
with MIT License
from cocosip
protected virtual void SetDefaultOptions()
{
//CacheName
var cacheNameAttribute = typeof(TCacheItem)
.GetCustomAttributes(true)
.OfType<CacheNameAttribute>()
.FirstOrDefault();
CacheName = cacheNameAttribute != null ? cacheNameAttribute.Name : typeof(TCacheItem).Name;
}
19
Source : AttributeMap.cs
with Apache License 2.0
from CodeZeg
with Apache License 2.0
from CodeZeg
public static AttributeMap[] Create(TypeModel model, Type type, bool inherit)
{
#if FEAT_IKVM
Type attribType = model.MapType(typeof(System.Attribute));
System.Collections.Generic.IList<CustomAttributeData> all = type.__GetCustomAttributes(attribType, inherit);
AttributeMap[] result = new AttributeMap[all.Count];
int index = 0;
foreach (CustomAttributeData attrib in all)
{
result[index++] = new AttributeDataMap(attrib);
}
return result;
#else
#if WINRT
Attribute[] all = System.Linq.Enumerable.ToArray(type.GetTypeInfo().GetCustomAttributes(inherit));
#else
object[] all = type.GetCustomAttributes(inherit);
#endif
AttributeMap[] result = new AttributeMap[all.Length];
for(int i = 0 ; i < all.Length ; i++)
{
result[i] = new ReflectionAttributeMap((Attribute)all[i]);
}
return result;
#endif
}
19
Source : AttributeMap.cs
with Apache License 2.0
from CodeZeg
with Apache License 2.0
from CodeZeg
public static AttributeMap[] Create(TypeModel model, MemberInfo member, bool inherit)
{
#if FEAT_IKVM
System.Collections.Generic.IList<CustomAttributeData> all = member.__GetCustomAttributes(model.MapType(typeof(Attribute)), inherit);
AttributeMap[] result = new AttributeMap[all.Count];
int index = 0;
foreach (CustomAttributeData attrib in all)
{
result[index++] = new AttributeDataMap(attrib);
}
return result;
#else
#if WINRT
Attribute[] all = System.Linq.Enumerable.ToArray(member.GetCustomAttributes(inherit));
#else
object[] all = member.GetCustomAttributes(inherit);
#endif
AttributeMap[] result = new AttributeMap[all.Length];
for(int i = 0 ; i < all.Length ; i++)
{
result[i] = new ReflectionAttributeMap((Attribute)all[i]);
}
return result;
#endif
}
19
Source : DbRepository.cs
with Apache License 2.0
from Coldairarrow
with Apache License 2.0
from Coldairarrow
protected static List<PropertyInfo> GetKeyPropertys<T>()
{
var properties = typeof(T)
.GetProperties()
.Where(x => x.GetCustomAttributes(true).Select(o => o.GetType().FullName).Contains(typeof(KeyAttribute).FullName))
.ToList();
return properties;
}
19
Source : DbRepository.cs
with MIT License
from Coldairarrow
with MIT License
from Coldairarrow
protected static List<PropertyInfo> GetKeyPropertys(Type type)
{
var properties = type
.GetProperties()
.Where(x => x.GetCustomAttributes(true).Select(o => o.GetType().FullName).Contains(typeof(KeyAttribute).FullName))
.ToList();
return properties;
}
19
Source : Interceptor.cs
with MIT License
from Coldairarrow
with MIT License
from Coldairarrow
public void Intercept(IInvocation invocation)
{
var allFilers = invocation.MethodInvocationTarget.GetCustomAttributes<BaseFilterAttribute>(true)
.Concat(invocation.InvocationTarget.GetType().GetCustomAttributes<BaseFilterAttribute>(true))
.Where(x => x is IFilter)
.Select(x => (IFilter)x)
.ToList();
//执行前
foreach(var aFiler in allFilers)
{
aFiler.OnActionExecuting(invocation);
if (!invocation.ReturnValue.IsNullOrEmpty())
return;
}
//执行
invocation.Proceed();
//执行后
allFilers.ForEach(aFiler =>
{
aFiler.OnActionExecuted(invocation);
});
}
19
Source : Interceptor.cs
with MIT License
from Coldairarrow
with MIT License
from Coldairarrow
public void Intercept(IInvocation invocation)
{
var allFilers = invocation.MethodInvocationTarget.GetCustomAttributes<BaseFilterAttribute>(true)
.Concat(invocation.InvocationTarget.GetType().GetCustomAttributes<BaseFilterAttribute>(true))
.Where(x => x is IFilter)
.Select(x => (IFilter)x)
.ToList();
//执行前
foreach (var aFiler in allFilers)
{
aFiler.OnActionExecuting(invocation);
if (!invocation.ReturnValue.IsNullOrEmpty())
return;
}
//执行
invocation.Proceed();
//执行后
allFilers.ForEach(aFiler =>
{
aFiler.OnActionExecuted(invocation);
});
}
19
Source : Specification.cs
with MIT License
from commandlineparser
with MIT License
from commandlineparser
public static Specification FromProperty(PropertyInfo property)
{
var attrs = property.GetCustomAttributes(true);
var oa = attrs.OfType<OptionAttribute>();
if (oa.Count() == 1)
{
var spec = OptionSpecification.FromAttribute(oa.Single(), property.PropertyType,
ReflectionHelper.GetNamesOfEnum(property.PropertyType));
if (spec.ShortName.Length == 0 && spec.LongName.Length == 0)
{
return spec.WithLongName(property.Name.ToLowerInvariant());
}
return spec;
}
var va = attrs.OfType<ValueAttribute>();
if (va.Count() == 1)
{
return ValueSpecification.FromAttribute(va.Single(), property.PropertyType,
property.PropertyType.GetTypeInfo().IsEnum
? Enum.GetNames(property.PropertyType)
: Enumerable.Empty<string>());
}
throw new InvalidOperationException();
}
19
Source : ReflectionExtensions.cs
with MIT License
from commandlineparser
with MIT License
from commandlineparser
public static IEnumerable<T> GetSpecifications<T>(this Type type, Func<PropertyInfo, T> selector)
{
return from pi in type.FlattenHierarchy().SelectMany(x => x.GetTypeInfo().GetProperties())
let attrs = pi.GetCustomAttributes(true)
where
attrs.OfType<OptionAttribute>().Any() ||
attrs.OfType<ValueAttribute>().Any()
group pi by pi.Name into g
select selector(g.First());
}
19
Source : ReflectionExtensions.cs
with MIT License
from commandlineparser
with MIT License
from commandlineparser
public static Maybe<Tuple<PropertyInfo, UsageAttribute>> GetUsageData(this Type type)
{
return
(from pi in type.FlattenHierarchy().SelectMany(x => x.GetTypeInfo().GetProperties())
let attrs = pi.GetCustomAttributes(true)
where attrs.OfType<UsageAttribute>().Any()
select Tuple.Create(pi, (UsageAttribute)attrs.First()))
.SingleOrDefault()
.ToMaybe();
}
19
Source : AttributeBasedDirectory.cs
with MIT License
from connellw
with MIT License
from connellw
private static IEnumerable<DirectoryTypePair> TryGetreplacedemblyTypes(replacedembly replacedembly)
{
try
{
return from type in replacedembly.GetExportedTypes()
from startAttribute in type.GetCustomAttributes<RestStartResourceAttribute>(true)
select new DirectoryTypePair
{
DirectoryName = startAttribute.DirectoryName,
Type = type
};
}
catch (NotSupportedException)
{
return null;
}
}
19
Source : EntityPrimaryKeyFinder.cs
with MIT License
from connellw
with MIT License
from connellw
public PropertyInfo GetPrimaryKeyInfo(Type type)
{
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo pI in properties)
{
object[] attributes = pI.GetCustomAttributes(true);
foreach (object attribute in attributes)
{
if (attribute is EdmScalarPropertyAttribute propertyAttr && propertyAttr.EnreplacedyKeyProperty)
return pI;
// TODO reintroduce System.Data.Linq.Mapping.ColumnAttribute
//if (attribute is ColumnAttribute columnAttr && columnAttr.IsPrimaryKey)
// return pI;
}
}
return null;
}
19
Source : CustomAttributeProvider.cs
with MIT License
from CoreWCF
with MIT License
from CoreWCF
public object[] GetCustomAttributes(bool inherit)
{
switch (ProviderType)
{
case AttributeProviderType.Type:
return Type.GetTypeInfo().GetCustomAttributes(inherit).ToArray();
case AttributeProviderType.MethodInfo:
return MethodInfo.GetCustomAttributes(inherit).ToArray();
case AttributeProviderType.MemberInfo:
return MemberInfo.GetCustomAttributes(inherit).ToArray();
case AttributeProviderType.ParameterInfo:
// ParameterInfo.GetCustomAttributes can return null instead of an empty enumerable
return ParameterInfo.GetCustomAttributes(inherit)?.ToArray();
}
Contract.replacedert(false, "This should never execute.");
throw new InvalidOperationException();
}
19
Source : AttributeEvaluatingExpressionTransformer.cs
with Apache License 2.0
from coronabytes
with Apache License 2.0
from coronabytes
private static IMethodCallExpressionTransformerAttribute GetTransformerProvider(MethodInfo methodInfo)
{
var attributes = methodInfo.GetCustomAttributes(true).OfType<IMethodCallExpressionTransformerAttribute>()
.ToArray();
if (attributes.Length > 1)
{
var message = string.Format(
"There is more than one attribute providing transformers declared for method '{0}.{1}'.",
methodInfo.DeclaringType,
methodInfo.Name);
throw new InvalidOperationException(message);
}
return attributes.SingleOrDefault();
}
19
Source : ILOp.cs
with BSD 3-Clause "New" or "Revised" License
from CosmosOS
with BSD 3-Clause "New" or "Revised" License
from CosmosOS
private static void DoGetFieldsInfo(Type aType, List<_FieldInfo> aFields, bool includeStatic)
{
var xCurList = new Dictionary<string, _FieldInfo>();
var xBindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
if (includeStatic)
{
xBindingFlags |= BindingFlags.Static;
}
var xFields = (from item in aType.GetFields(xBindingFlags)
orderby item.Name, item.DeclaringType.ToString()
select item).ToArray();
for (int i = 0; i < xFields.Length; i++)
{
var xField = xFields[i];
// todo: should be possible to have GetFields only return fields from a given type, thus removing need of next statement
if (xField.DeclaringType != aType)
{
continue;
}
string xId = xField.GetFullName();
var xInfo = new _FieldInfo(xId, SizeOfType(xField.FieldType), aType, xField.FieldType);
xInfo.IsStatic = xField.IsStatic;
xInfo.Field = xField;
var xFieldOffsetAttrib =
xField.GetCustomAttributes<FieldOffsetAttribute>(true).FirstOrDefault();
if (xFieldOffsetAttrib != null)
{
xInfo.Offset = (uint)xFieldOffsetAttrib.Value;
}
aFields.Add(xInfo);
xCurList.Add(xId, xInfo);
}
// now check plugs
if (PlugManager.PlugFields.TryGetValue(aType, out var xPlugFields))
{
foreach (var xPlugField in xPlugFields)
{
if (xCurList.TryGetValue(xPlugField.Key, out var xPluggedField))
{
// plugfield modifies an already existing field
// TODO: improve.
if (xPlugField.Value.IsExternalValue)
{
xPluggedField.IsExternalValue = true;
xPluggedField.FieldType = xPluggedField.FieldType.MakePointerType();
xPluggedField.Size = 4;
}
}
else
{
xPluggedField = new _FieldInfo(xPlugField.Value.FieldId, SizeOfType(xPlugField.Value.FieldType), aType,
xPlugField.Value.FieldType);
aFields.Add(xPluggedField);
}
}
}
Type xBase = aType.BaseType;
if (xBase != null)
{
DoGetFieldsInfo(xBase, aFields, includeStatic);
}
}
19
Source : PlugManager.cs
with BSD 3-Clause "New" or "Revised" License
from CosmosOS
with BSD 3-Clause "New" or "Revised" License
from CosmosOS
public void FindPlugImpls(IEnumerable<replacedembly> replacedemblies)
{
// TODO: Cache method list with info - so we dont have to keep
// scanning attributes for enabled etc repeatedly
// TODO: New plug system, common plug base which all descend from
// It can have a "this" member and then we
// can separate static from instance by the static keyword
// and ctors can be static "ctor" by name
// Will still need plug attrib though to specify target
// Also need to handle asm plugs, but those will be different anyways
// TODO: Allow whole clreplaced plugs? ie, a clreplaced that completely replaces another clreplaced
// and is subsreplaceduted on the fly? Plug scanner would direct all access to that
// clreplaced and throw an exception if any method, field, member etc is missing.
foreach (var xAsm in replacedemblies)
{
LogWarning("Loading plugs from replacedembly: " + xAsm.FullName);
// Find all clreplacedes marked as a Plug
foreach (var xPlugType in xAsm.GetTypes())
{
// Foreach, it is possible there could be one plug clreplaced with mult plug targets
foreach (var xAttrib in xPlugType.GetCustomAttributes<Plug>(false))
{
var xTargetType = xAttrib.Target;
// If no type is specified, try to find by a specified name.
// This is needed in cross replacedembly references where the
// plug cannot reference the replacedembly of the target type
if (xTargetType == null)
{
try
{
xTargetType = _typeResolver.ResolveType(xAttrib.TargetName, true, false);
}
catch (Exception ex)
{
if (!xAttrib.IsOptional)
{
throw new Exception("Error", ex);
}
continue;
}
}
Dictionary<Type, List<Type>> mPlugs;
if (xTargetType.ContainsGenericParameters)
{
mPlugs = xAttrib.Inheritable ? mGenericPlugImplsInhrt : mGenericPlugImpls;
}
else
{
mPlugs = xAttrib.Inheritable ? mPlugImplsInhrt : mPlugImpls;
}
if (mPlugs.TryGetValue(xTargetType, out var xImpls))
{
xImpls.Add(xPlugType);
}
else
{
mPlugs.Add(xTargetType, new List<Type>() { xPlugType });
}
}
}
}
}
19
Source : ResourceLoader.cs
with MIT License
from cr4yz
with MIT License
from cr4yz
private static string FindPathPrefix(Type type)
{
var attrib = type.GetCustomAttributes<PathPrefixAttribute>(false).FirstOrDefault();
return attrib?.Value;
}
19
Source : ReflectionUtility.cs
with Apache License 2.0
from crazyants
with Apache License 2.0
from crazyants
public static List<object> GetAttributesOfMemberAndDeclaringType(MemberInfo memberInfo, bool inherit = true)
{
var attributeList = new List<object>();
attributeList.AddRange(memberInfo.GetCustomAttributes(inherit));
//Add attributes on the clreplaced
if (memberInfo.DeclaringType != null)
{
attributeList.AddRange(memberInfo.DeclaringType.GetTypeInfo().GetCustomAttributes(inherit));
}
return attributeList;
}
19
Source : ReflectionExtensions.cs
with Apache License 2.0
from cs-util-com
with Apache License 2.0
from cs-util-com
public static bool TryGetCustomAttributes<T>(this MemberInfo self, out IEnumerable<T> attr, bool inherit = false) where T : Attribute {
attr = self.GetCustomAttributes<T>(inherit);
return !attr.IsNullOrEmpty();
}
19
Source : PluginBootstrapper.cs
with MIT License
from csharpfritz
with MIT License
from csharpfritz
internal IEnumerable<IFeature> GetFeaturesForStreamEvent(StreamEvent evt)
{
var outFeatures = new List<IFeature>();
// Identify the features that interact with the StreamEvent requested
var featuresToMake = _Features.Where(t =>
{
var attr = t.GetCustomAttributes(true)
.Where(a => a is ActivatingEventsAttribute).FirstOrDefault() as ActivatingEventsAttribute;
if (attr == null) return false;
return (attr.EventsListeningTo | evt) != StreamEvent.None;
});
// Instantiate the features that interact with the StreamEvent requested
foreach (var f in featuresToMake)
{
var newFeature = ActivatorUtilities.CreateInstance(ServiceProvider, f) as IFeature;
if (!(_Configuration?.FeatureConfigurations.ContainsKey(newFeature.Name) ?? false)) continue;
var featureConfig = _Configuration?.FeatureConfigurations[newFeature.Name];
if (featureConfig.IsEnabled)
{
if (featureConfig != null) newFeature.Configure(featureConfig);
if (featureConfig == null || newFeature.IsVisible) outFeatures.Add(newFeature);
}
}
return outFeatures;
}
19
Source : Attributes.cs
with MIT License
from CSharpWithUnity
with MIT License
from CSharpWithUnity
void UseMultipleAttributes()
{
{
Debug.Log("BaseThing's Attributes:");
var attribs = typeof(BaseThing).GetCustomAttributes(true);
foreach (var attrib in attribs)
{
Debug.Log(attrib);
}
// BaseThing's Attributes:
// Attributes+SpecialAttribute
// Attributes+SuperficialAttribute
}
{
Debug.Log("SuperThing's Attributes:");
var attribs = typeof(SuperThing).GetCustomAttributes(true);
foreach (var attrib in attribs)
{
Debug.Log(attrib);
}
// SuperThing's Attributes:
// Attributes+SpecialAttribute
}
}
19
Source : Attributes.cs
with MIT License
from CSharpWithUnity
with MIT License
from CSharpWithUnity
void UseCustomAttribute()
{
// using Reflection, get the custom attributes of the
// Something clreplaced.
var memberInfos = typeof(Something).GetCustomAttributes(true);
foreach (var i in memberInfos)
{
CustomAttribute custom = i as CustomAttribute;
Debug.Log(custom.customString);
}
// A Custom Attribute
}
19
Source : ReflectionHelper.cs
with MIT License
from csinkers
with MIT License
from csinkers
static Type[] BuildTypeCache()
{
PerfTracker.StartupEvent("Start building reflection cache");
var types = new List<Type>();
foreach (var replacedembly in AppDomain.CurrentDomain.Getreplacedemblies())
{
if (!replacedembly.FullName.Contains("Albion", StringComparison.OrdinalIgnoreCase))
continue;
Type[] replacedemblyTypes;
try
{
replacedemblyTypes = replacedembly.GetTypes();
}
catch (ReflectionTypeLoadException e)
{
replacedemblyTypes = e.Types;
}
foreach (var type in replacedemblyTypes.Where(x =>
x != null &&
!x.IsAbstract &&
x.GetCustomAttributes(false).Any()))
{
types.Add(type);
}
}
PerfTracker.StartupEvent("Done building reflection cache");
return types.ToArray();
}
19
Source : ResourcesSingleton.cs
with MIT License
from Cushmily
with MIT License
from Cushmily
private static string GetFilePath()
{
foreach (var customAttribute in typeof(T).GetCustomAttributes(true))
{
var path = customAttribute as ResourcePathAttribute;
if (path != null)
{
return path.filepath;
}
}
return string.Empty;
}
19
Source : LuisDialog.cs
with MIT License
from CXuesong
with MIT License
from CXuesong
public static IEnumerable<KeyValuePair<string, IntentActivityHandler>> EnumerateHandlers(object dialog)
{
var type = dialog.GetType();
var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
foreach (var method in methods)
{
var intents = method.GetCustomAttributes<LuisIntentAttribute>(inherit: true).ToArray();
IntentActivityHandler intentHandler = null;
try
{
intentHandler = (IntentActivityHandler)Delegate.CreateDelegate(typeof(IntentActivityHandler), dialog, method, throwOnBindFailure: false);
}
catch (ArgumentException)
{
// "Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type."
// https://github.com/Microsoft/BotBuilder/issues/634
// https://github.com/Microsoft/BotBuilder/issues/435
}
// fall back for compatibility
if (intentHandler == null)
{
try
{
var handler = (IntentHandler)Delegate.CreateDelegate(typeof(IntentHandler), dialog, method, throwOnBindFailure: false);
if (handler != null)
{
// thunk from new to old delegate type
intentHandler = (context, message, result) => handler(context, result);
}
}
catch (ArgumentException)
{
// "Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type."
// https://github.com/Microsoft/BotBuilder/issues/634
// https://github.com/Microsoft/BotBuilder/issues/435
}
}
if (intentHandler != null)
{
var intentNames = intents.Select(i => i.IntentName).DefaultIfEmpty(method.Name);
foreach (var intentName in intentNames)
{
var key = string.IsNullOrWhiteSpace(intentName) ? string.Empty : intentName;
yield return new KeyValuePair<string, IntentActivityHandler>(intentName, intentHandler);
}
}
else
{
if (intents.Length > 0)
{
throw new InvalidIntentHandlerException(string.Join(";", intents.Select(i => i.IntentName)), method);
}
}
}
}
19
Source : InheritedAttributes.cs
with MIT License
from CXuesong
with MIT License
from CXuesong
private static IReadOnlyList<Attribute> ForHelper(MethodInfo method)
{
var declaring = method.DeclaringType;
var interfaces = declaring.GetInterfaces();
var methods =
from i in interfaces
let map = declaring.GetInterfaceMap(i)
let index = Array.IndexOf(map.TargetMethods, method)
where index >= 0
let source = map.InterfaceMethods[index]
select source;
Func<MethodInfo, IEnumerable<Attribute>> ExpandAttributes = m =>
{
var ma = m.GetCustomAttributes<Attribute>(inherit: true);
var ta = m.DeclaringType.GetCustomAttributes<Attribute>(inherit: true);
return ma.Concat(ta);
};
return ExpandAttributes(method).Concat(methods.SelectMany(m => ExpandAttributes(m))).ToArray();
}
19
Source : NodeDataCache.cs
with Apache License 2.0
from CyanCode
with Apache License 2.0
from CyanCode
private static bool IsDynamicListPort(NodePort port) {
// Ports flagged as "dynamicPortList = true" end up having a "backing port" and a name with an index, but we have
// no guarantee that a dynamic port called "output 0" is an element in a list backed by a static "output" port.
// Thus, we need to check for attributes... (but at least we don't need to look at all fields this time)
string[] fieldNameParts = port.fieldName.Split(' ');
if (fieldNameParts.Length != 2) return false;
FieldInfo backingPortInfo = port.node.GetType().GetField(fieldNameParts[0]);
if (backingPortInfo == null) return false;
object[] attribs = backingPortInfo.GetCustomAttributes(true);
return attribs.Any(x => {
Node.InputAttribute inputAttribute = x as Node.InputAttribute;
Node.OutputAttribute outputAttribute = x as Node.OutputAttribute;
return inputAttribute != null && inputAttribute.dynamicPortList ||
outputAttribute != null && outputAttribute.dynamicPortList;
});
}
19
Source : NodeDataCache.cs
with Apache License 2.0
from CyanCode
with Apache License 2.0
from CyanCode
private static void CachePorts(System.Type nodeType) {
List<System.Reflection.FieldInfo> fieldInfo = GetNodeFields(nodeType);
for (int i = 0; i < fieldInfo.Count; i++) {
//Get InputAttribute and OutputAttribute
object[] attribs = fieldInfo[i].GetCustomAttributes(true);
Node.InputAttribute inputAttrib = attribs.FirstOrDefault(x => x is Node.InputAttribute) as Node.InputAttribute;
Node.OutputAttribute outputAttrib = attribs.FirstOrDefault(x => x is Node.OutputAttribute) as Node.OutputAttribute;
UnityEngine.Serialization.FormerlySerializedAsAttribute formerlySerializedAsAttribute = attribs.FirstOrDefault(x => x is UnityEngine.Serialization.FormerlySerializedAsAttribute) as UnityEngine.Serialization.FormerlySerializedAsAttribute;
if (inputAttrib == null && outputAttrib == null) continue;
if (inputAttrib != null && outputAttrib != null) Debug.LogError("Field " + fieldInfo[i].Name + " of type " + nodeType.FullName + " cannot be both input and output.");
else {
if (!portDataCache.ContainsKey(nodeType)) portDataCache.Add(nodeType, new List<NodePort>());
portDataCache[nodeType].Add(new NodePort(fieldInfo[i]));
}
if(formerlySerializedAsAttribute != null) {
if (formerlySerializedAsCache == null) formerlySerializedAsCache = new Dictionary<System.Type, Dictionary<string, string>>();
if (!formerlySerializedAsCache.ContainsKey(nodeType)) formerlySerializedAsCache.Add(nodeType, new Dictionary<string, string>());
if (formerlySerializedAsCache[nodeType].ContainsKey(formerlySerializedAsAttribute.oldName)) Debug.LogError("Another FormerlySerializedAs with value '" + formerlySerializedAsAttribute.oldName + "' already exist on this node.");
else formerlySerializedAsCache[nodeType].Add(formerlySerializedAsAttribute.oldName, fieldInfo[i].Name);
}
}
}
19
Source : EnumHelper.cs
with MIT License
from cyclonefreeze
with MIT License
from cyclonefreeze
internal static TAttribute GetAttribute<TAttribute>(this Enum value)
where TAttribute : Attribute
{
var enumType = value.GetType();
var name = Enum.GetName(enumType, value);
return enumType.GetField(name).GetCustomAttributes(false).OfType<TAttribute>().SingleOrDefault();
}
19
Source : ComConnectionPoint.cs
with MIT License
from dahall
with MIT License
from dahall
private static Type[] GetComInterfaces(object sink) =>
sink?.GetType().GetInterfaces().
Where(i => i.GetCustomAttributes(true).Any(a => a.GetType() == typeof(ComImportAttribute) || a.GetType() == typeof(InterfaceTypeAttribute))).
ToArray();
19
Source : Program.cs
with MIT License
from Daimler
with MIT License
from Daimler
private static List<object> GetAttributes(Type clreplacedType)
{
List<object> result = new List<object>();
object[] attributes = clreplacedType.GetCustomAttributes(true);
if (attributes != null || attributes.Length > 0)
result.AddRange(attributes.ToList());
var methods = clreplacedType.GetMethods();
foreach (var method in methods)
{
var methodAttributes = method.GetCustomAttributes(true);
if (methodAttributes != null && methodAttributes.Length > 0)
result.AddRange(methodAttributes.ToList());
}
return result;
}
19
Source : DictionaryPropertyDrawer.cs
with MIT License
from daniellochner
with MIT License
from daniellochner
private bool IsUnitySerialized(FieldInfo fieldInfo)
{
object[] customAttributes = fieldInfo.GetCustomAttributes(true);
if (customAttributes.Any(x => x is System.NonSerializedAttribute))
{
return false;
}
if (fieldInfo.IsPrivate && !customAttributes.Any(x => x is SerializeField))
{
return false;
}
return IsUnitySerialized(fieldInfo.FieldType);
}
19
Source : EntityHelper.cs
with MIT License
from daryllabar
with MIT License
from daryllabar
public static string GetEnreplacedyLogicalName(Type type)
{
if (type.IsGenericParameter && type.BaseType != null)
{
// Handle SomeType<TEnreplacedy> where TEnreplacedy : Enreplacedy
return GetEnreplacedyLogicalName(type.BaseType);
}
var att = type.GetCustomAttributes<Microsoft.Xrm.Sdk.Client.EnreplacedyLogicalNameAttribute>(true).FirstOrDefault();
if (att != null)
{
return att.LogicalName;
}
var field = type.GetField("EnreplacedyLogicalName");
if (field != null)
{
return (string) field.GetValue(null);
}
if (type == typeof(Enreplacedy))
{
return "enreplacedy";
}
throw new Exception("Type " + type.FullName + " does not contain an EnreplacedyLogicalName Field");
}
19
Source : ModelDefBuilder.cs
with MIT License
from DataObjects-NET
with MIT License
from DataObjects-NET
public TypeDef ProcessType(Type type)
{
var modelDef = context.ModelDef;
var typeDef = modelDef.Types.TryGetValue(type);
if (typeDef != null) {
return typeDef;
}
using (BuildLog.InfoRegion(Strings.LogDefiningX, type.GetFullName())) {
typeDef = DefineType(type);
if (modelDef.Types.Contains(typeDef.Name)) {
throw new DomainBuilderException(string.Format(Strings.ExTypeWithNameXIsAlreadyDefined, typeDef.Name));
}
HierarchyDef hierarchyDef = null;
if (typeDef.IsEnreplacedy) {
// HierarchyRootAttribute is required for hierarchy root
var hra = type.GetAttribute<HierarchyRootAttribute>(AttributeSearchOptions.Default);
if (hra != null) {
hierarchyDef = DefineHierarchy(typeDef, hra);
}
}
ProcessProperties(typeDef, hierarchyDef);
if (typeDef.IsEnreplacedy || typeDef.IsInterface) {
ProcessIndexes(typeDef);
}
if (hierarchyDef != null) {
BuildLog.Info(Strings.LogHierarchyX, typeDef.Name);
modelDef.Hierarchies.Add(hierarchyDef);
}
modelDef.Types.Add(typeDef);
ProcessFullTextIndexes(typeDef);
var validators = type.GetCustomAttributes(false).OfType<IObjectValidator>();
foreach (var validator in validators) {
typeDef.Validators.Add(validator);
}
return typeDef;
}
}
19
Source : ModelDefBuilder.cs
with MIT License
from DataObjects-NET
with MIT License
from DataObjects-NET
public FieldDef DefineField(PropertyInfo propertyInfo, IReadOnlyList<FieldAttribute> reversedFieldAttributes)
{
// Persistent indexers are not supported
var indexParameters = propertyInfo.GetIndexParameters();
if (indexParameters.Length > 0) {
throw new DomainBuilderException(Strings.ExIndexedPropertiesAreNotSupported);
}
var fieldDef = new FieldDef(propertyInfo, context.Validator);
fieldDef.Name = context.NameBuilder.BuildFieldName(fieldDef);
if (reversedFieldAttributes.Count > 0) {
for (int i = reversedFieldAttributes.Count; i-- > 0;) {
attributeProcessor.Process(fieldDef, reversedFieldAttributes[i]);
}
// replacedociation
var reversedreplacedociationAttributes = GetReversedFieldAttributes<replacedociationAttribute>(propertyInfo);
for (int i = reversedreplacedociationAttributes.Count; i-- > 0;) {
attributeProcessor.Process(fieldDef, reversedreplacedociationAttributes[i]);
}
// Mapping name
var reversedMappingAttributes = GetReversedFieldAttributes<FieldMappingAttribute>(propertyInfo);
for (int i = reversedMappingAttributes.Count; i-- > 0;) {
attributeProcessor.Process(fieldDef, reversedMappingAttributes[i]);
}
// Type discriminator
var typeDiscriminatorAttribute =
propertyInfo.GetAttribute<TypeDiscriminatorAttribute>(AttributeSearchOptions.InheritAll);
if (typeDiscriminatorAttribute != null) {
attributeProcessor.Process(fieldDef, typeDiscriminatorAttribute);
}
// Version
var versionAttribute = propertyInfo.GetAttribute<VersionAttribute>(AttributeSearchOptions.InheritAll);
if (versionAttribute != null) {
attributeProcessor.Process(fieldDef, versionAttribute);
}
// Validators
var validators = propertyInfo.GetCustomAttributes(false).OfType<IPropertyValidator>();
foreach (var validator in validators) {
fieldDef.Validators.Add(validator);
}
}
return fieldDef;
}
19
Source : XTabsAuthorizeRouteView.cs
with MIT License
from David-Moreira
with MIT License
from David-Moreira
ComputeAuthorizeDataForType(Type type)
{
// Allow Anonymous skips all authorization
var allAttributes = type.GetCustomAttributes(inherit: true);
List<IAuthorizeData>? authorizeDatas = null;
for (var i = 0; i < allAttributes.Length; i++)
{
if (allAttributes[i] is IAllowAnonymous)
{
return null;
}
if (allAttributes[i] is IAuthorizeData authorizeData)
{
authorizeDatas ??= new();
authorizeDatas.Add(authorizeData);
}
}
return authorizeDatas?.ToArray();
}
19
Source : FrmWsusADComparator.cs
with MIT License
from DCourtel
with MIT License
from DCourtel
private void SetColumnsWidth()
{
foreach (System.Reflection.PropertyInfo propertyInfo in WPP.Management.WppComputer.GetDataGridViewProperties())
{
DataGridViewColumn column = this.adgvComputer.Columns[this._localization.GetLocalizedString(propertyInfo.Name)];
WPP.Management.DataGridViewDataAttribute attribute = (WPP.Management.DataGridViewDataAttribute)propertyInfo.GetCustomAttributes(false)[0];
column.Visible = attribute.Visible && attribute.DisplayedByDefault;
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
column.FillWeight = attribute.Width;
column.DataPropertyName = column.Name;
column.Tag = attribute;
}
}
19
Source : ReflectionHelper.cs
with GNU General Public License v3.0
from deathkiller
with GNU General Public License v3.0
from deathkiller
public static IEnumerable<T> GetAttributesCached<T>(this MemberInfo member) where T : Attribute
{
Attribute[] result;
if (!customMemberAttribCache.TryGetValue(member, out result))
{
result = member.GetCustomAttributes(true).OfType<Attribute>().ToArray();
// If it's a Type, also check implemented interfaces for (EditorHint) attributes
if (member is TypeInfo)
{
/*TypeInfo typeInfo = member as TypeInfo;
IEnumerable<Attribute> query = result;
Type[] interfaces = typeInfo.ImplementedInterfaces.ToArray();
if (interfaces.Length > 0)
{
bool addedAny = false;
foreach (Type interfaceType in interfaces)
{
TypeInfo interfaceTypeInfo = interfaceType.GetTypeInfo();
IEnumerable<Attribute> subQuery = GetAttributesCached<Editor.EditorHintAttribute>(interfaceTypeInfo);
if (subQuery.Any())
{
query = query.Concat(subQuery);
addedAny = true;
}
}
if (addedAny)
{
result = query.Distinct().ToArray();
}
}*/
}
// If it's a member, check if it is an interface implementation and add their (EditorHint) attributes as well
else
{
/*TypeInfo declaringTypeInfo = member.DeclaringType == null ? null : member.DeclaringType.GetTypeInfo();
if (declaringTypeInfo != null && !declaringTypeInfo.IsInterface)
{
IEnumerable<Attribute> query = result;
Type[] interfaces = declaringTypeInfo.ImplementedInterfaces.ToArray();
if (interfaces.Length > 0)
{
bool addedAny = false;
foreach (Type interfaceType in interfaces)
{
TypeInfo interfaceTypeInfo = interfaceType.GetTypeInfo();
foreach (MemberInfo interfaceMemberInfo in interfaceTypeInfo.DeclaredMembersDeep())
{
if (interfaceMemberInfo.Name != member.Name) continue;
IEnumerable<Attribute> subQuery = GetAttributesCached<Editor.EditorHintAttribute>(interfaceMemberInfo);
if (subQuery.Any())
{
query = query.Concat(subQuery);
addedAny = true;
}
}
}
if (addedAny)
{
result = query.Distinct().ToArray();
}
}
}*/
}
// Mind the result for later. Don't do this twice.
customMemberAttribCache[member] = result;
}
if (typeof(T) == typeof(Attribute))
return result as IEnumerable<T>;
else
return result.OfType<T>();
}
19
Source : STNode.cs
with MIT License
from DebugST
with MIT License
from DebugST
internal Dictionary<string, byte[]> OnSaveNode() {
Dictionary<string, byte[]> dic = new Dictionary<string, byte[]>();
dic.Add("Guid", this._Guid.ToByteArray());
dic.Add("Left", BitConverter.GetBytes(this._Left));
dic.Add("Top", BitConverter.GetBytes(this._Top));
dic.Add("Width", BitConverter.GetBytes(this._Width));
dic.Add("Height", BitConverter.GetBytes(this._Height));
dic.Add("AutoSize", new byte[] { (byte)(this._AutoSize ? 1 : 0) });
if (this._Mark != null) dic.Add("Mark", Encoding.UTF8.GetBytes(this._Mark));
dic.Add("LockOption", new byte[] { (byte)(this._LockLocation ? 1 : 0) });
dic.Add("LockLocation", new byte[] { (byte)(this._LockLocation ? 1 : 0) });
Type t = this.GetType();
foreach (var p in t.GetProperties()) {
var attrs = p.GetCustomAttributes(true);
foreach (var a in attrs) {
if (!(a is STNodePropertyAttribute)) continue;
var attr = a as STNodePropertyAttribute;
object obj = Activator.CreateInstance(attr.DescriptorType);
if (!(obj is STNodePropertyDescriptor))
throw new InvalidOperationException("[STNodePropertyAttribute.Type]参数值必须为[STNodePropertyDescriptor]或者其子类的类型");
var desc = (STNodePropertyDescriptor)Activator.CreateInstance(attr.DescriptorType);
desc.Node = this;
desc.PropertyInfo = p;
byte[] byData = desc.GetBytesFromValue();
if (byData == null) continue;
dic.Add(p.Name, byData);
}
}
this.OnSaveNode(dic);
return dic;
}
19
Source : STNodePropertyGrid.cs
with MIT License
from DebugST
with MIT License
from DebugST
private List<STNodePropertyDescriptor> GetProperties(STNode node) {
List<STNodePropertyDescriptor> lst = new List<STNodePropertyDescriptor>();
if (node == null) return lst;
Type t = node.GetType();
foreach (var p in t.GetProperties()) {
var attrs = p.GetCustomAttributes(true);
foreach (var a in attrs) {
if (!(a is STNodePropertyAttribute)) continue;
var attr = a as STNodePropertyAttribute;
object obj = Activator.CreateInstance(attr.DescriptorType);
if (!(obj is STNodePropertyDescriptor))
throw new ArgumentException("[STNodePropertyAttribute.DescriptorType]参数值必须为[STNodePropertyDescriptor]或者其子类的类型");
var desc = (STNodePropertyDescriptor)Activator.CreateInstance(attr.DescriptorType);
desc.Node = node;
desc.Name = attr.Name;
desc.Description = attr.Description;
desc.PropertyInfo = p;
desc.Control = this;
lst.Add(desc);
}
}
return lst;
}
19
Source : STNodePropertyGrid.cs
with MIT License
from DebugST
with MIT License
from DebugST
private STNodeAttribute GetNodeAttribute(STNode node) {
if (node == null) return null;
Type t = node.GetType();
foreach (var v in t.GetCustomAttributes(true)) {
if (!(v is STNodeAttribute)) continue;
return (STNodeAttribute)v;
}
return null;
}
19
Source : STNode.cs
with MIT License
from DebugST
with MIT License
from DebugST
protected internal virtual void OnLoadNode(Dictionary<string, byte[]> dic) {
if (dic.ContainsKey("AutoSize")) this._AutoSize = dic["AutoSize"][0] == 1;
if (dic.ContainsKey("LockOption")) this._LockOption = dic["LockOption"][0] == 1;
if (dic.ContainsKey("LockLocation")) this._LockLocation = dic["LockLocation"][0] == 1;
if (dic.ContainsKey("Guid")) this._Guid = new Guid(dic["Guid"]);
if (dic.ContainsKey("Left")) this._Left = BitConverter.ToInt32(dic["Left"], 0);
if (dic.ContainsKey("Top")) this._Top = BitConverter.ToInt32(dic["Top"], 0);
if (dic.ContainsKey("Width") && !this._AutoSize) this._Width = BitConverter.ToInt32(dic["Width"], 0);
if (dic.ContainsKey("Height") && !this._AutoSize) this._Height = BitConverter.ToInt32(dic["Height"], 0);
if (dic.ContainsKey("Mark")) this.Mark = Encoding.UTF8.GetString(dic["Mark"]);
Type t = this.GetType();
foreach (var p in t.GetProperties()) {
var attrs = p.GetCustomAttributes(true);
foreach (var a in attrs) {
if (!(a is STNodePropertyAttribute)) continue;
var attr = a as STNodePropertyAttribute;
object obj = Activator.CreateInstance(attr.DescriptorType);
if (!(obj is STNodePropertyDescriptor))
throw new InvalidOperationException("[STNodePropertyAttribute.Type]参数值必须为[STNodePropertyDescriptor]或者其子类的类型");
var desc = (STNodePropertyDescriptor)Activator.CreateInstance(attr.DescriptorType);
desc.Node = this;
desc.PropertyInfo = p;
try {
if (dic.ContainsKey(p.Name)) desc.SetValue(dic[p.Name]);
} catch (Exception ex) {
string strErr = "属性[" + this.replacedle + "." + p.Name + "]的值无法被还原 可通过重写[STNodePropertyAttribute.GetBytesFromValue(),STNodePropertyAttribute.GetValueFromBytes(byte[])]确保保存和加载时候的二进制数据正确";
Exception e = ex;
while (e != null) {
strErr += "\r\n----\r\n[" + e.GetType().Name + "] -> " + e.Message;
e = e.InnerException;
}
throw new InvalidOperationException(strErr, ex);
}
}
}
}
19
Source : STNodeTreeView.cs
with MIT License
from DebugST
with MIT License
from DebugST
private STNodeAttribute GetNodeAttribute(Type stNodeType) {
if (stNodeType == null) return null;
foreach (var v in stNodeType.GetCustomAttributes(true)) {
if (!(v is STNodeAttribute)) continue;
return (STNodeAttribute)v;
}
return null;
}
19
Source : SystemManager.cs
with MIT License
from deccer
with MIT License
from deccer
private void CreatePool(Type type, IEnumerable<Attribute> attributes)
{
ComponentPoolAttribute propertyComponentPool = null;
foreach (var artemisComponentPool in attributes.OfType<ComponentPoolAttribute>())
{
propertyComponentPool = artemisComponentPool;
}
var methods = type.GetMethods();
var methodInfos = from methodInfo in methods
let methodAttributes = methodInfo.GetCustomAttributes(false)
from attribute in methodAttributes.OfType<ComponentCreateAttribute>()
select methodInfo;
Func<Type, ComponentPoolable> create = null;
foreach (var methodInfo in methodInfos)
{
create = (Func<Type, ComponentPoolable>)Delegate.CreateDelegate(typeof(Func<Type, ComponentPoolable>), methodInfo);
}
if (create == null)
{
create = CreateInstance;
}
IComponentPool<ComponentPoolable> pool;
if (propertyComponentPool == null)
{
throw new NullReferenceException("propertyComponentPool is null.");
}
if (!propertyComponentPool.IsSupportMulreplacedhread)
{
pool = new ComponentPool<ComponentPoolable>(propertyComponentPool.InitialSize, propertyComponentPool.ResizeSize, propertyComponentPool.IsResizable, create, type);
}
else
{
pool = new ComponentPoolMulreplacedhread<ComponentPoolable>(propertyComponentPool.InitialSize, propertyComponentPool.ResizeSize, propertyComponentPool.IsResizable, create, type);
}
_enreplacedyWorld.SetPool(type, pool);
}
19
Source : AttributesProcessor.cs
with MIT License
from deccer
with MIT License
from deccer
public static IDictionary<Type, List<Attribute>> Process(List<Type> supportedAttributes, IEnumerable<replacedembly> replacedembliesToScan) // Do not double overload "= null)"
{
IDictionary<Type, List<Attribute>> attributeTypes = new Dictionary<Type, List<Attribute>>();
if (replacedembliesToScan != null)
{
foreach (var item in replacedembliesToScan)
{
IEnumerable<Type> types = item.GetTypes();
foreach (var type in types)
{
var attributes = type.GetCustomAttributes(false);
foreach (var attribute in attributes)
{
if (supportedAttributes.Contains(attribute.GetType()))
{
if (!attributeTypes.ContainsKey(type))
{
attributeTypes[type] = new List<Attribute>();
}
attributeTypes[type].Add((Attribute)attribute);
}
}
}
}
}
return attributeTypes;
}
19
Source : FieldNode.cs
with GNU Affero General Public License v3.0
from DelvUI
with GNU Affero General Public License v3.0
from DelvUI
protected static ConfigAttribute? GetConfigAttribute(FieldInfo field)
{
return field.GetCustomAttributes(true).Where(a => a is ConfigAttribute).FirstOrDefault() as ConfigAttribute;
}
See More Examples