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 : ServiceBuilder.cs
with MIT License
from 1100100
with MIT License
from 1100100
public async Task StartAsync(CancellationToken cancellationToken)
{
UraganoSettings.ClientGlobalInterceptors.Reverse();
UraganoSettings.ServerGlobalInterceptors.Reverse();
var enableClient = ServiceProvider.GetService<ILoadBalancing>() != null;
var enableServer = UraganoSettings.ServerSettings != null;
var types = ReflectHelper.GetDependencyTypes();
var services = types.Where(t => t.IsInterface && typeof(IService).IsreplacedignableFrom(t)).Select(@interface => new
{
Interface = @interface,
Implementation = types.FirstOrDefault(p => p.IsClreplaced && p.IsPublic && !p.IsAbstract && !p.Name.EndsWith("_____UraganoClientProxy") && @interface.IsreplacedignableFrom(p))
}).ToList();
foreach (var service in services)
{
var imp = service.Implementation;
var routeAttr = service.Interface.GetCustomAttribute<ServiceRouteAttribute>();
var routePrefix = routeAttr == null ? $"{service.Interface.Namespace}/{service.Interface.Name}" : routeAttr.Route;
var interfaceMethods = service.Interface.GetMethods();
List<MethodInfo> implementationMethods = null;
if (enableServer && imp != null)
implementationMethods = imp.GetMethods().ToList();
var disableClientIntercept = service.Interface.GetCustomAttribute<NonInterceptAttribute>(true) != null;
var clientClreplacedInterceptors = new List<Type>();
if (!disableClientIntercept)
clientClreplacedInterceptors = service.Interface.GetCustomAttributes(true).Where(p => p is IInterceptor)
.Select(p => p.GetType()).ToList();
var serverClreplacedInterceptors = new List<Type>();
var disableServerIntercept = false;
if (enableServer && imp != null)
{
disableServerIntercept = imp.GetCustomAttribute<NonInterceptAttribute>(true) != null;
if (!disableServerIntercept)
serverClreplacedInterceptors = imp.GetCustomAttributes(true).Where(p => p is IInterceptor)
.Select(p => p.GetType()).ToList();
}
foreach (var interfaceMethod in interfaceMethods)
{
MethodInfo serverMethod = null;
var idAttr = interfaceMethod.GetCustomAttribute<ServiceRouteAttribute>();
var route = idAttr == null ? $"{routePrefix}/{interfaceMethod.Name}" : $"{routePrefix}/{idAttr.Route}";
var clientInterceptors = new List<Type>();
if (enableClient && !disableClientIntercept && interfaceMethod.GetCustomAttribute<NonInterceptAttribute>(true) == null)
{
clientInterceptors.AddRange(UraganoSettings.ClientGlobalInterceptors);
clientInterceptors.AddRange(clientClreplacedInterceptors);
clientInterceptors.AddRange(interfaceMethod.GetCustomAttributes(true)
.Where(p => p is IInterceptor).Select(p => p.GetType()).ToList());
clientInterceptors.Reverse();
}
var serverInterceptors = new List<Type>();
if (enableServer && imp != null)
{
serverMethod = implementationMethods.First(p => IsImplementationMethod(interfaceMethod, p));
if (!disableServerIntercept && serverMethod?.GetCustomAttribute<NonInterceptAttribute>(true) == null)
{
serverInterceptors.AddRange(UraganoSettings.ServerGlobalInterceptors);
serverInterceptors.AddRange(serverClreplacedInterceptors.ToList());
if (serverMethod != null)
serverInterceptors.AddRange(serverMethod.GetCustomAttributes(true)
.Where(p => p is IInterceptor).Select(p => p.GetType()).ToList());
serverInterceptors.Reverse();
}
}
ServiceFactory.Create(route, serverMethod, interfaceMethod, serverInterceptors, clientInterceptors);
}
}
await Task.CompletedTask;
}
19
Source : DynamicProxy.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static DynamicProxyMeta CreateDynamicProxyMeta(Type type, bool isCompile, bool isThrow)
{
if (type == null) return null;
var typeCSharpName = type.DisplayCsharp();
if (type.IsNotPublic)
{
if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 需要使用 public 标记");
return null;
}
var matchedMemberInfos = new List<MemberInfo>();
var matchedAttributes = new List<DynamicProxyAttribute>();
var matchedAttributesFromServices = new List<FieldInfo[]>();
var clreplacedName = $"AopProxyClreplaced___{Guid.NewGuid().ToString("N")}";
var methodOverrideSb = new StringBuilder();
var sb = methodOverrideSb;
#region Common Code
Func<Type, DynamicProxyInjectorType, bool, int, string, string> getMatchedAttributesCode = (returnType, injectorType, isAsync, attrsIndex, proxyMethodName) =>
{
var sbt = new StringBuilder();
for (var a = attrsIndex; a < matchedAttributes.Count; a++)
{
sbt.Append($@"{(proxyMethodName == "Before" ? $@"
var __DP_ARG___attribute{a} = __DP_Meta.{nameof(DynamicProxyMeta.CreateDynamicProxyAttribute)}({a});
__DP_ARG___attribute{a}_FromServicesCopyTo(__DP_ARG___attribute{a});" : "")}
var __DP_ARG___{proxyMethodName}{a} = new {(proxyMethodName == "Before" ? _beforeAgumentsName : _afterAgumentsName)}(this, {_injectorTypeName}.{injectorType.ToString()}, __DP_Meta.MatchedMemberInfos[{a}], __DP_ARG___parameters, {(proxyMethodName == "Before" ? "null" : "__DP_ARG___return_value, __DP_ARG___exception")});
{(isAsync ? "await " : "")}__DP_ARG___attribute{a}.{proxyMethodName}(__DP_ARG___{proxyMethodName}{a});
{(proxyMethodName == "Before" ?
$@"if (__DP_ARG___is_return == false)
{{
__DP_ARG___is_return = __DP_ARG___{proxyMethodName}{a}.Returned;{(returnType != typeof(void) ? $@"
if (__DP_ARG___is_return) __DP_ARG___return_value = __DP_ARG___{proxyMethodName}{a}.ReturnValue;" : "")}
}}" :
$"if (__DP_ARG___{proxyMethodName}{a}.Exception != null && __DP_ARG___{proxyMethodName}{a}.ExceptionHandled == false) throw __DP_ARG___{proxyMethodName}{a}.Exception;")}");
}
return sbt.ToString();
};
Func<Type, DynamicProxyInjectorType, bool, string, string> getMatchedAttributesCodeReturn = (returnType, injectorType, isAsync, basePropertyValueTpl) =>
{
var sbt = new StringBuilder();
var taskType = returnType.ReturnTypeWithoutTask();
sbt.Append($@"
{(returnType == typeof(void) ? "return;" : (isAsync == false && returnType.IsTask() ?
(taskType.IsValueType || taskType.IsGenericParameter ?
$"return __DP_ARG___return_value == null ? null : (__DP_ARG___return_value.GetType() == typeof({taskType.DisplayCsharp()}) ? System.Threading.Tasks.Task.FromResult(({taskType.DisplayCsharp()})__DP_ARG___return_value) : ({returnType.DisplayCsharp()})__DP_ARG___return_value);" :
$"return __DP_ARG___return_value == null ? null : (__DP_ARG___return_value.GetType() == typeof({taskType.DisplayCsharp()}) ? System.Threading.Tasks.Task.FromResult(__DP_ARG___return_value as {taskType.DisplayCsharp()}) : ({returnType.DisplayCsharp()})__DP_ARG___return_value);"
) :
(returnType.IsValueType || returnType.IsGenericParameter ? $"return ({returnType.DisplayCsharp()})__DP_ARG___return_value;" : $"return __DP_ARG___return_value as {returnType.DisplayCsharp()};")))}");
return sbt.ToString();
};
Func<string, Type, string> getMatchedAttributesCodeAuditParameter = (methodParameterName, methodParameterType) =>
{
return $@"
if (!object.ReferenceEquals({methodParameterName}, __DP_ARG___parameters[""{methodParameterName}""])) {methodParameterName} = {(methodParameterType.IsValueType ? $@"({methodParameterType.DisplayCsharp()})__DP_ARG___parameters[""{methodParameterName}""]" : $@"__DP_ARG___parameters[""{methodParameterName}""] as {methodParameterType.DisplayCsharp()}")};";
};
#endregion
#region Methods
var ctors = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.IsStatic == false).ToArray();
var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
foreach (var method in methods)
{
if (method.Name.StartsWith("get_") || method.Name.StartsWith("set_"))
if (type.GetProperty(method.Name.Substring(4), BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null) continue;
var attrs = method.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
if (attrs.Any() == false) continue;
var attrsIndex = matchedAttributes.Count;
matchedMemberInfos.AddRange(attrs.Select(a => method));
matchedAttributes.AddRange(attrs);
#if net50 || ns21 || ns20
matchedAttributesFromServices.AddRange(attrs.Select(af => af.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
.Where(gf => gf.GetCustomAttribute(typeof(DynamicProxyFromServicesAttribute)) != null).ToArray()));
#else
matchedAttributesFromServices.AddRange(attrs.Select(af => new FieldInfo[0]));
#endif
if (method.IsVirtual == false || method.IsFinal)
{
if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 方法 {method.Name} 需要使用 virtual 标记");
continue;
}
#if net40
var returnType = method.ReturnType;
var methodIsAsync = false;
#else
var returnType = method.ReturnType.ReturnTypeWithoutTask();
var methodIsAsync = method.ReturnType.IsTask();
//if (attrs.Where(a => a.GetType().GetMethod("BeforeAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null).Any() ||
// attrs.Where(a => a.GetType().GetMethod("AfterAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null).Any())
//{
//}
#endif
var baseInvoke = type.IsInterface == false ? $@"
try
{{
if (__DP_ARG___is_return == false)
{{{string.Join("", method.GetParameters().Select(a => getMatchedAttributesCodeAuditParameter(a.Name, a.ParameterType)))}
{(returnType != typeof(void) ? "__DP_ARG___return_value = " : "")}{(methodIsAsync ? "await " : "")}base.{method.Name}({(string.Join(", ", method.GetParameters().Select(a => a.Name)))});
}}
}}
catch (Exception __DP_ARG___ex)
{{
__DP_ARG___exception = __DP_ARG___ex;
}}" : "";
sb.Append($@"
{(methodIsAsync ? "async " : "")}{method.DisplayCsharp(true)}
{{
Exception __DP_ARG___exception = null;
var __DP_ARG___is_return = false;
object __DP_ARG___return_value = null;
var __DP_ARG___parameters = new Dictionary<string, object>();{string.Join("\r\n ", method.GetParameters().Select(a => $"__DP_ARG___parameters.Add(\"{a.Name}\", {a.Name});"))}
{getMatchedAttributesCode(returnType, DynamicProxyInjectorType.Method, methodIsAsync, attrsIndex, "Before")}{baseInvoke}
{getMatchedAttributesCode(returnType, DynamicProxyInjectorType.Method, methodIsAsync, attrsIndex, "After")}
{getMatchedAttributesCodeReturn(returnType, DynamicProxyInjectorType.Method, methodIsAsync, null)}
}}");
}
#endregion
var propertyOverrideSb = new StringBuilder();
sb = propertyOverrideSb;
#region Property
var props = type.IsInterface == false ? type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) : new PropertyInfo[0];
foreach (var prop2 in props)
{
var getMethod = prop2.GetGetMethod(false);
var setMethod = prop2.GetSetMethod(false);
if (getMethod?.IsFinal == true || setMethod?.IsFinal == true || (getMethod?.IsVirtual == false && setMethod?.IsVirtual == false))
{
if (getMethod?.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).Any() == true ||
setMethod?.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).Any() == true)
{
if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 属性 {prop2.Name} 需要使用 virtual 标记");
continue;
}
}
var attrs = prop2.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
var prop2AttributeAny = attrs.Any();
var getMethodAttributeAny = prop2AttributeAny;
var setMethodAttributeAny = prop2AttributeAny;
if (attrs.Any() == false && getMethod?.IsVirtual == true)
{
attrs = getMethod.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
getMethodAttributeAny = attrs.Any();
}
if (attrs.Any() == false && setMethod?.IsVirtual == true)
{
attrs = setMethod.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
setMethodAttributeAny = attrs.Any();
}
if (attrs.Any() == false) continue;
var attrsIndex = matchedAttributes.Count;
matchedMemberInfos.AddRange(attrs.Select(a => prop2));
matchedAttributes.AddRange(attrs);
#if net50 || ns21 || ns20
matchedAttributesFromServices.AddRange(attrs.Select(af => af.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
.Where(gf => gf.GetCustomAttribute(typeof(DynamicProxyFromServicesAttribute)) != null).ToArray()));
#else
matchedAttributesFromServices.AddRange(attrs.Select(af => new FieldInfo[0]));
#endif
var returnTypeCSharpName = prop2.PropertyType.DisplayCsharp();
var propModification = (getMethod?.IsPublic == true || setMethod?.IsPublic == true ? "public " : (getMethod?.Isreplacedembly == true || setMethod?.Isreplacedembly == true ? "internal " : (getMethod?.IsFamily == true || setMethod?.IsFamily == true ? "protected " : (getMethod?.IsPrivate == true || setMethod?.IsPrivate == true ? "private " : ""))));
var propSetModification = (setMethod?.IsPublic == true ? "public " : (setMethod?.Isreplacedembly == true ? "internal " : (setMethod?.IsFamily == true ? "protected " : (setMethod?.IsPrivate == true ? "private " : ""))));
var propGetModification = (getMethod?.IsPublic == true ? "public " : (getMethod?.Isreplacedembly == true ? "internal " : (getMethod?.IsFamily == true ? "protected " : (getMethod?.IsPrivate == true ? "private " : ""))));
if (propSetModification == propModification) propSetModification = "";
if (propGetModification == propModification) propGetModification = "";
//if (getMethod.IsAbstract) sb.Append("abstract ");
sb.Append($@"
{propModification}{(getMethod?.IsStatic == true ? "static " : "")}{(getMethod?.IsVirtual == true ? "override " : "")}{returnTypeCSharpName} {prop2.Name}
{{");
if (getMethod != null)
{
if (getMethodAttributeAny == false) sb.Append($@"
{propGetModification} get
{{
return base.{prop2.Name}
}}");
else sb.Append($@"
{propGetModification} get
{{
Exception __DP_ARG___exception = null;
var __DP_ARG___is_return = false;
object __DP_ARG___return_value = null;
var __DP_ARG___parameters = new Dictionary<string, object>();
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertyGet, false, attrsIndex, "Before")}
try
{{
if (__DP_ARG___is_return == false) __DP_ARG___return_value = base.{prop2.Name};
}}
catch (Exception __DP_ARG___ex)
{{
__DP_ARG___exception = __DP_ARG___ex;
}}
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertyGet, false, attrsIndex, "After")}
{getMatchedAttributesCodeReturn(prop2.PropertyType, DynamicProxyInjectorType.Method, false, null)}
}}");
}
if (setMethod != null)
{
if (setMethodAttributeAny == false) sb.Append($@"
{propSetModification} set
{{
base.{prop2.Name} = value;
}}");
else sb.Append($@"
{propSetModification} set
{{
Exception __DP_ARG___exception = null;
var __DP_ARG___is_return = false;
object __DP_ARG___return_value = null;
var __DP_ARG___parameters = new Dictionary<string, object>();
__DP_ARG___parameters.Add(""value"", value);
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertySet, false, attrsIndex, "Before")}
try
{{
if (__DP_ARG___is_return == false)
{{{getMatchedAttributesCodeAuditParameter("value", prop2.PropertyType)}
base.{prop2.Name} = value;
}}
}}
catch (Exception __DP_ARG___ex)
{{
__DP_ARG___exception = __DP_ARG___ex;
}}
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertySet, false, attrsIndex, "After")}
}}");
}
sb.Append($@"
}}");
}
#endregion
string proxyCscode = "";
replacedembly proxyreplacedembly = null;
Type proxyType = null;
if (matchedMemberInfos.Any())
{
#region Constructors
sb = new StringBuilder();
var fromServicesTypes = matchedAttributesFromServices.SelectMany(fs => fs).GroupBy(a => a.FieldType).Select((a, b) => new KeyValuePair<Type, string>(a.Key, $"__DP_ARG___FromServices_{b}")).ToDictionary(a => a.Key, a => a.Value);
sb.Append(string.Join("", fromServicesTypes.Select(serviceType => $@"
private {serviceType.Key.DisplayCsharp()} {serviceType.Value};")));
foreach (var ctor in ctors)
{
var ctorParams = ctor.GetParameters();
sb.Append($@"
{(ctor.IsPrivate ? "private " : "")}{(ctor.IsFamily ? "protected " : "")}{(ctor.Isreplacedembly ? "internal " : "")}{(ctor.IsPublic ? "public " : "")}{clreplacedName}({string.Join(", ", ctorParams.Select(a => $"{a.ParameterType.DisplayCsharp()} {a.Name}"))}{
(ctorParams.Any() && fromServicesTypes.Any() ? ", " : "")}{
string.Join(", ", fromServicesTypes.Select(serviceType => $@"{serviceType.Key.DisplayCsharp()} parameter{serviceType.Value}"))})
: base({(string.Join(", ", ctorParams.Select(a => a.Name)))})
{{{string.Join("", fromServicesTypes.Select(serviceType => $@"
{serviceType.Value} = parameter{serviceType.Value};"))}
}}");
}
for (var a = 0; a < matchedAttributesFromServices.Count; a++)
{
sb.Append($@"
private void __DP_ARG___attribute{a}_FromServicesCopyTo({_idynamicProxyName} attr)
{{{string.Join("", matchedAttributesFromServices[a].Select(fs => $@"
__DP_Meta.{nameof(DynamicProxyMeta.SetDynamicProxyAttributePropertyValue)}({a}, attr, ""{fs.Name}"", {fromServicesTypes[fs.FieldType]});"))}
}}");
}
#endregion
proxyCscode = $@"using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
public clreplaced {clreplacedName} : {typeCSharpName}
{{
private {_metaName} __DP_Meta = {typeof(DynamicProxy).DisplayCsharp()}.{nameof(GetAvailableMeta)}(typeof({typeCSharpName}));
//这里要注释掉,如果重写的基类没有无参构造函数,会报错
//public {clreplacedName}({_metaName} meta)
//{{
// __DP_Meta = meta;
//}}
{sb.ToString()}
{methodOverrideSb.ToString()}
{propertyOverrideSb.ToString()}
}}";
proxyreplacedembly = isCompile == false ? null : CompileCode(proxyCscode);
proxyType = isCompile == false ? null : proxyreplacedembly.GetExportedTypes()/*.DefinedTypes*/.Where(a => a.FullName.EndsWith(clreplacedName)).FirstOrDefault();
}
methodOverrideSb.Clear();
propertyOverrideSb.Clear();
sb.Clear();
return new DynamicProxyMeta(
type, ctors,
matchedMemberInfos.ToArray(), matchedAttributes.ToArray(),
isCompile == false ? proxyCscode : null, clreplacedName, proxyreplacedembly, proxyType);
}
19
Source : InternalExtensions.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static string GetDescription(this Type that)
{
object[] attrs = null;
try
{
attrs = that.GetCustomAttributes(false).ToArray(); //.net core 反射存在版本冲突问题,导致该方法异常
}
catch { }
var dyattr = attrs?.Where(a => {
return ((a as Attribute)?.TypeId as Type)?.Name == "DescriptionAttribute";
}).FirstOrDefault();
if (dyattr != null)
{
var valueProp = dyattr.GetType().GetProperties().Where(a => a.PropertyType == typeof(string)).FirstOrDefault();
var comment = valueProp?.GetValue(dyattr, null)?.ToString();
if (string.IsNullOrEmpty(comment) == false)
return comment;
}
return null;
}
19
Source : AttributeMap.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
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 || COREFX || PROFILE259
Attribute[] all = System.Linq.Enumerable.ToArray(System.Linq.Enumerable.OfType<Attribute>(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 MIT License
from 404Lcc
with MIT License
from 404Lcc
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 || COREFX || PROFILE259
Attribute[] all = System.Linq.Enumerable.ToArray(System.Linq.Enumerable.OfType<Attribute>(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 : AssessmentProperties.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
private static HashSet<TResult> GetValues<T, TResult>()
{
var list = typeof(T).GetFields().Select(x => new
{
att = x.GetCustomAttributes(false).OfType<replacedessmentPropertyAttribute>().FirstOrDefault(),
member = x
}).Where(x => x.att != null && x.member.Name != "value__").Select(x => (TResult)x.member.GetValue(null)).ToList();
return new HashSet<TResult>(list);
}
19
Source : ClientProperties.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
private static HashSet<TResult> GetValues<T, TResult>()
{
var list =typeof(T).GetFields().Select(x => new
{
att = x.GetCustomAttributes(false).OfType<ServerOnlyAttribute>().FirstOrDefault(),
member = x
}).Where(x => x.att == null && x.member.Name != "value__").Select(x => (TResult)x.member.GetValue(null)).ToList();
return new HashSet<TResult>(list);
}
19
Source : EphemeralProperties.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
private static HashSet<T> GetValues<T>()
{
var list = typeof(T).GetFields().Select(x => new
{
att = x.GetCustomAttributes(false).OfType<EphemeralAttribute>().FirstOrDefault(),
member = x
}).Where(x => x.att != null && x.member.Name != "value__").Select(x => (T)x.member.GetValue(null)).ToList();
return new HashSet<T>(list);
}
19
Source : SendOnLoginProperties.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
private static HashSet<TResult> GetValues<T, TResult>()
{
var list = typeof(T).GetFields().Select(x => new
{
att = x.GetCustomAttributes(false).OfType<SendOnLoginAttribute>().FirstOrDefault(),
member = x
}).Where(x => x.att != null && x.member.Name != "value__").Select(x => (TResult)x.member.GetValue(null)).ToList();
return new HashSet<TResult>(list);
}
19
Source : ServerOnlyProperties.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
private static HashSet<TResult> GetValues<T, TResult>()
{
var list = typeof(T).GetFields().Select(x => new
{
att = x.GetCustomAttributes(false).OfType<ServerOnlyAttribute>().FirstOrDefault(),
member = x
}).Where(x => x.att != null && x.member.Name != "value__").Select(x => (TResult)x.member.GetValue(null)).ToList();
return new HashSet<TResult>(list);
}
19
Source : VssConnection.cs
with MIT License
from actions
with MIT License
from actions
private Guid GetServiceIdentifier(
Type requestedType)
{
ResourceAreaAttribute[] attributes = (ResourceAreaAttribute[])requestedType.GetTypeInfo().GetCustomAttributes<ResourceAreaAttribute>(true);
if (attributes.Length > 0)
{
return attributes[0].AreaId;
}
else
{
return Guid.Empty;
}
}
19
Source : VssConnection.cs
with MIT License
from actions
with MIT License
from actions
private Type GetExtensibleType(Type managedType)
{
if (managedType.GetTypeInfo().IsAbstract || managedType.GetTypeInfo().IsInterface)
{
Type extensibleType = null;
// We can add extensible type registration for the client later (app.config? windows registry?). For now it is based solely on the attribute
if (!m_extensibleServiceTypes.TryGetValue(managedType.Name, out extensibleType))
{
VssClientServiceImplementationAttribute[] attributes = (VssClientServiceImplementationAttribute[])managedType.GetTypeInfo().GetCustomAttributes<VssClientServiceImplementationAttribute>(true);
if (attributes.Length > 0)
{
if (attributes[0].Type != null)
{
extensibleType = attributes[0].Type;
m_extensibleServiceTypes[managedType.Name] = extensibleType;
}
else if (!String.IsNullOrEmpty(attributes[0].TypeName))
{
extensibleType = Type.GetType(attributes[0].TypeName);
if (extensibleType != null)
{
m_extensibleServiceTypes[managedType.Name] = extensibleType;
}
else
{
Debug.replacedert(false, "VssConnection: Could not load type from type name: " + attributes[0].TypeName);
}
}
}
}
if (extensibleType == null)
{
throw new ExtensibleServiceTypeNotRegisteredException(managedType);
}
if (!managedType.GetTypeInfo().IsreplacedignableFrom(extensibleType.GetTypeInfo()))
{
throw new ExtensibleServiceTypeNotValidException(managedType, extensibleType);
}
return extensibleType;
}
else
{
return managedType;
}
}
19
Source : TypeExtensions.cs
with MIT License
from adamant
with MIT License
from adamant
public static bool HasCustomAttribute<TAttribute>(this Type type)
{
return type.GetCustomAttributes(true).OfType<TAttribute>().Any();
}
19
Source : ReflectionExtend.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public static T GetAttribute2<T>(this MemberInfo field) where T : Attribute
{
return field.GetCustomAttributes(true).LastOrDefault(p=>p is T) as T;
}
19
Source : UnityContainerAttributeExtensions.cs
with Apache License 2.0
from agoda-com
with Apache License 2.0
from agoda-com
private static IList<string> ScanAndRegister<TAttribute, TLifestyleManager>(bool mockMode, replacedembly[] replacedemblies)
where TAttribute : ContainerRegistrationAttribute
where TLifestyleManager : LifetimeManager, new()
{
// Look for all clreplacedes in the given replacedemblies that are decorated with a ContainerRegistrationAttribute
var registrations = replacedemblies
.SelectMany(replacedembly => replacedembly.GetExportedTypes())
.Where(type => type.IsClreplaced)
.Select(type => new
{
ToType = type,
Attributes = type.GetCustomAttributes<TAttribute>(false)
})
.Where(x => x.Attributes.Any())
.SelectMany(x => x.Attributes.Select(
attr => new RegistrationContext(attr, x.ToType, mockMode, _interceptorWrapper)
))
.ToList();
var errorMsgs = registrations
.Where(reg => !reg.Validation.IsValid)
.Select(reg => reg.Validation.ErrorMessage)
.ToList();
if (errorMsgs.Any())
{
return errorMsgs;
}
foreach (var reg in registrations)
{
try
{
if (reg.FromType != null)
{
RegisterAbstract<TLifestyleManager>(reg, mockMode);
}
else
{
RegisterConcrete<TLifestyleManager>(reg);
}
}
catch (RegistrationFailedException ex)
{
errorMsgs.Add(ex.Message);
}
}
return errorMsgs;
}
19
Source : StartupExtension.cs
with Apache License 2.0
from agoda-com
with Apache License 2.0
from agoda-com
public static IServiceCollection AutoWirereplacedembly<T>(
this IServiceCollection services, replacedembly[] replacedemblies,
ServiceLifetime serviceLifetime,
bool isMockMode,
Action<ContainerRegistrationOption> option = null,
IDictionary<Type, List<KeyTypePair>> keysForTypes = null)
where T : ContainerRegistrationAttribute
{
var containerRegistrationOption = new ContainerRegistrationOption();
option?.Invoke(containerRegistrationOption);
var registrations = replacedemblies
.SelectMany(replacedembly => replacedembly.GetExportedTypes())
.Where(type => type.IsClreplaced)
.Select(type => new
{
ToType = type,
Attributes = type.GetCustomAttributes<T>(false)
})
.Where(x => x.Attributes.Any())
.SelectMany(x => x.Attributes.Select(
attr => new RegistrationContext(attr, x.ToType, isMockMode)
))
.ToList();
if (!Validate(registrations, containerRegistrationOption))
{
throw new RegistrationFailedException("There are validations error!!!");
}
foreach (var reg in registrations)
{
if (reg.Key != null)
{
// keyed instances is recorded here for registration later
AddToKeyedRegistrationList(reg, keysForTypes, serviceLifetime);
continue;
}
var toType = isMockMode && reg.MockType != null
? reg.MockType
: reg.ToType;
var serviceDescriptor = CreateServiceDescriptor(reg, serviceLifetime, toType);
if (reg?.ReplaceServices == true)
{
services.Replace(serviceDescriptor);
}
else
{
services.Add(serviceDescriptor);
}
}
return services;
}
19
Source : AspectInterceptorSelector.cs
with MIT License
from ahmet-cetinkaya
with MIT License
from ahmet-cetinkaya
public IInterceptor[] SelectInterceptors(Type type, MethodInfo method, IInterceptor[] interceptors)
{
var clreplacedAttributes = type.GetCustomAttributes<MethodInterceptionBaseAttribute>
(true).ToList();
var methodAttributes = type.GetMethod(method.Name)
.GetCustomAttributes<MethodInterceptionBaseAttribute>(true);
clreplacedAttributes.AddRange(methodAttributes);
clreplacedAttributes.Add(new PerformanceAspect(5));
return clreplacedAttributes.OrderBy(x => x.Priority).ToArray();
}
19
Source : JsonServiceHandler.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public void ProcessRequest(HttpRequest Request, HttpResponse Response)
{
try
{
string name = System.IO.Path.GetFileNameWithoutExtension(Request.Url.AbsolutePath);
Debug.replacedert(_services.ContainsKey(name));
var svc = _services[name];
if (Request.QueryString.Count == 0)
{
// return proxy script of the service.
var proxy = new JsonServiceScript(svc);
string script = proxy.GenerateScript(name);
Response.SendJsonScript(script, false);
}
else
{
// call method.
string method = Request.QueryString["$method"] ?? Request.QueryString["$m"];
MethodInfo mi = svc.GetType().GetMethod(method);
if (mi != null)
{
try
{
if (Array.Exists(mi.GetCustomAttributes(false), a => a is RawRequestAttribute))
{
var result = mi.Invoke(svc, new object[] { Request });
Response.SendJsonObject(result, Request.CanCompress);
}
else if (Array.Exists(mi.GetCustomAttributes(false), a => a is RawParametersAttribute))
{
var result = mi.Invoke(svc, new object[] { Request.Parameters });
Response.SendJsonObject(result, Request.CanCompress);
}
else if (Array.Exists(mi.GetCustomAttributes(false), a => a is RawResponseAttribute))
{
mi.Invoke(svc, MakeInvokeParameters(mi, Request.Parameters, Response));
Response.Close();
}
else
{
// json response.
var result = mi.Invoke(svc, MakeInvokeParameters(mi, Request.Parameters));
Response.SendJsonObject(result, Request.CanCompress);
}
}
catch (Exception ex)
{
TraceLogger.Instance.WriteLineError(string.Format(@"Service Exception at: {0}::{1}", svc, method));
TraceLogger.Instance.WriteException(ex.InnerException == null ? ex : ex.InnerException); throw;
}
}
else
throw new NotImplementedException("Service method not found: " + method);
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
}
19
Source : HttpService.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private object[] MakeInvokeParameters(MethodInfo mi, HttpListenerRequest Request, HttpListenerResponse Response)
{
var attrs = mi.GetCustomAttributes(false);
if (Array.Exists(attrs, a => a is RawRequestAttribute))
{
return Array.Exists(attrs, a => a is RawResponseAttribute) ?
new object[] { Request, Response } :
new object[] { Request };
}
else if (Array.Exists(attrs, a => a is RawParametersAttribute))
{
return Array.Exists(attrs, a => a is RawResponseAttribute) ?
new object[] { Request.GetParameters(), Response } :
new object[] { Request.GetParameters() };
}
else
{
List<object> ps = new List<object>();
var prams = Request.GetParameters();
foreach (var p in mi.GetParameters())
{
if (prams[p.Name] != null)
ps.Add(DataConverter.ChangeType(prams[p.Name], p.ParameterType));
else
ps.Add(p.RawDefaultValue == DBNull.Value ? null : p.RawDefaultValue);
};
return ps.ToArray();
}
}
19
Source : DiscriminatedUnionConverter.cs
with MIT License
from akaskela
with MIT License
from akaskela
public override bool CanConvert(Type objectType)
{
if (typeof(IEnumerable).IsreplacedignableFrom(objectType))
{
return false;
}
// all fsharp objects have CompilationMappingAttribute
// get the fsharp replacedembly from the attribute and initialize latebound methods
object[] attributes;
#if !(DOTNET || PORTABLE)
attributes = objectType.GetCustomAttributes(true);
#else
attributes = objectType.GetTypeInfo().GetCustomAttributes(true).ToArray();
#endif
bool isFSharpType = false;
foreach (object attribute in attributes)
{
Type attributeType = attribute.GetType();
if (attributeType.FullName == "Microsoft.FSharp.Core.CompilationMappingAttribute")
{
FSharpUtils.EnsureInitialized(attributeType.replacedembly());
isFSharpType = true;
break;
}
}
if (!isFSharpType)
{
return false;
}
return (bool)FSharpUtils.IsUnion(null, objectType, null);
}
19
Source : ReflectionUtils.cs
with MIT License
from akaskela
with MIT License
from akaskela
public static Attribute[] GetAttributes(object attributeProvider, Type attributeType, bool inherit)
{
ValidationUtils.ArgumentNotNull(attributeProvider, nameof(attributeProvider));
object provider = attributeProvider;
// http://hyperthink.net/blog/getcustomattributes-gotcha/
// ICustomAttributeProvider doesn't do inheritance
if (provider is Type)
{
Type t = (Type)provider;
object[] a = (attributeType != null) ? t.GetCustomAttributes(attributeType, inherit) : t.GetCustomAttributes(inherit);
Attribute[] attributes = a.Cast<Attribute>().ToArray();
#if (NET20 || NET35)
// ye olde .NET GetCustomAttributes doesn't respect the inherit argument
if (inherit && t.BaseType != null)
{
attributes = attributes.Union(GetAttributes(t.BaseType, attributeType, inherit)).ToArray();
}
#endif
return attributes;
}
if (provider is replacedembly)
{
replacedembly a = (replacedembly)provider;
return (attributeType != null) ? Attribute.GetCustomAttributes(a, attributeType) : Attribute.GetCustomAttributes(a);
}
if (provider is MemberInfo)
{
MemberInfo m = (MemberInfo)provider;
return (attributeType != null) ? Attribute.GetCustomAttributes(m, attributeType, inherit) : Attribute.GetCustomAttributes(m, inherit);
}
#if !PORTABLE40
if (provider is Module)
{
Module m = (Module)provider;
return (attributeType != null) ? Attribute.GetCustomAttributes(m, attributeType, inherit) : Attribute.GetCustomAttributes(m, inherit);
}
#endif
if (provider is ParameterInfo)
{
ParameterInfo p = (ParameterInfo)provider;
return (attributeType != null) ? Attribute.GetCustomAttributes(p, attributeType, inherit) : Attribute.GetCustomAttributes(p, inherit);
}
#if !PORTABLE40
ICustomAttributeProvider customAttributeProvider = (ICustomAttributeProvider)attributeProvider;
object[] result = (attributeType != null) ? customAttributeProvider.GetCustomAttributes(attributeType, inherit) : customAttributeProvider.GetCustomAttributes(inherit);
return (Attribute[])result;
#else
throw new Exception("Cannot get attributes from '{0}'.".FormatWith(CultureInfo.InvariantCulture, provider));
#endif
}
19
Source : NodeDataCache.cs
with MIT License
from aksyr
with MIT License
from aksyr
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;
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]));
}
}
}
19
Source : GraphCLI.Generator.cs
with MIT License
from alelievr
with MIT License
from alelievr
public static void Export(BaseGraph graph, string filePath)
{
List< string > commands = new List< string >();
List< string > nodeNames = new List< string >();
var nodeToNameMap = new Dictionary< BaseNode, string >();
//GraphAttr commands
var fields = graph.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
foreach (var field in fields)
{
var attrs = field.GetCustomAttributes(true);
if (attrs.Any(a => a is TextSerializeField))
{
string s = GenerateGraphAttributeCommand(field.Name, field.GetValue(graph));
if (s != null)
commands.Add(s);
}
}
//CreateNode commands
foreach (var node in graph.allNodes)
{
var attrs = new BaseGraphCLIAttributes();
//load node attributes
FieldInfo[] attrFields = node.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
foreach (var field in attrFields)
{
var attributes = field.GetCustomAttributes(false);
bool isInput = attributes.Any(a => {
return a.GetType() == typeof(InputAttribute);
});
if (isInput)
continue ;
//if the field can't be jsonified, we skip it
if (Jsonizer.allowedJsonTypes.FindIndex(j => j.type == field.FieldType) == -1)
continue ;
attrs.Add(field.Name, field.GetValue(node));
}
string nodeName = node.name;
int i = 0;
//unique name generation
while (nodeNames.Contains(nodeName))
nodeName = node.name + i++;
nodeNames.Add(nodeName);
nodeToNameMap[node] = nodeName;
commands.Add(GenerateNewNodeCommand(node.GetType(), nodeName, node.rect.position, attrs));
}
//Link commands
foreach (var link in graph.nodeLinkTable.GetLinks())
{
if (link.fromNode == null || link.toNode == null)
continue ;
var fromName = nodeToNameMap[link.fromNode];
var toName = nodeToNameMap[link.toNode];
var fromAnchorName = link.fromAnchor.fieldName;
var toAnchorName = link.toAnchor.fieldName;
commands.Add(GenerateLinkAnchorNameCommand(fromName, fromAnchorName, toName, toAnchorName));
}
File.WriteAllLines(filePath, commands.ToArray());
}
19
Source : BaseNode.Init.cs
with MIT License
from alelievr
with MIT License
from alelievr
void LoadFieldAttributes()
{
//get input variables
System.Reflection.FieldInfo[] fInfos = GetType().GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
List< string > actualFields = new List< string >();
anchorFieldInfoMap.Clear();
foreach (var field in fInfos)
{
// reading field informations.
actualFields.Add(field.Name);
anchorFieldInfoMap[field.Name] = field;
if (!anchorFieldDictionary.ContainsKey(field.Name))
anchorFieldDictionary[field.Name] = CreateAnchorField();
AnchorField anchorField = anchorFieldDictionary[field.Name];
//detect multi-anchor by checking for PWArray<T> type
if (field.FieldType.IsGenericType)
{
if (field.FieldType.GetGenericTypeDefinition() == typeof(PWArray<>))
anchorField.multiple = true;
}
System.Object[] attrs = field.GetCustomAttributes(true);
foreach (var attr in attrs)
{
InputAttribute inputAttr = attr as InputAttribute;
OutputAttribute outputAttr = attr as OutputAttribute;
ColorAttribute colorAttr = attr as ColorAttribute;
OffsetAttribute offsetAttr = attr as OffsetAttribute;
VisibilityAttribute visibilityAttr = attr as VisibilityAttribute;
NotRequiredAttribute notRequiredAttr = attr as NotRequiredAttribute;
if (inputAttr != null)
{
anchorField.anchorType = AnchorType.Input;
if (inputAttr.name != null)
anchorField.name = inputAttr.name;
}
if (outputAttr != null)
{
anchorField.anchorType = AnchorType.Output;
if (outputAttr.name != null)
anchorField.name = outputAttr.name;
}
if (colorAttr != null)
anchorField.color = new SerializableColor(colorAttr.color);
if (offsetAttr != null)
{
anchorField.offset = offsetAttr.offset;
anchorField.padding = offsetAttr.padding;
}
if (notRequiredAttr != null)
anchorField.required = false;
if (visibilityAttr != null)
anchorField.defaultVisibility = visibilityAttr.visibility;
}
if (anchorField.anchorType == AnchorType.None) //field does not have a PW attribute
anchorFieldDictionary.Remove(field.Name);
else
{
//create anchor in this anchorField if there is not existing one
if (anchorField.anchors.Count == 0)
anchorField.CreateNewAnchor();
anchorField.colorSchemeName = ColorTheme.GetAnchorColorSchemeName(field.FieldType);
anchorField.fieldName = field.Name;
anchorField.fieldType = (SerializableType)field.FieldType;
anchorField.fieldValue = field.GetValue(this);
anchorField.nodeRef = this;
}
}
//remove inhexistants field dictionary entries (for renamed variables):
var toRemoveKeys = new List< string >();
foreach (var kp in anchorFieldDictionary)
if (!actualFields.Contains(kp.Key))
toRemoveKeys.Add(kp.Key);
foreach (var toRemoveKey in toRemoveKeys)
anchorFieldDictionary.Remove(toRemoveKey);
}
19
Source : BaseNode.Utils.cs
with MIT License
from alelievr
with MIT License
from alelievr
void LoadClonableFields()
{
clonableFields.Clear();
Type[] unserializableAttributes = {
typeof(InputAttribute),
typeof(OutputAttribute),
typeof(System.NonSerializedAttribute),
};
var fields = GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
foreach (var field in fields)
{
var attrs = field.GetCustomAttributes(false);
if (attrs.Any(a => unserializableAttributes.Contains(a.GetType())))
continue ;
if (field.IsPrivate && !attrs.Any(a => a is SerializeField))
continue ;
clonableFields.Add(ReflectionUtils.CreateGenericField(GetType(), field.Name));
}
}
19
Source : RuntimeUtilities.cs
with MIT License
from alelievr
with MIT License
from alelievr
public static Attribute[] GetMemberAttributes<TType, TValue>(Expression<Func<TType, TValue>> expr)
{
Expression body = expr;
if (body is LambdaExpression)
body = ((LambdaExpression)body).Body;
switch (body.NodeType)
{
case ExpressionType.MemberAccess:
var fi = (FieldInfo)((MemberExpression)body).Member;
return fi.GetCustomAttributes(false).Cast<Attribute>().ToArray();
default:
throw new InvalidOperationException();
}
}
19
Source : UndoRedoHelper.cs
with MIT License
from alelievr
with MIT License
from alelievr
public void LoadUndoableFields()
{
System.Reflection.FieldInfo[] fInfos = target.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
undoableFields.Clear();
foreach (var fInfo in fInfos)
{
var attrs = fInfo.GetCustomAttributes(false);
bool hreplacederializeField = false;
bool hasNonSerialized = false;
foreach (var attr in attrs)
{
if (attr is InputAttribute || attr is OutputAttribute)
goto skipThisField;
if (attr is System.NonSerializedAttribute)
hasNonSerialized = true;
if (attr is SerializeField)
hreplacederializeField = true;
}
if (fInfo.IsPrivate && !hreplacederializeField)
goto skipThisField;
if (hasNonSerialized)
goto skipThisField;
if (fInfo.IsNotSerialized)
goto skipThisField;
undoableFields.Add(ReflectionUtils.CreateGenericField(target.GetType(), fInfo.Name));
skipThisField:
continue ;
}
}
19
Source : GraphProcessor.cs
with MIT License
from alelievr
with MIT License
from alelievr
void BakeNode(System.Type t)
{
var dico = new Dictionary< string, FieldInfo >();
bakedNodeFields[t.replacedemblyQualifiedName] = dico;
foreach (var field in t.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
var attrs = field.GetCustomAttributes(false);
bool skip = true;
foreach (var attr in attrs)
if (attr is InputAttribute || attr is OutputAttribute)
skip = false;
if (skip)
continue ;
dico[field.Name] = field;
}
}
19
Source : InvokeWrapper.cs
with Apache License 2.0
from Algoryx
with Apache License 2.0
from Algoryx
public U[] GetAttributes<U>( bool inherit = false )
where U : Attribute
{
return Member.GetCustomAttributes<U>( inherit ).ToArray();
}
19
Source : DocumentHelper.cs
with MIT License
from aliencube
with MIT License
from aliencube
public OpenApiResponses GetOpenApiResponses(MethodInfo element, NamingStrategy namingStrategy, VisitorCollection collection)
{
var responsesWithBody = element.GetCustomAttributes<OpenApiResponseWithBodyAttribute>(inherit: false)
.Select(p => new { StatusCode = p.StatusCode, Response = p.ToOpenApiResponse(namingStrategy) });
var responsesWithoutBody = element.GetCustomAttributes<OpenApiResponseWithoutBodyAttribute>(inherit: false)
.Select(p => new { StatusCode = p.StatusCode, Response = p.ToOpenApiResponse(namingStrategy) });
var responses = responsesWithBody.Concat(responsesWithoutBody)
.ToDictionary(p => ((int)p.StatusCode).ToString(), p => p.Response)
.ToOpenApiResponses();
return responses;
}
19
Source : DocumentHelper.cs
with MIT License
from aliencube
with MIT License
from aliencube
public Dictionary<string, OpenApiSchema> GetOpenApiSchemas(List<MethodInfo> elements, NamingStrategy namingStrategy, VisitorCollection collection)
{
var requests = elements.SelectMany(p => p.GetCustomAttributes<OpenApiRequestBodyAttribute>(inherit: false))
.Select(p => p.BodyType);
var responses = elements.SelectMany(p => p.GetCustomAttributes<OpenApiResponseWithBodyAttribute>(inherit: false))
.Select(p => p.BodyType);
var types = requests.Union(responses)
.Select(p => p.IsOpenApiArray() || p.IsOpenApiDictionary() ? p.GetOpenApiSubType() : p)
.Distinct()
.Where(p => !p.IsSimpleType())
.Where(p => p != typeof(JObject))
.Where(p => p != typeof(JToken))
.Where(p => !typeof(Array).IsreplacedignableFrom(p))
.ToList();
var rootSchemas = new Dictionary<string, OpenApiSchema>();
var schemas = new Dictionary<string, OpenApiSchema>();
this._acceptor.Types = types.ToDictionary(p => p.GetOpenApiTypeName(namingStrategy), p => p);
this._acceptor.RootSchemas = rootSchemas;
this._acceptor.Schemas = schemas;
this._acceptor.Accept(collection, namingStrategy);
var union = schemas.Concat(rootSchemas.Where(p => !schemas.Keys.Contains(p.Key)))
.Distinct()
.OrderBy(p => p.Key)
.ToDictionary(p => p.Key,
p =>
{
// replacedle was intentionally added for schema key.
// It's not necessary when it's added to the root schema.
// Therefore, it's removed.
p.Value.replacedle = null;
return p.Value;
});
return union;
}
19
Source : DocumentHelper.cs
with MIT License
from aliencube
with MIT License
from aliencube
public List<OpenApiParameter> GetOpenApiParameters(MethodInfo element, HttpTriggerAttribute trigger, NamingStrategy namingStrategy, VisitorCollection collection)
{
var parameters = element.GetCustomAttributes<OpenApiParameterAttribute>(inherit: false)
.Select(p => p.ToOpenApiParameter(namingStrategy, collection))
.ToList();
// TODO: Should this be forcibly provided?
// This needs to be provided separately.
if (trigger.AuthLevel != AuthorizationLevel.Anonymous)
{
parameters.AddOpenApiParameter<string>("code", @in: ParameterLocation.Query, required: false);
}
return parameters;
}
19
Source : DocumentHelper.cs
with MIT License
from aliencube
with MIT License
from aliencube
public OpenApiRequestBody GetOpenApiRequestBody(MethodInfo element, NamingStrategy namingStrategy, VisitorCollection collection)
{
var attributes = element.GetCustomAttributes<OpenApiRequestBodyAttribute>(inherit: false);
if (!attributes.Any())
{
return null;
}
var contents = attributes.ToDictionary(p => p.ContentType, p => p.ToOpenApiMediaType(namingStrategy, collection));
if (contents.Any())
{
return new OpenApiRequestBody()
{
Content = contents,
Required = attributes.First().Required
};
}
return null;
}
19
Source : FieldPropertyListInfo.cs
with MIT License
from allenwp
with MIT License
from allenwp
public object[] GetCustomAttributes(bool inherit)
{
if (list != null)
{
// attributes aren't supported for list items
return new object[0];
}
else
{
return fieldInfo != null ? fieldInfo.GetCustomAttributes(inherit) : propertyInfo.GetCustomAttributes(inherit);
}
}
19
Source : EnumExtensions.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public static string ToEnumMemberAttributeValue(this Enum @enum)
{
EnumMemberAttribute attr = @enum
.GetType()
.GetMember(@enum.ToString())
.FirstOrDefault()
?.GetCustomAttributes(false)
.OfType<EnumMemberAttribute>()
.FirstOrDefault();
return attr == null ? @enum.ToString() : attr.Value;
}
19
Source : IDirectInputDevice8.cs
with MIT License
from amerkoleci
with MIT License
from amerkoleci
private unsafe DataFormat GetDataFormat<TRaw>() where TRaw : unmanaged
{
if (_dataFormat == null)
{
// Build DataFormat from IDataFormatProvider
if (typeof(IDataFormatProvider).IsreplacedignableFrom(typeof(TRaw)))
{
var provider = (IDataFormatProvider)(new TRaw());
_dataFormat = new DataFormat(provider.Flags)
{
DataSize = sizeof(TRaw),
ObjectsFormat = provider.ObjectsFormat
};
}
else
{
// Build DataFormat from DataFormat and DataObjectFormat attributes
IEnumerable<DataFormatAttribute> dataFormatAttributes = typeof(TRaw).GetCustomAttributes<DataFormatAttribute>(false);
if (dataFormatAttributes.Count() != 1)
throw new InvalidOperationException(
string.Format(System.Globalization.CultureInfo.InvariantCulture, "The structure [{0}] must be marked with DataFormatAttribute or provide a IDataFormatProvider",
typeof(TRaw).FullName));
_dataFormat = new DataFormat(((DataFormatAttribute)dataFormatAttributes.First()).Flags)
{
DataSize = sizeof(TRaw)
};
var dataObjects = new List<ObjectDataFormat>();
IEnumerable<FieldInfo> fields = typeof(TRaw).GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
// Iterates on fields
foreach (var field in fields)
{
IEnumerable<DataObjectFormatAttribute> dataObjectAttributes = field.GetCustomAttributes<DataObjectFormatAttribute>(false);
if (dataObjectAttributes.Count() > 0)
{
int fieldOffset = Marshal.OffsetOf(typeof(TRaw), field.Name).ToInt32();
int totalSizeOfField = Marshal.SizeOf(field.FieldType);
int offset = fieldOffset;
int numberOfDataObjects = 0;
// Count the number of effective sub-field for a field
// A field that contains a fixed array should have sub-field
for (int i = 0; i < dataObjectAttributes.Count(); i++)
{
var attr = dataObjectAttributes.ElementAt(i);
numberOfDataObjects += attr.ArrayCount == 0 ? 1 : attr.ArrayCount;
}
// Check that the size of the field is compatible with the number of sub-field
// For a simple field without any array element, sub-field = field
int sizeOfField = totalSizeOfField / numberOfDataObjects;
if ((sizeOfField * numberOfDataObjects) != totalSizeOfField)
throw new InvalidOperationException(string.Format(System.Globalization.CultureInfo.InvariantCulture, "Field [{0}] has incompatible size [{1}] and number of DataObjectAttributes [{2}]", field.Name, (double)totalSizeOfField / numberOfDataObjects, numberOfDataObjects));
int subFieldIndex = 0;
// Iterates on attributes
for (int i = 0; i < dataObjectAttributes.Count(); i++)
{
var attr = dataObjectAttributes.ElementAt(i);
numberOfDataObjects = attr.ArrayCount == 0 ? 1 : attr.ArrayCount;
// Add DataObjectFormat
for (int j = 0; j < numberOfDataObjects; j++)
{
var dataObject = new ObjectDataFormat(
string.IsNullOrEmpty(attr.Guid) ? Guid.Empty : new Guid(attr.Guid), offset,
attr.TypeFlags, attr.Flags, attr.InstanceNumber);
// Use attribute name or fallback to field's name
string name = (string.IsNullOrEmpty(attr.Name)) ? field.Name : attr.Name;
name = numberOfDataObjects == 1 ? name : name + subFieldIndex;
dataObject.Name = name;
dataObjects.Add(dataObject);
offset += sizeOfField;
subFieldIndex++;
}
}
}
}
_dataFormat.ObjectsFormat = dataObjects.ToArray();
}
for (int i = 0; i < _dataFormat.ObjectsFormat.Length; i++)
{
var dataObject = _dataFormat.ObjectsFormat[i];
// Map field name to object
if (_mapNameToObjectFormat.ContainsKey(dataObject.Name))
throw new InvalidOperationException(string.Format(System.Globalization.CultureInfo.InvariantCulture, "Incorrect field name [{0}]. Field name must be unique", dataObject.Name));
_mapNameToObjectFormat.Add(dataObject.Name, dataObject);
}
// DumpDataFormat(_dataFormat);
}
return _dataFormat;
}
19
Source : ContentManager.cs
with MIT License
from Aminator
with MIT License
from Aminator
public object[] GetCustomAttributes(bool inherit)
{
var attributes = memberInfo.GetCustomAttributes(inherit);
return GetAdditionalAttributes(attributes, inherit);
}
19
Source : ContentManager.cs
with MIT License
from Aminator
with MIT License
from Aminator
public object[] GetCustomAttributes(bool inherit)
{
return type.GetCustomAttributes(inherit);
}
19
Source : AttributeMap.cs
with MIT License
from AnotherEnd15
with MIT License
from AnotherEnd15
public static AttributeMap[] Create(TypeModel model, Type type, bool inherit)
{
#if COREFX || PROFILE259
Attribute[] all = System.Linq.Enumerable.ToArray(System.Linq.Enumerable.OfType<Attribute>(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;
}
19
Source : AttributeMap.cs
with MIT License
from AnotherEnd15
with MIT License
from AnotherEnd15
public static AttributeMap[] Create(TypeModel model, MemberInfo member, bool inherit)
{
#if COREFX || PROFILE259
Attribute[] all = System.Linq.Enumerable.ToArray(System.Linq.Enumerable.OfType<Attribute>(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;
}
19
Source : ITrigger.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public static async void ImportProperties(
this ITrigger t,
ITrigger source)
{
if (source == null ||
t == null)
{
return;
}
var properties = source.GetType().GetProperties(
BindingFlags.Public |
BindingFlags.Instance)
.Where(x =>
x.CanRead &&
x.CanWrite);
await WPFHelper.InvokeAsync(() =>
{
foreach (var pi in properties)
{
if (t.GetType().GetProperty(pi.Name) == null ||
ImportIgnoreProperties.Contains(pi.Name))
{
continue;
}
var attrs = pi.GetCustomAttributes(true);
if (attrs.Any(a => a is XmlIgnoreAttribute))
{
continue;
}
pi.SetValue(t, pi.GetValue(source));
Thread.Yield();
(t as TreeItemBase)?.ExecuteRaisePropertyChanged(pi.Name);
Thread.Yield();
}
switch (t)
{
case Spell spell:
spell.Enabled = true;
break;
case Ticker ticker:
ticker.Enabled = true;
break;
}
});
}
19
Source : BaseTestCase.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private void ApplyTestSetupAttributes()
{
// Apply TestSetup Attribute in correct order
TestContext.TestAdapter testAdapter = TestContext.CurrentContext.Test;
MethodInfo methodInfo = GetType().GetMethod(testAdapter.MethodName);
object[] attributes = methodInfo.GetCustomAttributes(true);
// This set will order the TestSetup Attributes in the appropriate execution order for NMS Instance Initialization.
// ie, should a test setup a connection and a session dependent that connection it ensure the connection setup attribute
// execute its setup first.
ISet<TestSetupAttribute> testSetupAttributes = new SortedSet<TestSetupAttribute>(TestSetupOrderComparer);
foreach (System.Attribute attribute in attributes)
{
if (attribute is TestSetupAttribute)
{
//Console.WriteLine("Setup Attribute Identification: {0}.", attribute.GetType().Name);
testSetupAttributes.Add(attribute as TestSetupAttribute);
}
}
foreach (TestSetupAttribute tsa in testSetupAttributes)
{
//Console.WriteLine("Setup Attribute: {0}.", tsa.GetType().Name);
try
{
tsa.Setup(this);
}
catch (Exception ex)
{
this.PrintTestFailureAndreplacedert(testAdapter.MethodName, "Failed to setup test attribute.", ex);
}
}
}
19
Source : WrappedMethodInfo.cs
with MIT License
from Aragas
with MIT License
from Aragas
public override object[] GetCustomAttributes(bool inherit) => _methodInfoImplementation.GetCustomAttributes(inherit);
19
Source : WrappedPropertyInfo.cs
with MIT License
from Aragas
with MIT License
from Aragas
public override object[] GetCustomAttributes(bool inherit) => _propertyInfoImplementation.GetCustomAttributes(inherit);
19
Source : AttributeLocator.cs
with MIT License
from arbelatech
with MIT License
from arbelatech
public static IReadOnlyCollection<Type> GetTypesWithAttribute<TAttr>() where TAttr : Attribute
{
var replacedembly = replacedembly.GetExecutingreplacedembly();
return replacedembly.GetTypes()
.Where(t => t.GetCustomAttributes<TAttr>(true).Any())
.ToList();
}
19
Source : ReflectionHelper.cs
with MIT License
from ARKlab
with MIT License
from ARKlab
public static TAttribute GetAttribute<TAttribute>(MemberInfo memberInfo)
{
var attributes = from a in memberInfo.GetCustomAttributes(true)
where a is TAttribute
select a;
return (TAttribute)attributes.FirstOrDefault();
}
19
Source : ReflectionHelper.cs
with MIT License
from ARKlab
with MIT License
from ARKlab
public static TAttribute GetAttribute<TAttribute>(Type type)
{
var attributes = from a in type.GetCustomAttributes(true)
where a is TAttribute
select a;
return (TAttribute)attributes.FirstOrDefault();
}
19
Source : UnityDebugViewerLogger.cs
with Apache License 2.0
from AsanCai
with Apache License 2.0
from 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
Source : MqttRouteTableFactory.cs
with MIT License
from Atlas-LiftTech
with MIT License
from Atlas-LiftTech
internal static MqttRouteTable Create(IEnumerable<MethodInfo> actions)
{
// A future perf improvement would be to use a stringbuilder to avoid multiple string allocations
var templatesByHandler = new Dictionary<MethodInfo, string[]>();
foreach (var action in actions)
{
// We're deliberately using inherit = false here. // MqttRouteAttribute is defined as non-inherited,
// because inheriting a route attribute always causes an ambiguity. You end up with two components (base
// clreplaced and derived clreplaced) with the same route.
var controllerTemplates = action.DeclaringType.GetCustomAttributes<MqttRouteAttribute>(inherit: false)
.Select(c => ReplaceTokens(c.Template, action.DeclaringType.Name, action.Name) + "/")
.ToArray();
var routeAttributes = action.GetCustomAttributes<MqttRouteAttribute>(inherit: false)
.Select(a => ReplaceTokens(a.Template, action.DeclaringType.Name, action.Name))
.ToArray();
if (controllerTemplates.Length == 0)
{
controllerTemplates = new string[] { "" };
}
// If an action doesn't have a route attribute on it, we use the action name. Unlike Mvc/WebAPI we don't
// need to strip the "Get", "Put", etc. prefixes from the action because MQTT doesn't have verbs by convention.
if (routeAttributes.Length == 0)
{
routeAttributes = new string[] { action.Name };
}
// If an action starts with a /, we throw away the inherited portion of the path. We don't process ~/
// because it wouldn't make sense in the context of Mqtt routing which has no concept of relative paths.
var templates = controllerTemplates.SelectMany((c) => routeAttributes, (c, a) => a[0] == '/' ? a.Substring(1) : $"{c}{a}").ToArray();
templatesByHandler.Add(action, templates);
}
return Create(templatesByHandler);
}
19
Source : FunctionSignatureExtractor.cs
with GNU General Public License v3.0
from atomex-me
with GNU General Public License v3.0
from atomex-me
public static string ExtractSignature<T>()
{
string result = null;
var memberInfo = typeof(T);
var clreplacedAttributes = memberInfo.GetCustomAttributes(true);
foreach (var attribute in clreplacedAttributes)
{
if (attribute is FunctionAttribute functionAttribute)
{
result += $"{functionAttribute.Name}(";
break;
}
}
if (result == null)
throw new Exception("Can't find event clreplaced name");
var types = new List<string>();
var clreplacedProperties = memberInfo.GetProperties();
foreach (var property in clreplacedProperties)
{
var propertyAttributes = property.GetCustomAttributes(true);
foreach (var attribute in propertyAttributes)
{
if (attribute is ParameterAttribute parameterAttribute)
types.Add(parameterAttribute.Type);
}
}
return result + string.Join(",", types) + ")";
}
See More Examples