System.Reflection.MemberInfo.GetCustomAttributes()

Here are the examples of the csharp api System.Reflection.MemberInfo.GetCustomAttributes() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

653 Examples 7

19 Source : ResponsePacketProcessor.cs
with MIT License
from 499116344

public IPacketCommand Process()
        {
            var receivePackageCommandAttributes = _receivePacketType.GetCustomAttributes<ReceivePacketCommand>();
            if (receivePackageCommandAttributes.Any())
            {
                var packetCommand = receivePackageCommandAttributes.First().Command;
                var types = replacedembly.GetExecutingreplacedembly().GetTypes();
                foreach (var type in types)
                {
                    var attributes = type.GetCustomAttributes<ResponsePacketCommand>();
                    if (!attributes.Any())
                    {
                        continue;
                    }

                    var responseCommand = attributes.First().Command;
                    if (responseCommand == packetCommand)
                    {
                        return Activator.CreateInstance(type, _args) as IPacketCommand;
                    }
                }
            }

            return new DefaultResponseCommand(new QQEventArgs<ReceivePacket>(_args.Service, _args.User,
                _args.ReceivePacket));
        }

19 Source : ReceivePacket.cs
with MIT License
from 499116344

internal void TlvExecutionProcessing(ICollection<Tlv> tlvs)
        {
            if (_tlvTypes == null)
            {
                var types = replacedembly.GetExecutingreplacedembly().GetTypes();
                _tlvTypes = new Dictionary<int, Type>();
                foreach (var type in types)
                {
                    var attributes = type.GetCustomAttributes();
                    if (!attributes.Any(attr => attr is TlvTagAttribute))
                    {
                        continue;
                    }

                    var attribute = attributes.First(attr => attr is TlvTagAttribute) as TlvTagAttribute;
                    _tlvTypes.Add((int) attribute.Tag, type);
                }
            }
            foreach (var tlv in tlvs)
            {
                if (_tlvTypes.ContainsKey(tlv.Tag))
                {
                    var tlvClreplaced = replacedembly.GetExecutingreplacedembly().CreateInstance(_tlvTypes[tlv.Tag].FullName, true);
                    var methodinfo = _tlvTypes[tlv.Tag].GetMethod("Parser_Tlv");
                    methodinfo.Invoke(tlvClreplaced, new object[] { User, Reader });
                }
            }
        }

19 Source : DispatchPacketToCommand.cs
with MIT License
from 499116344

public IPacketCommand dispatch_receive_packet(QQCommand command)
        {
            var types = replacedembly.GetExecutingreplacedembly().GetTypes();
            foreach (var type in types)
            {
                var attributes = type.GetCustomAttributes();
                if (!attributes.Any(attr => attr is ReceivePacketCommand))
                {
                    continue;
                }

                var attribute = attributes.First(attr => attr is ReceivePacketCommand) as ReceivePacketCommand;
                if (attribute.Command == command)
                {
                    var receivePacket =
                        Activator.CreateInstance(type, _data, _service, _transponder, _user) as IPacketCommand;
                    return receivePacket;
                }
            }

            return new DefaultReceiveCommand(_data, _service, _transponder, _user);
        }

19 Source : VxHelpers.cs
with MIT License
from Aaltuj

internal static List<T> GetAllAttributes<T>(Type modelType) where T : Attribute => modelType.GetCustomAttributes<T>().ToList();

19 Source : CommandManager.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static void Initialize()
        {
            commandHandlers = new Dictionary<string, CommandHandlerInfo>(StringComparer.OrdinalIgnoreCase);
            foreach (var type in replacedembly.GetExecutingreplacedembly().GetTypes())
            {
                foreach (var method in type.GetMethods())
                {
                    foreach (var attribute in method.GetCustomAttributes<CommandHandlerAttribute>())
                    {
                        var commandHandler = new CommandHandlerInfo()
                        {
                            Handler = (CommandHandler)Delegate.CreateDelegate(typeof(CommandHandler), method),
                            Attribute = attribute
                        };

                        commandHandlers[attribute.Command] = commandHandler;
                    }
                }
            }

            if (NonInteractiveConsole)
            {
                log.Info("ACEmulator command prompt disabled - Environment.GetEnvironmentVariable(ACE_NONINTERACTIVE_CONSOLE) was true");
                return;
            }

            var thread = new Thread(new ThreadStart(CommandThread));
            thread.Name = "Command Manager";
            thread.IsBackground = true;
            thread.Start();
        }

19 Source : InboundMessageManager.cs
with GNU Affero General Public License v3.0
from ACEmulator

private static void DefineMessageHandlers()
        {
            messageHandlers = new Dictionary<GameMessageOpcode, MessageHandlerInfo>();

            foreach (var type in replacedembly.GetExecutingreplacedembly().GetTypes())
            {
                foreach (var methodInfo in type.GetMethods())
                {
                    foreach (var messageHandlerAttribute in methodInfo.GetCustomAttributes<GameMessageAttribute>())
                    {
                        var messageHandler = new MessageHandlerInfo()
                        {
                            Handler   = (MessageHandler)Delegate.CreateDelegate(typeof(MessageHandler), methodInfo),
                            Attribute = messageHandlerAttribute
                        };

                        messageHandlers[messageHandlerAttribute.Opcode] = messageHandler;
                    }
                }
            }
        }

19 Source : InboundMessageManager.cs
with GNU Affero General Public License v3.0
from ACEmulator

private static void DefineActionHandlers()
        {
            actionHandlers = new Dictionary<GameActionType, ActionHandlerInfo>();

            foreach (var type in replacedembly.GetExecutingreplacedembly().GetTypes())
            {
                foreach (var methodInfo in type.GetMethods())
                {
                    foreach (var actionHandlerAttribute in methodInfo.GetCustomAttributes<GameActionAttribute>())
                    {
                        var actionhandler = new ActionHandlerInfo()
                        {
                            Handler = (ActionHandler)Delegate.CreateDelegate(typeof(ActionHandler), methodInfo),
                            Attribute = actionHandlerAttribute
                        };

                        actionHandlers[actionHandlerAttribute.Opcode] = actionhandler;
                    }
                }
            }
        }

19 Source : VssException.cs
with MIT License
from actions

internal static void GetTypeNameAndKeyForExceptionType(Type exceptionType, Version restApiVersion, out String typeName, out String typeKey)
        {
            typeName = null;
            typeKey = exceptionType.Name;
            if (restApiVersion != null)
            {
                IEnumerable<ExceptionMappingAttribute> exceptionAttributes = exceptionType.GetTypeInfo().GetCustomAttributes<ExceptionMappingAttribute>().Where(ea => ea.MinApiVersion <= restApiVersion && ea.ExclusiveMaxApiVersion > restApiVersion);
                if (exceptionAttributes.Any())
                {
                    ExceptionMappingAttribute exceptionAttribute = exceptionAttributes.First();
                    typeName = exceptionAttribute.TypeName;
                    typeKey = exceptionAttribute.TypeKey;
                }
                else if (restApiVersion < s_backCompatExclusiveMaxVersion)  //if restApiVersion < 3 we send the replacedembly qualified name with the current binary version switched out to 14
                {
                    typeName = GetBackCompatreplacedemblyQualifiedName(exceptionType);
                }
            }
            
            if (typeName == null)
            {

                replacedemblyName asmName = exceptionType.GetTypeInfo().replacedembly.GetName();
                if (asmName != null)
                {
                    //going forward we send "FullName" and simple replacedembly name which includes no version.
                    typeName = exceptionType.FullName + ", " + asmName.Name;
                }
                else
                {
                    String replacedemblyString = exceptionType.GetTypeInfo().replacedembly.FullName;
                    replacedemblyString = replacedemblyString.Substring(0, replacedemblyString.IndexOf(','));
                    typeName = exceptionType.FullName + ", " + replacedemblyString;
                }
            }
        }

19 Source : WrappedException.cs
with MIT License
from actions

private static void UpdateExceptionAttributeMappingCache()
        {
            foreach (replacedembly replacedembly in AppDomain.CurrentDomain.Getreplacedemblies().Where(a => !s_replacedembliesCheckedForExceptionMappings.Contains(a)))
            {
                if (DoesreplacedemblyQualify(replacedembly)) // only look at replacedemblies that match this binary's major version and public key token
                {
                    try
                    {

                        IEnumerable<Type> types;
                        try
                        {
                            // calling GetTypes has side effect of loading direct dependancies of the replacedembly.
                            types = replacedembly.GetTypes();
                        }
                        catch (ReflectionTypeLoadException ex)
                        {
                            // if dependant replacedembly fails to load, we should still be able to get all the exceptions, since it would be unlikely,
                            // that an exception is referencing a type from the replacedembly that failed to load.
                            types = ex.Types.Where<Type>(t => t != null);
                        }

                        foreach (TypeInfo typeInfo in types)
                        {
                            foreach (ExceptionMappingAttribute attribute in typeInfo.GetCustomAttributes<ExceptionMappingAttribute>())
                            {
                                Tuple<Version, Type> cachedValue;

                                // Check if the TypeName already exists in cache and add it if not.  if it does exist, update if it has a higher ExclusiveMaxApiVersion.
                                // (In theory an old exception could be mapped to more then one type in the case we want the latest server
                                // to send different older types to different versions of older clients.  This method is used only on client when converting a type 
                                // from an older server, so we want the latest mapping of the older type.)
                                if (!s_exceptionsWithAttributeMapping.TryGetValue(attribute.TypeName, out cachedValue) || attribute.ExclusiveMaxApiVersion > cachedValue.Item1)
                                {
                                    s_exceptionsWithAttributeMapping[attribute.TypeName] = new Tuple<Version, Type>(attribute.ExclusiveMaxApiVersion, typeInfo.AsType());
                                }
                            }
                        }
                    }
                    catch (Exception)
                    {
                        // if for any reason we can't get the defined types, we don't want an exception here to mask the real exception.
                    }
                }
                s_replacedembliesCheckedForExceptionMappings.Add(replacedembly); // keep track of all replacedemblies we have either ruled out or cached mappings for, so we don't have to consider them again
            }
        }

19 Source : BaseViewModelWithAnnotationValidation.cs
with MIT License
from ahmed-abdelrazek

public bool ValidateProperty(string propertyName)
        {
            if (_Properties.TryGetValue(propertyName, out PropertyInfo propInfo))
            {
                var errors = new List<object>();
                foreach (var attribute in propInfo.GetCustomAttributes<ValidationAttribute>())
                {
                    if (!attribute.IsValid(propInfo.GetValue(this)))
                    {
                        errors.Add(attribute.FormatErrorMessage(propertyName));
                    }
                }

                if (errors.Any())
                {
                    _ValidationErrorsByProperty[propertyName] = errors;
                    ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
                    return false;
                }

                if (_ValidationErrorsByProperty.Remove(propertyName))
                {
                    ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
                }
            }
            return true;
        }

19 Source : CommandsNextExtension.cs
with MIT License
from Aiko-IT-Systems

private void RegisterCommands(Type t, CommandGroupBuilder currentParent, IEnumerable<CheckBaseAttribute> inheritedChecks, out List<CommandBuilder> foundCommands)
        {
            var ti = t.GetTypeInfo();

            var lifespan = ti.GetCustomAttribute<ModuleLifespanAttribute>();
            var moduleLifespan = lifespan != null ? lifespan.Lifespan : ModuleLifespan.Singleton;

            var module = new CommandModuleBuilder()
                .WithType(t)
                .WithLifespan(moduleLifespan)
                .Build(this.Services);

            // restrict parent lifespan to more or equally restrictive
            if (currentParent?.Module is TransientCommandModule && moduleLifespan != ModuleLifespan.Transient)
                throw new InvalidOperationException("In a transient module, child modules can only be transient.");

            // check if we are anything
            var groupBuilder = new CommandGroupBuilder(module);
            var isModule = false;
            var moduleAttributes = ti.GetCustomAttributes();
            var moduleHidden = false;
            var moduleChecks = new List<CheckBaseAttribute>();

            foreach (var xa in moduleAttributes)
            {
                switch (xa)
                {
                    case GroupAttribute g:
                        isModule = true;
                        var moduleName = g.Name;
                        if (moduleName == null)
                        {
                            moduleName = ti.Name;

                            if (moduleName.EndsWith("Group") && moduleName != "Group")
                                moduleName = moduleName.Substring(0, moduleName.Length - 5);
                            else if (moduleName.EndsWith("Module") && moduleName != "Module")
                                moduleName = moduleName.Substring(0, moduleName.Length - 6);
                            else if (moduleName.EndsWith("Commands") && moduleName != "Commands")
                                moduleName = moduleName.Substring(0, moduleName.Length - 8);
                        }

                        if (!this.Config.CaseSensitive)
                            moduleName = moduleName.ToLowerInvariant();

                        groupBuilder.WithName(moduleName);

                        if (inheritedChecks != null)
                            foreach (var chk in inheritedChecks)
                                groupBuilder.WithExecutionCheck(chk);

                        foreach (var mi in ti.DeclaredMethods.Where(x => x.IsCommandCandidate(out _) && x.GetCustomAttribute<GroupCommandAttribute>() != null))
                            groupBuilder.WithOverload(new CommandOverloadBuilder(mi));
                        break;

                    case AliasesAttribute a:
                        foreach (var xalias in a.Aliases)
                            groupBuilder.WithAlias(this.Config.CaseSensitive ? xalias : xalias.ToLowerInvariant());
                        break;

                    case HiddenAttribute h:
                        groupBuilder.WithHiddenStatus(true);
                        moduleHidden = true;
                        break;

                    case DescriptionAttribute d:
                        groupBuilder.WithDescription(d.Description);
                        break;

                    case CheckBaseAttribute c:
                        moduleChecks.Add(c);
                        groupBuilder.WithExecutionCheck(c);
                        break;

                    default:
                        groupBuilder.WithCustomAttribute(xa);
                        break;
                }
            }

            if (!isModule)
            {
                groupBuilder = null;
                if (inheritedChecks != null)
                    moduleChecks.AddRange(inheritedChecks);
            }

            // candidate methods
            var methods = ti.DeclaredMethods;
            var commands = new List<CommandBuilder>();
            var commandBuilders = new Dictionary<string, CommandBuilder>();
            foreach (var m in methods)
            {
                if (!m.IsCommandCandidate(out _))
                    continue;

                var attrs = m.GetCustomAttributes();
                if (attrs.FirstOrDefault(xa => xa is CommandAttribute) is not CommandAttribute cattr)
                    continue;

                var commandName = cattr.Name;
                if (commandName == null)
                {
                    commandName = m.Name;
                    if (commandName.EndsWith("Async") && commandName != "Async")
                        commandName = commandName.Substring(0, commandName.Length - 5);
                }

                if (!this.Config.CaseSensitive)
                    commandName = commandName.ToLowerInvariant();

                if (!commandBuilders.TryGetValue(commandName, out var commandBuilder))
                {
                    commandBuilders.Add(commandName, commandBuilder = new CommandBuilder(module).WithName(commandName));

                    if (!isModule)
                        if (currentParent != null)
                            currentParent.WithChild(commandBuilder);
                        else
                            commands.Add(commandBuilder);
                    else
                        groupBuilder.WithChild(commandBuilder);
                }

                commandBuilder.WithOverload(new CommandOverloadBuilder(m));

                if (!isModule && moduleChecks.Any())
                    foreach (var chk in moduleChecks)
                        commandBuilder.WithExecutionCheck(chk);

                foreach (var xa in attrs)
                {
                    switch (xa)
                    {
                        case AliasesAttribute a:
                            foreach (var xalias in a.Aliases)
                                commandBuilder.WithAlias(this.Config.CaseSensitive ? xalias : xalias.ToLowerInvariant());
                            break;

                        case CheckBaseAttribute p:
                            commandBuilder.WithExecutionCheck(p);
                            break;

                        case DescriptionAttribute d:
                            commandBuilder.WithDescription(d.Description);
                            break;

                        case HiddenAttribute h:
                            commandBuilder.WithHiddenStatus(true);
                            break;

                        default:
                            commandBuilder.WithCustomAttribute(xa);
                            break;
                    }
                }

                if (!isModule && moduleHidden)
                    commandBuilder.WithHiddenStatus(true);
            }

            // candidate types
            var types = ti.DeclaredNestedTypes
                .Where(xt => xt.IsModuleCandidateType() && xt.DeclaredConstructors.Any(xc => xc.IsPublic));
            foreach (var type in types)
            {
                this.RegisterCommands(type.AsType(),
                    groupBuilder,
                    !isModule ? moduleChecks : null,
                    out var tempCommands);

                if (isModule)
                    foreach (var chk in moduleChecks)
                        groupBuilder.WithExecutionCheck(chk);

                if (isModule && tempCommands != null)
                    foreach (var xtcmd in tempCommands)
                        groupBuilder.WithChild(xtcmd);
                else if (tempCommands != null)
                    commands.AddRange(tempCommands);
            }

            if (isModule && currentParent == null)
                commands.Add(groupBuilder);
            else if (isModule)
                currentParent.WithChild(groupBuilder);
            foundCommands = commands;
        }

19 Source : GetDisplayName.cs
with MIT License
from akasarto

public static string GetDisplayName(this Enum @this)
		{
			if (@this == null)
			{
				return string.Empty;
			}

			var attributes = @this.GetType().GetMember(@this.ToString())?.FirstOrDefault()?.GetCustomAttributes();

			if (attributes != null)
			{
				foreach (var attribute in attributes)
				{
					if (attribute is DisplayAttribute)
					{
						return ((DisplayAttribute)attribute).GetName();
					}

					if (attribute is DisplayNameAttribute)
					{
						return ((DisplayNameAttribute)attribute).DisplayName;
					}
				}
			}

			return @this.ToString();
		}

19 Source : BaseNode.cs
with MIT License
from alelievr

void InitializeCustomPortTypeMethods()
		{
			MethodInfo[] methods = new MethodInfo[0];
			Type baseType = GetType();
			while (true)
			{
				methods = baseType.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance);
				foreach (var method in methods)
				{
					var typeBehaviors = method.GetCustomAttributes<CustomPortTypeBehavior>().ToArray();

					if (typeBehaviors.Length == 0)
						continue;

					CustomPortTypeBehaviorDelegate deleg = null;
					try
					{
						deleg = Delegate.CreateDelegate(typeof(CustomPortTypeBehaviorDelegate), this, method) as CustomPortTypeBehaviorDelegate;
					} catch (Exception e)
					{
						Debug.LogError(e);
						Debug.LogError($"Cannot convert method {method} to a delegate of type {typeof(CustomPortTypeBehaviorDelegate)}");
					}

					foreach (var typeBehavior in typeBehaviors)
						customPortTypeBehaviorMap[typeBehavior.type] = deleg;
				}

				// Try to also find private methods in the base clreplaced
				baseType = baseType.BaseType;
				if (baseType == null)
					break;
			}
		}

19 Source : NodeProvider.cs
with MIT License
from alelievr

static bool IsNodeAccessibleFromMenu(Type nodeType)
		{
			if (nodeType.IsAbstract)
				return false;

			return nodeType.GetCustomAttributes<NodeMenuItemAttribute>().Count() > 0;
		}

19 Source : NodeProvider.cs
with MIT License
from alelievr

static bool IsNodeSpecificToGraph(Type nodeType)
		{
			var isCompatibleWithGraphMethods = nodeType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy).Where(m => m.GetCustomAttribute<IsCompatibleWithGraph>() != null);
			var nodeMenuAttributes = nodeType.GetCustomAttributes<NodeMenuItemAttribute>();

			List<Type> compatibleGraphTypes = nodeMenuAttributes.Where(n => n.onlyCompatibleWithGraph != null).Select(a => a.onlyCompatibleWithGraph).ToList();

			List<MethodInfo> compatibleMethods = new List<MethodInfo>();
			foreach (var method in isCompatibleWithGraphMethods)
			{
				// Check if the method is static and have the correct prototype
				var p = method.GetParameters();
				if (method.ReturnType != typeof(bool) || p.Count() != 1 || p[0].ParameterType != typeof(BaseGraph))
					Debug.LogError($"The function '{method.Name}' marked with the IsCompatibleWithGraph attribute either doesn't return a boolean or doesn't take one parameter of BaseGraph type.");
				else
					compatibleMethods.Add(method);
			}

			if (compatibleMethods.Count > 0 || compatibleGraphTypes.Count > 0)
			{
				// We still need to add the element in specificNode even without specific graph
				if (compatibleGraphTypes.Count == 0)
					compatibleGraphTypes.Add(null);

				foreach (var graphType in compatibleGraphTypes)
				{
					specificNodes.Add(new NodeSpecificToGraph{
						nodeType = nodeType,
						isCompatibleWithGraph = compatibleMethods,
						compatibleWithGraphType = graphType
					});
				}
				return true;
			}
			return false;
		}

19 Source : NodeProvider.cs
with MIT License
from alelievr

static void BuildCacheForNode(Type nodeType, NodeDescriptions targetDescription, BaseGraph graph = null)
		{
			var attrs = nodeType.GetCustomAttributes(typeof(NodeMenuItemAttribute), false) as NodeMenuItemAttribute[];

			if (attrs != null && attrs.Length > 0)
			{
				foreach (var attr in attrs)
					targetDescription.nodePerMenureplacedle[attr.menureplacedle] = nodeType;
			}

			foreach (var field in nodeType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
			{
				if (field.GetCustomAttribute<HideInInspector>() == null && field.GetCustomAttributes().Any(c => c is InputAttribute || c is OutputAttribute))
					targetDescription.slotTypes.Add(field.FieldType);
			}

			ProvideNodePortCreationDescription(nodeType, targetDescription, graph);
		}

19 Source : LinqToSql.cs
with MIT License
from AlenToma

protected override Expression VisitMethodCall(MethodCallExpression m)
        {
            if (m.Method.DeclaringType == typeof(Queryable) || (m.Method.Name == "Any"))
            {
                var invert = GetInvert();
                var typecast = m.Arguments.First().Type.GenericTypeArguments.First();
                var cl = new LinqToSql(typecast, _transaction);
                cl._generatedKeys = _generatedKeys;
                cl.DataBaseTypes = DataBaseTypes;
                cl.Translate(m.Arguments.Last() as Expression);
                cl._overridedNodeType = ExpressionType.MemberAccess;
                cl.Visit(m.Arguments[0]);
                if (!string.IsNullOrEmpty(invert))
                    sb.Append(invert);
                sb.Append(cl.QuaryExist);
                cl._overridedNodeType = null;
                _generatedKeys = cl._generatedKeys;
                return m;
            }
            else if (m.Method.Name == "IsNullOrEmpty")
            {

                var invert = sb.ToString().EndsWith("NOT ");
                GetInvert();
                sb.Append("((CASE WHEN ");
                this.Visit(m.Arguments[0]);
                CleanDecoder("");
                sb.Append(" IS NULL THEN " + boolString.Replace("#", "1T") + " ELSE CASE WHEN ");
                this.Visit(m.Arguments[0]);
                CleanDecoder("");
                sb.Append(" = String[] THEN " + boolString.Replace("#", "1T") + " ELSE " + boolString.Replace("#", "0T") + " END END)");
                sb.Append(")");
                sb.Append(boolString.Replace("#", invert ? "0" : "1"));
                return m;
            }
            else if (m.Method.Name == "Contains")
            {
                var ex = (((MemberExpression)m.Object).Expression as ConstantExpression);

                if (ex == null && ((MemberExpression)m.Object).Expression != null)
                {
                    var invert = GetInvert();
                    var value = GetSingleValue(m.Arguments[0]);
                    sb.Append("(CASE WHEN ");
                    this.Visit(m.Object);
                    InsertBeforeDecoder(" LIKE ");
                    CleanDecoder(string.Format("String[%{0}%]", value));
                    sb.Append(" THEN " + boolString.Replace("#", "1T") + " ELSE " + boolString.Replace("#", "0T") + " END) ");
                    sb.Append(boolString.Replace("#", !string.IsNullOrEmpty(invert) ? "0" : "1"));
                }
                else
                {
                    var invert = GetInvert();
                    sb.Append("(CASE WHEN ");
                    this.Visit(m.Arguments[0]);
                    InsertBeforeDecoder(" in (");
                    try
                    {
                        var Stringify = (m.Arguments[0] as MemberExpression).Member as PropertyInfo != null ? ((m.Arguments[0] as MemberExpression).Member as PropertyInfo).GetCustomAttributes<Stringify>() != null : false;
                        var value = GetSingleValue((MemberExpression)m.Object);
                        if (value == null)
                            this.Visit(ex);
                        else
                        {
                            var v = ValuetoSql(value, Stringify);
                            if (string.IsNullOrEmpty(v))
                            {
                                if (Stringify)
                                    v = ValuetoSql(string.Format("DefaultValueForEmptyArray({0})", Guid.NewGuid().ToString()), Stringify);
                                else
                                    v = ValuetoSql(-1, Stringify);
                            }

                            CleanDecoder(v);
                        }
                    }
                    catch
                    {
                        this.Visit(ex);
                    }
                    sb.Append(") THEN " + boolString.Replace("#", "1T") + " ELSE " + boolString.Replace("#", "0T") + " END) ");
                    sb.Append(boolString.Replace("#", !string.IsNullOrEmpty(invert) ? "0" : "1"));
                }
                return m;
            }
            else if (m.Method.Name == "StartsWith")
            {
                var ex = (((MemberExpression)m.Object).Expression as ConstantExpression);
                if (ex == null && ((MemberExpression)m.Object).Expression != null)
                {
                    var invert = GetInvert();
                    var value = GetSingleValue(m.Arguments[0]);
                    sb.Append("(CASE WHEN ");
                    this.Visit(m.Object);
                    InsertBeforeDecoder(" LIKE ");
                    CleanDecoder(string.Format("String[{0}%]", value));
                    sb.Append(" THEN " + boolString.Replace("#", "1T") + " ELSE " + boolString.Replace("#", "0T") + " END) ");
                    sb.Append(boolString.Replace("#", !string.IsNullOrEmpty(invert) ? "0" : "1"));

                }
                else
                {

                    var invert = GetInvert();
                    sb.Append("(CASE WHEN ");
                    this.Visit(m.Arguments[0]);
                    InsertBeforeDecoder(" LIKE ");
                    var value = GetSingleValue((MemberExpression)m.Object);
                    CleanDecoder(string.Format("String[{0}%]", value));
                    sb.Append(" THEN " + boolString.Replace("#", "1T") + " ELSE " + boolString.Replace("#", "0T") + " END) ");
                    sb.Append(boolString.Replace("#", !string.IsNullOrEmpty(invert) ? "0" : "1"));

                }
                return m;
            }
            else
            if (m.Method.Name == "EndsWith")
            {
                var ex = (((MemberExpression)m.Object).Expression as ConstantExpression);
                if (ex == null && ((MemberExpression)m.Object).Expression != null)
                {
                    var invert = GetInvert();
                    var value = GetSingleValue(m.Arguments[0]);
                    sb.Append("(CASE WHEN ");
                    this.Visit(m.Object);
                    InsertBeforeDecoder(" LIKE ");
                    CleanDecoder(string.Format("String[%{0}]", value));
                    sb.Append(" THEN " + boolString.Replace("#", "1T") + " ELSE " + boolString.Replace("#", "0T") + " END) ");
                    sb.Append(boolString.Replace("#", !string.IsNullOrEmpty(invert) ? "0" : "1"));

                }
                else
                {

                    var invert = GetInvert();
                    sb.Append("(CASE WHEN ");
                    this.Visit(m.Arguments[0]);
                    InsertBeforeDecoder(" LIKE ");
                    var value = GetSingleValue((MemberExpression)m.Object);
                    CleanDecoder(string.Format("String[%{0}]", value));
                    sb.Append(" THEN " + boolString.Replace("#", "1T") + " ELSE " + boolString.Replace("#", "0T") + " END) ");
                    sb.Append(boolString.Replace("#", !string.IsNullOrEmpty(invert) ? "0" : "1"));

                }
                return m;
            }
            else if (m.Method.Name == "Take")
            {
                if (this.ParseTakeExpression(m))
                {
                    return null;
                }
            }
            else if (m.Method.Name == "Skip")
            {
                if (this.ParseSkipExpression(m))
                {
                    return null;
                }
            }
            else if (m.Method.Name == "OrderBy")
            {
                if (this.ParseOrderByExpression(m, "ASC"))
                {
                    return null;
                }
            }
            else if (m.Method.Name == "OrderByDescending")
            {
                if (this.ParseOrderByExpression(m, "DESC"))
                {
                    return null;
                }
            }
            else if (m.Method.ReturnType.IsInternalType())
            {
                CleanDecoder(ValuetoSql(Expression.Lambda(m).Compile().DynamicInvoke()));
                return m;
            }
            else if ((m.Arguments?.Any() ?? false))
            {
                var expression = m.Arguments.First();
                if ((expression?.ToString().Contains("DisplayClreplaced") ?? false))
                {
                    CleanDecoder(ValuetoSql(Expression.Lambda(m).Compile().DynamicInvoke()));
                    return m;
                }
                else
                    throw new EnreplacedyException(string.Format("The method '{0}' is not supported", m.Method.Name));
            }

            throw new EnreplacedyException(string.Format("The method '{0}' is not supported", m.Method.Name));
        }

19 Source : TypeHelpers.cs
with MIT License
from AlexGhiondea

private static List<ArgumentGroupInfo> GetGroupsForProperty(TypeArgumentInfo tInfo, PropertyInfo property)
        {
            List<ArgumentGroupInfo> groupsForThisProperty = new List<ArgumentGroupInfo>();

            var customAttributes = property.GetCustomAttributes<GroupAttribute>();

            if (!customAttributes.Any())
            {
                // we need to make sure that we don't add this here is the attribute we are adding is the Action one (which is outside of groups)
                if (!property.GetCustomAttributes<ActionArgumentAttribute>().Any())
                {
                    // we have the simple case where we don't have groups defined
                    groupsForThisProperty.Add(GetArgumentInfoForSingleGroup(string.Empty, tInfo));
                }
            }
            else
            {
                // we have the complex scenario where groups are present

                // there are 2 types of arguments in a group:
                //  - common ones, flagged with the CommonArgumentAttribute
                //  - specific to each command group, flagged with ArgumentGroupAttribute
                groupsForThisProperty.AddRange(GetArgumentInfoForGroups(tInfo, customAttributes, property));
            }

            return groupsForThisProperty;
        }

19 Source : TypeHelpers.cs
with MIT License
from AlexGhiondea

public static void ScanTypeForProperties<TOptions>(out TypeArgumentInfo tInfo)
        {
            tInfo = new TypeArgumentInfo();
            PropertyInfo[] propertiesOnType = typeof(TOptions).GetTypeInfo().GetProperties(BindingFlags.Instance | BindingFlags.Public);

            // first of all, find the commandArgument, if any.
            tInfo.ActionArgument = FindCommandProperty(propertiesOnType);

            // we want to be able to support empty groups.
            if (tInfo.ActionArgument != null && IsEnum(tInfo.ActionArgument.PropertyType))
            {
                // get the values of the enum.
                var enumValues = Enum.GetValues(tInfo.ActionArgument.PropertyType);

                // Sort the enum by the enum values
                Array.Sort(enumValues);

                // add them to the dictionary now to make sure we preserve the order
                foreach (var val in enumValues)
                {
                    if (!tInfo.ArgumentGroups.ContainsKey(val.ToString()))
                    {
                        tInfo.ArgumentGroups.Add(val.ToString(), new ArgumentGroupInfo());
                    }
                }
            }

            // parse the rest of the properties
            foreach (PropertyInfo property in propertiesOnType)
            {
                // get the group containing this property (note: more than one group can have the same property)
                // this allows common required parameters

                List<ArgumentGroupInfo> groupsWhereThePropertyIsParticipating = GetGroupsForProperty(tInfo, property);
                List<ActualArgumentAttribute> actualAttribs = property.GetCustomAttributes<ActualArgumentAttribute>().ToList();

                if (actualAttribs.Count > 1)
                {
                    throw new ArgumentException($"Only one of Required/Optional attribute are allowed per property ({property.Name}). Help information might be incorrect!");
                }

                // if we have no attributes on that property, move on
                ActualArgumentAttribute baseAttrib = actualAttribs.FirstOrDefault();
                if (baseAttrib == null)
                {
                    continue;
                }

                // add the property to the groups it is a part of
                if (baseAttrib is RequiredArgumentAttribute)
                {
                    foreach (ArgumentGroupInfo grpPropInfo in groupsWhereThePropertyIsParticipating)
                    {
                        // do we have an override for this property? If we do, use that, otherwise use the regular one.
                        if (!grpPropInfo.OverridePositions.TryGetValue(property, out int requiredPositionIndex))
                        {
                            requiredPositionIndex = (int)baseAttrib.GetArgumentId();
                        }

                        if (grpPropInfo.RequiredArguments.ContainsKey(requiredPositionIndex))
                        {
                            throw new ArgumentException("Two required arguments share the same position!!");
                        }

                        // if we have a collection argument, keep track of it
                        if (baseAttrib.IsCollection)
                        {
                            // if we already have defined a required collection argument, throw an error
                            if (grpPropInfo.IndexOfCollectionArgument >= 0)
                            {
                                throw new ArgumentException("Cannot declare two required collection arguments. Please convert one of them to an optional collection one.");
                            }
                            grpPropInfo.IndexOfCollectionArgument = requiredPositionIndex;
                        }

                        grpPropInfo.RequiredArguments[requiredPositionIndex] = property;
                    }
                }
                else if (baseAttrib is OptionalArgumentAttribute)
                {
                    foreach (ArgumentGroupInfo grpPropInfo in groupsWhereThePropertyIsParticipating)
                    {
                        if (grpPropInfo.OptionalArguments.ContainsKey((string)baseAttrib.GetArgumentId()))
                        {
                            throw new ArgumentException("Two optional arguments share the same name!!");
                        }

                        grpPropInfo.OptionalArguments[(string)baseAttrib.GetArgumentId()] = property;
                    }
                }
            }

            // remove the empty one, if empty
            if (tInfo.ArgumentGroups.TryGetValue(string.Empty, out ArgumentGroupInfo grp))
            {
                if (grp.OptionalArguments.Count == 0 && grp.RequiredArguments.Count == 0)
                    tInfo.ArgumentGroups.Remove(string.Empty);
            }

            // validate that the collection is the last argument
            foreach (KeyValuePair<string, ArgumentGroupInfo> group in tInfo.ArgumentGroups)
            {
                if (group.Value.IndexOfCollectionArgument >= 0 && group.Value.IndexOfCollectionArgument != group.Value.RequiredArguments.Count - 1)
                {
                    if (!string.IsNullOrEmpty(group.Key))
                    {
                        throw new ArgumentException($"The required collection argument for group `{group.Key}` needs to be on the last position of the required arguments.");
                    }
                    else
                    {
                        throw new ArgumentException("The required collection argument needs to be on the last position of the required arguments.");
                    }
                }
            }
        }

19 Source : MemberInfoExtensions.cs
with MIT License
from AlFasGD

public static bool HasCustomAttributes<T>(this MemberInfo member, out IEnumerable<T> instances)
            where T : Attribute
        {
            instances = member.GetCustomAttributes<T>();
            return instances.Any();
        }

19 Source : SongInformation.cs
with MIT License
from AlFasGD

private static ImmutableArray<string> GetAttributedFields<TAttribute>()
            where TAttribute : Attribute
        {
            return typeof(SongInformation).GetFields()
                .Where(f => f.GetCustomAttributes<TAttribute>().Any())
                .Select(f => f.GetRawConstantValue() as string)
                .ToImmutableArray();
        }

19 Source : InvokeWrapperInspectorDrawer.cs
with Apache License 2.0
from Algoryx

public static DrawerInfo GetDrawerMethod( Type type )
    {
      DrawerInfo drawerInfo;
      if ( !m_drawerMethodsCache.TryGetValue( type, out drawerInfo ) ) {
        drawerInfo = new DrawerInfo() { Drawer = null, CopyOp = null, IsNullable = false };
        foreach ( var drawerClreplaced in m_drawerClreplacedes ) {
          var methods = drawerClreplaced.GetMethods( BindingFlags.Public | BindingFlags.Static );
          foreach ( var method in methods ) {
            if ( method.GetCustomAttributes<InspectorDrawerAttribute>().FirstOrDefault( attribute => attribute.Match( type ) ) != null ) {
              drawerInfo.Drawer = method;
              FindDrawerResult( ref drawerInfo, drawerClreplaced );
              m_drawerMethodsCache.Add( type, drawerInfo );
              break;
            }
          }

          if ( drawerInfo.Drawer != null )
            break;
        }
      }

      return drawerInfo;
    }

19 Source : DynamicUnionResolver.cs
with Apache License 2.0
from allenai

private static TypeInfo BuildType(Type type)
        {
            TypeInfo ti = type.GetTypeInfo();

            // order by key(important for use jump-table of switch)
            UnionAttribute[] unionAttrs = ti.GetCustomAttributes<UnionAttribute>().OrderBy(x => x.Key).ToArray();

            if (unionAttrs.Length == 0)
            {
                return null;
            }

            if (!ti.IsInterface && !ti.IsAbstract)
            {
                throw new MessagePackDynamicUnionResolverException("Union can only be interface or abstract clreplaced. Type:" + type.Name);
            }

            var checker1 = new HashSet<int>();
            var checker2 = new HashSet<Type>();
            foreach (UnionAttribute item in unionAttrs)
            {
                if (!checker1.Add(item.Key))
                {
                    throw new MessagePackDynamicUnionResolverException("Same union key has found. Type:" + type.Name + " Key:" + item.Key);
                }

                if (!checker2.Add(item.SubType))
                {
                    throw new MessagePackDynamicUnionResolverException("Same union subType has found. Type:" + type.Name + " SubType: " + item.SubType);
                }
            }

            Type formatterType = typeof(IMessagePackFormatter<>).MakeGenericType(type);
            using (MonoProtection.EnterRefEmitLock())
            {
                TypeBuilder typeBuilder = Dynamicreplacedembly.Value.DefineType("MessagePack.Formatters." + SubtractFullNameRegex.Replace(type.FullName, string.Empty).Replace(".", "_") + "Formatter" + +Interlocked.Increment(ref nameSequence), TypeAttributes.Public | TypeAttributes.Sealed, null, new[] { formatterType });

                FieldBuilder typeToKeyAndJumpMap = null; // Dictionary<RuntimeTypeHandle, KeyValuePair<int, int>>
                FieldBuilder keyToJumpMap = null; // Dictionary<int, int>

                // create map dictionary
                {
                    ConstructorBuilder method = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes);
                    typeToKeyAndJumpMap = typeBuilder.DefineField("typeToKeyAndJumpMap", typeof(Dictionary<RuntimeTypeHandle, KeyValuePair<int, int>>), FieldAttributes.Private | FieldAttributes.InitOnly);
                    keyToJumpMap = typeBuilder.DefineField("keyToJumpMap", typeof(Dictionary<int, int>), FieldAttributes.Private | FieldAttributes.InitOnly);

                    ILGenerator il = method.GetILGenerator();
                    BuildConstructor(type, unionAttrs, method, typeToKeyAndJumpMap, keyToJumpMap, il);
                }

                {
                    MethodBuilder method = typeBuilder.DefineMethod(
                        "Serialize",
                        MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot,
                        null,
                        new Type[] { typeof(MessagePackWriter).MakeByRefType(), type, typeof(MessagePackSerializerOptions) });

                    ILGenerator il = method.GetILGenerator();
                    BuildSerialize(type, unionAttrs, method, typeToKeyAndJumpMap, il);
                }

                {
                    MethodBuilder method = typeBuilder.DefineMethod(
                        "Deserialize",
                        MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot,
                        type,
                        new Type[] { refMessagePackReader, typeof(MessagePackSerializerOptions) });

                    ILGenerator il = method.GetILGenerator();
                    BuildDeserialize(type, unionAttrs, method, keyToJumpMap, il);
                }

                return typeBuilder.CreateTypeInfo();
            }
        }

19 Source : DarkMeta.cs
with MIT License
from Alprog

private void ProcessMember(MemberInfo memberInfo, List<KeyValuePair<int, MemberFormatter>> formatters, ref int count)
        {
            var keys = memberInfo.GetCustomAttributes<KeyAttribute>();
            foreach (var key in keys)
            {
                if (key.Value == -1)
                {
                    if (LastKeyAttribute == null)
                    {
                        LastKeyAttribute = new LastKeyAttribute();
                        Logger.Instance.Error("Type {0} contains unsetted keys, but it has no one [LastKey] attribute. Saves won't work properly!", Type.FullName);
                    }
                    key.Value = LastKeyAttribute.Value++;
                }

                if (key.DistributedSubPath != null)
                {
                    var flags = key.Flags | SerializationFlags.Distributed;
                    var externalFormatter = MemberFormatter.CreateDistributed(memberInfo, flags, key.DistributedSubPath);
                    formatters.Add(new KeyValuePair<int, MemberFormatter>(key.Value, externalFormatter));
                }
                var formatter = MemberFormatter.Create(memberInfo, key.Flags);
                formatters.Add(new KeyValuePair<int, MemberFormatter>(key.Value, formatter));
                count = Math.Max(count, key.Value + 1);
            }
        }

19 Source : JsonSubTypes.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

private static Type GetTypeByPropertyPresence(JObject jObject, Type parentType)
        {
            foreach (var type in parentType.GetTypeInfo().GetCustomAttributes<KnownSubTypeWithPropertyAttribute>())
            {
                JToken ignore;
                if (jObject.TryGetValue(type.PropertyName, out ignore))
                {
                    return type.SubType;
                }
            }

            return null;
        }

19 Source : JsonSubTypes.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

private static Dictionary<object, Type> GetSubTypeMapping(Type type)
        {
            return type.GetTypeInfo().GetCustomAttributes<KnownSubTypeAttribute>().ToDictionary(x => x.replacedociatedValue, x => x.SubType);
        }

19 Source : EntityManager.cs
with MIT License
from Aminator

private void CollectNewEnreplacedySystems(Type componentType)
        {
            var enreplacedySystemAttributes = componentType.GetCustomAttributes<DefaultEnreplacedySystemAttribute>();

            foreach (DefaultEnreplacedySystemAttribute enreplacedySystemAttribute in enreplacedySystemAttributes)
            {
                bool addNewSystem = !Systems.Any(s => s.GetType() == enreplacedySystemAttribute.Type);

                if (addNewSystem)
                {
                    EnreplacedySystem system = (EnreplacedySystem)ActivatorUtilities.CreateInstance(Services, enreplacedySystemAttribute.Type);
                    system.EnreplacedyManager = this;

                    Systems.Add(system);
                }
            }
        }

19 Source : ShaderGenerator.cs
with MIT License
from Aminator

private void WriteMethod(MethodInfo methodInfo, bool isTopLevel = false, string ? explicitMethodName = null, IEnumerable<Attribute>? attributes = null)
        {
            bool isStatic = methodInfo.IsStatic;

            var methodAttributes = methodInfo.GetCustomAttributes();

            if (attributes != null)
            {
                methodAttributes = methodAttributes.Concat(attributes);
            }

            foreach (Attribute attribute in methodAttributes)
            {
                if (isTopLevel || !(attribute is ShaderAttribute))
                {
                    WriteAttribute(attribute);
                }
            }

            if (isStatic) writer.Write("static ");

            string methodName = explicitMethodName ?? methodInfo.Name;

            writer.Write(HlslKnownTypes.GetMappedName(methodInfo.ReturnType));
            writer.Write(" ");
            writer.Write(methodName);

            WriteParameters(methodInfo);

            if (methodInfo.ReturnTypeCustomAttributes.GetCustomAttributes(typeof(ShaderSemanticAttribute), false).FirstOrDefault(a => HlslKnownTypes.ContainsKey(a.GetType())) is ShaderSemanticAttribute returnTypeAttribute)
            {
                writer.Write(GetHlslSemantic(returnTypeAttribute));
            }

            if (methodInfo.GetMethodBody() != null)
            {
                string methodBody = GetMethodBody(methodInfo);

                writer.WriteLine();
                writer.WriteLine("{");
                writer.Indent++;
                writer.WriteLine(methodBody);
                writer.Indent--;
                writer.WriteLine("}");
            }
            else
            {
                writer.Write(";");
            }

            writer.WriteLine();
        }

19 Source : Snapshot.cs
with MIT License
from amolines

private IEnumerable<PropertyInfo> Properties()
        {
            return GetType().GetProperties().Where(p => !p.GetCustomAttributes<InternalPropertyAttribute>().Any()).ToArray();
        }

19 Source : EmbedFieldAttribute.cs
with MIT License
from amolines

public static IEnumerable<string> GetFields<T>()
        {
            var fields = typeof(T).GetCustomAttributes<EmbedFieldAttribute>();
            return fields.Select(field => field.Name);
        }

19 Source : ModelDescriptionGenerator.cs
with GNU General Public License v3.0
from andysal

private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
        {
            List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();

            IEnumerable<Attribute> attributes = property.GetCustomAttributes();
            foreach (Attribute attribute in attributes)
            {
                Func<object, string> textGenerator;
                if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
                {
                    annotations.Add(
                        new ParameterAnnotation
                        {
                            AnnotationAttribute = attribute,
                            Doreplacedentation = textGenerator(attribute)
                        });
                }
            }

            // Rearrange the annotations
            annotations.Sort((x, y) =>
            {
                // Special-case RequiredAttribute so that it shows up on top
                if (x.AnnotationAttribute is RequiredAttribute)
                {
                    return -1;
                }
                if (y.AnnotationAttribute is RequiredAttribute)
                {
                    return 1;
                }

                // Sort the rest based on alphabetic order of the doreplacedentation
                return String.Compare(x.Doreplacedentation, y.Doreplacedentation, StringComparison.OrdinalIgnoreCase);
            });

            foreach (ParameterAnnotation annotation in annotations)
            {
                propertyModel.Annotations.Add(annotation);
            }
        }

19 Source : SitemapMiddleware.cs
with MIT License
from anteatergames

private string CheckMethod(Type controller, MethodInfo method)
        {
            bool isPost = method.CustomAttributes.Any(x => x.AttributeType == typeof(HttpPostAttribute));
            bool isDelete = method.CustomAttributes.Any(x => x.AttributeType == typeof(HttpDeleteAttribute));
            bool isPut = method.CustomAttributes.Any(x => x.AttributeType == typeof(HttpPutAttribute));

            RouteAttribute routeAttribute = method.GetCustomAttributes<RouteAttribute>().FirstOrDefault();

            bool hasParameter = routeAttribute != null && !routeAttribute.Template.Contains("{");
            string routeTemplate = routeAttribute != null ? routeAttribute.Template.Trim('/') : string.Empty;

            string actionName = method.Name.ToLower();

            return CheckMethod(controller, actionName, isPost, isDelete, isPut, hasParameter, routeTemplate);
        }

19 Source : NetCoreForceModelGeneratorNamingConvention.cs
with MIT License
from anthonyreilly

public bool IgnoreProperty(PropertyInfo property)
        {
            return property.GetCustomAttributes<JsonIgnoreAttribute>().Any();
        }

19 Source : MBOv1SettingsPropertyDiscoverer.cs
with MIT License
from Aragas

private static IEnumerable<ISettingsPropertyDefinition> GetPropertiesInternal(object @object)
        {
            var type = @object.GetType();

            var subGroupDelimiter = AccessTools2.Property(type, "SubGroupDelimiter")?.GetValue(@object) as char? ?? '/';

            foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                if (property.Name == nameof(v1::MBOptionScreen.Settings.SettingsBase.Id))
                    continue;
                if (property.Name == nameof(v1::MBOptionScreen.Settings.SettingsBase.ModName))
                    continue;
                if (property.Name == nameof(v1::MBOptionScreen.Settings.SettingsBase.ModuleFolderName))
                    continue;
                if (property.Name == nameof(v1::MBOptionScreen.Settings.SettingsBase.UIVersion))
                    continue;
                if (property.Name == nameof(v1::MBOptionScreen.Settings.SettingsBase.SubFolder))
                    continue;

                var attributes = property.GetCustomAttributes().ToList();

                object? groupAttrObj = attributes.SingleOrDefault(a => a is v1::MBOptionScreen.Attributes.SettingPropertyGroupAttribute);
                var groupDefinition = groupAttrObj is not null
                    ? new MBOPropertyGroupDefinitionWrapper(groupAttrObj)
                    : SettingPropertyGroupAttribute.Default;

                var propertyDefinitions = new List<IPropertyDefinitionBase>();

                var propertyDefinitionWrappers = GetPropertyDefinitionWrappers(attributes).ToList();
                if (propertyDefinitionWrappers.Count > 0)
                {
                    propertyDefinitions.AddRange(propertyDefinitionWrappers);

                    if (groupDefinition is MBOPropertyGroupDefinitionWrapper { IsMainToggle: true })
                        propertyDefinitions.Add(new AttributePropertyDefinitionGroupToggleWrapper(propertyDefinitions[0]));
                }

                if (propertyDefinitions.Count > 0)
                {
                    yield return new SettingsPropertyDefinition(propertyDefinitions,
                        groupDefinition,
                        new PropertyRef(property, @object),
                        subGroupDelimiter);
                }
            }
        }

19 Source : MBOv2SettingsPropertyDiscoverer.cs
with MIT License
from Aragas

private static IEnumerable<ISettingsPropertyDefinition> GetPropertiesInternal(object @object)
        {
            var type = @object.GetType();

            var subGroupDelimiter = AccessTools2.Property(type, "SubGroupDelimiter")?.GetValue(@object) as char? ?? '/';

            foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                if (property.Name == nameof(v2::MBOptionScreen.Settings.SettingsBase.Id))
                    continue;
                if (property.Name == nameof(v2::MBOptionScreen.Settings.SettingsBase.ModName))
                    continue;
                if (property.Name == nameof(v2::MBOptionScreen.Settings.SettingsBase.ModuleFolderName))
                    continue;
                if (property.Name == nameof(v2::MBOptionScreen.Settings.SettingsBase.UIVersion))
                    continue;
                if (property.Name == nameof(v2::MBOptionScreen.Settings.SettingsBase.SubFolder))
                    continue;
                if (property.Name == nameof(v2::MBOptionScreen.Settings.SettingsBase.Format))
                    continue;

                var attributes = property.GetCustomAttributes().ToList();

                object? groupAttrObj = attributes.SingleOrDefault(a => a is v2::MBOptionScreen.Settings.IPropertyGroupDefinition);
                var groupDefinition = groupAttrObj is not null
                    ? new MBOPropertyGroupDefinitionWrapper(groupAttrObj)
                    : SettingPropertyGroupAttribute.Default;

                var propertyDefinitions = new List<IPropertyDefinitionBase>();

                var propertyDefinitionWrappers = GetPropertyDefinitionWrappers(attributes).ToList();
                if (propertyDefinitionWrappers.Count > 0)
                {
                    propertyDefinitions.AddRange(propertyDefinitionWrappers);

                    if (groupDefinition is MBOPropertyGroupDefinitionWrapper { IsMainToggle: true })
                        propertyDefinitions.Add(new AttributePropertyDefinitionGroupToggleWrapper(propertyDefinitions[0]));
                }

                if (propertyDefinitions.Count > 0)
                {
                    yield return new SettingsPropertyDefinition(propertyDefinitions,
                        groupDefinition,
                        new PropertyRef(property, @object),
                        subGroupDelimiter);
                }
            }
        }

19 Source : MCMv3SettingsPropertyDiscoverer.cs
with MIT License
from Aragas

private static IEnumerable<ISettingsPropertyDefinition> GetPropertiesInternal(object @object)
        {
            var type = @object.GetType();

            var subGroupDelimiter = AccessTools2.Property(type, "SubGroupDelimiter")?.GetValue(@object) as char? ?? '/';

            foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                if (property.Name == nameof(v3::MCM.Abstractions.Settings.Base.BaseSettings.Id))
                    continue;
                if (property.Name == nameof(v3::MCM.Abstractions.Settings.Base.BaseSettings.DisplayName))
                    continue;
                if (property.Name == nameof(v3::MCM.Abstractions.Settings.Base.BaseSettings.FolderName))
                    continue;
                if (property.Name == nameof(v3::MCM.Abstractions.Settings.Base.BaseSettings.Format))
                    continue;
                if (property.Name == nameof(v3::MCM.Abstractions.Settings.Base.BaseSettings.SubFolder))
                    continue;
                if (property.Name == nameof(v3::MCM.Abstractions.Settings.Base.BaseSettings.UIVersion))
                    continue;

                var attributes = property.GetCustomAttributes().ToList();

                object? groupAttrObj = attributes.SingleOrDefault(a => a is v3::MCM.Abstractions.Settings.Definitions.IPropertyGroupDefinition);
                var groupDefinition = groupAttrObj is not null
                    ? new MCMv3PropertyGroupDefinitionWrapper(groupAttrObj)
                    : SettingPropertyGroupAttribute.Default;

                var propertyDefinitions = new List<IPropertyDefinitionBase>();

                var propertyDefinitionWrappers = GetPropertyDefinitionWrappers(attributes).ToList();
                if (propertyDefinitionWrappers.Count > 0)
                {
                    propertyDefinitions.AddRange(propertyDefinitionWrappers);

                    if (groupDefinition is MCMv3PropertyGroupDefinitionWrapper { IsMainToggle: true })
                        propertyDefinitions.Add(new AttributePropertyDefinitionGroupToggleWrapper(propertyDefinitions[0]));
                }

                if (propertyDefinitions.Count > 0)
                {
                    yield return new SettingsPropertyDefinition(propertyDefinitions,
                        groupDefinition,
                        new PropertyRef(property, @object),
                        subGroupDelimiter);
                }
            }
        }

19 Source : ModLibSettingsPropertyDiscoverer.cs
with MIT License
from Aragas

private static IEnumerable<ISettingsPropertyDefinition> GetPropertiesInternal(object @object)
        {
            var type = @object.GetType();

            const char subGroupDelimiter = '/';

            foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                if (property.Name == nameof(v1::ModLib.SettingsBase.ID))
                    continue;
                if (property.Name == nameof(v1::ModLib.SettingsBase.ModName))
                    continue;
                if (property.Name == nameof(v1::ModLib.SettingsBase.ModuleFolderName))
                    continue;
                if (property.Name == nameof(v1::ModLib.SettingsBase.SubFolder))
                    continue;

                var attributes = property.GetCustomAttributes().ToList();

                object? groupAttrObj = attributes.Find(a => a is v1::ModLib.Attributes.SettingPropertyGroupAttribute);
                var groupDefinition = groupAttrObj is not null
                    ? new ModLibPropertyGroupDefinitionWrapper(groupAttrObj)
                    : SettingPropertyGroupAttribute.Default;

                var propertyDefinitions = new List<IPropertyDefinitionBase>();

                var propertyDefinitionWrappers = GetPropertyDefinitionWrappers(attributes).ToList();
                if (propertyDefinitionWrappers.Count > 0)
                {
                    propertyDefinitions.AddRange(propertyDefinitionWrappers);

                    if (groupDefinition is ModLibPropertyGroupDefinitionWrapper { IsMainToggle: true })
                        propertyDefinitions.Add(new AttributePropertyDefinitionGroupToggleWrapper(propertyDefinitions[0]));
                }

                if (propertyDefinitions.Count > 0)
                {
                    yield return new SettingsPropertyDefinition(propertyDefinitions,
                        groupDefinition,
                        new PropertyRef(property, @object),
                        subGroupDelimiter);
                }
            }
        }

19 Source : ModLibDefinitionsSettingsPropertyDiscoverer.cs
with MIT License
from Aragas

private static IEnumerable<ISettingsPropertyDefinition> GetPropertiesInternal(object @object)
        {
            var type = @object.GetType();

            const char subGroupDelimiter = '/';

            foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                if (property.Name == nameof(v13::ModLib.Definitions.SettingsBase.ID))
                    continue;
                if (property.Name == nameof(v13::ModLib.Definitions.SettingsBase.ModName))
                    continue;
                if (property.Name == nameof(v13::ModLib.Definitions.SettingsBase.ModuleFolderName))
                    continue;
                if (property.Name == nameof(v13::ModLib.Definitions.SettingsBase.SubFolder))
                    continue;

                var attributes = property.GetCustomAttributes().ToList();

                object? groupAttrObj = attributes.Find(a => a is v13::ModLib.Definitions.Attributes.SettingPropertyGroupAttribute);
                var groupDefinition = groupAttrObj is not null
                    ? new ModLibDefinitionsPropertyGroupDefinitionWrapper(groupAttrObj)
                    : SettingPropertyGroupAttribute.Default;

                var propertyDefinitions = new List<IPropertyDefinitionBase>();

                var propertyDefinitionWrappers = GetPropertyDefinitionWrappers(attributes).ToList();
                if (propertyDefinitionWrappers.Count > 0)
                {
                    propertyDefinitions.AddRange(propertyDefinitionWrappers);

                    if (groupDefinition is ModLibDefinitionsPropertyGroupDefinitionWrapper { IsMainToggle: true })
                        propertyDefinitions.Add(new AttributePropertyDefinitionGroupToggleWrapper(propertyDefinitions[0]));
                }

                if (propertyDefinitions.Count > 0)
                {
                    yield return new SettingsPropertyDefinition(propertyDefinitions,
                        groupDefinition,
                        new PropertyRef(property, @object),
                        subGroupDelimiter);
                }
            }
        }

19 Source : AttributeSettingsPropertyDiscoverer.cs
with MIT License
from Aragas

private static IEnumerable<ISettingsPropertyDefinition> GetPropertiesInternal(object @object)
        {
            var type = @object.GetType();
            var subGroupDelimiter = AccessTools2.Property(type, "SubGroupDelimiter")?.GetValue(@object) as char? ?? '/';
            foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                if (property.Name == nameof(BaseSettings.Id))
                    continue;
                if (property.Name == nameof(BaseSettings.DisplayName))
                    continue;
                if (property.Name == nameof(BaseSettings.FolderName))
                    continue;
                if (property.Name == nameof(BaseSettings.FormatType))
                    continue;
                if (property.Name == nameof(BaseSettings.SubFolder))
                    continue;
                if (property.Name == nameof(BaseSettings.UIVersion))
                    continue;

                var attributes = property.GetCustomAttributes().ToList();

                object? groupAttrObj = attributes.SingleOrDefault(a => a is IPropertyGroupDefinition);
                var groupDefinition = groupAttrObj is not null
                    ? new PropertyGroupDefinitionWrapper(groupAttrObj)
                    : SettingPropertyGroupAttribute.Default;

                var propertyDefinitions = SettingsUtils.GetPropertyDefinitionWrappers(attributes).ToList();
                if (propertyDefinitions.Count > 0)
                {
                    yield return new SettingsPropertyDefinition(propertyDefinitions,
                        groupDefinition,
                        new PropertyRef(property, @object),
                        subGroupDelimiter);
                }
            }
        }

19 Source : TypeExtensions.cs
with MIT License
from arbelatech

public static bool HasAttribute<TAttr>(this Type type, Func<TAttr, bool> predicate) where TAttr:Attribute
        {
            return type.GetCustomAttributes<TAttr>()
                .Any(predicate);
        }

19 Source : BaseEndpointClient.cs
with MIT License
from Archomeda

private IReadOnlyList<T> GetAttributes<T>() where T : Attribute =>
            this.GetType().GetCustomAttributes<T>().ToList();

19 Source : CastableTypeConverter.cs
with MIT License
from Archomeda

public override bool CanConvert(Type typeToConvert)
        {
            bool hasInterface = typeToConvert.GetInterfaces()
                .Where(i => i.IsGenericType)
                .Any(i => i.GetGenericTypeDefinition() == typeof(ICastableType<,>) && i.GetGenericArguments()[1].IsEnum);
            bool hasAttributes = typeToConvert.GetCustomAttributes<CastableTypeAttribute>().Any();
            return hasInterface && hasAttributes;
        }

19 Source : MainResolver.cs
with MIT License
from areller

public void AddResolver(Type type, Type proxy)
        {
            var typeInfo = type.GetTypeInfo();
            var proxyTypeInfo = proxy.GetTypeInfo();

            if (typeInfo.GenericTypeParameters.Length != proxyTypeInfo.GenericTypeParameters.Length)
            {
                throw new Exception("Base type and proxy must have the same type parameters");
            }

            var paramsOrdinal = Enumerable.Range(0, proxyTypeInfo.GenericTypeParameters.Length)
                .Select(i => (i, proxyTypeInfo.GenericTypeParameters[i]))
                .ToDictionary(p => p.Item2.Name, p => p.i);

            var dataTypeAttr = proxy.GetCustomAttributes()
                .FirstOrDefault(attr => attr is RedILDataType) as RedILDataType;
            var dataType = DataValueType.Unknown;
            if (!(dataTypeAttr is null))
            {
                dataType = dataTypeAttr.Type;
            }

            RedILValueResolver valueResolver = null;
            var valueResolveAttr = proxy.GetCustomAttributes()
                .FirstOrDefault(attr => attr is RedILResolve) as RedILResolve;
            if (!(valueResolveAttr is null))
            {
                valueResolver = valueResolveAttr.CreateValueResolver();
            }

            var constructors = new List<Constructor>();
            var instanceMethods = new List<Method>();
            var instanceMembers = new List<Member>();
            var staticMethods = new List<Method>();
            var staticMembers = new List<Member>();

            foreach (var ctor in proxy.GetConstructors())
            {
                var resolveAttr = ctor.GetCustomAttributes()
                    .FirstOrDefault(attr => attr is RedILResolve) as RedILResolve;

                if (resolveAttr is null)
                {
                    continue;
                }

                var signature = ctor.GetParameters()
                    .Select(param => param.ParameterType).ToArray();

                var resolver = resolveAttr.CreateObjectResolver();
                constructors.Add(new Constructor()
                {
                    Signature = signature,
                    Resolver = resolver
                });
            }

            foreach (var method in proxy.GetMethods())
            {
                var resolveAttr = method.GetCustomAttributes()
                    .FirstOrDefault(attr => attr is RedILResolve) as RedILResolve;

                if (resolveAttr is null)
                {
                    continue;
                }

                var signature = method.GetParameters()
                    .Select(param => param.ParameterType).ToArray();

                var resolver = resolveAttr.CreateMethodResolver();
                (method.IsStatic ? staticMethods : instanceMethods).Add(new Method()
                {
                    Name = method.Name,
                    Signature = signature,
                    Resolver = resolver
                });
            }

            foreach (var member in proxy.GetProperties())
            {
                var resolveAttr = member.GetCustomAttributes()
                    .FirstOrDefault(attr => attr is RedILResolve) as RedILResolve;

                if (resolveAttr is null)
                {
                    continue;
                }

                var resolver = resolveAttr.CreateMemberResolver();
                (member.GetAccessors().First().IsStatic ? staticMembers : instanceMembers).Add(new Member()
                {
                    Name = member.Name,
                    Resolver = resolver
                });
            }

            if (proxy.IsEnum)
            {
                foreach (var enumName in proxy.GetEnumNames())
                {
                    var field = proxy.GetField(enumName);
                    var resolveAttr = field?.GetCustomAttributes()
                        ?.FirstOrDefault(attr => attr is RedILResolve) as RedILResolve;

                    if (resolveAttr is null)
                    {
                        continue;
                    }

                    var resolver = resolveAttr.CreateMemberResolver();
                    staticMembers.Add(new Member()
                    {
                        Name = enumName,
                        Resolver = resolver
                    });
                }
            }

            _typeDefs.Add(type.FullName, new TypeDefinition()
            {
                DataType = dataType,
                ValueResolver = valueResolver,
                ParametersOrdinal = paramsOrdinal,
                Constructors = constructors.GroupBy(c => c.Signature.Length).ToDictionary(g => g.Key, g => g.ToList()),
                InstanceMethods = instanceMethods.GroupBy(m => (m.Name, m.Signature.Length)).ToDictionary(g => g.Key, g => g.ToList()),
                InstanceMembers = instanceMembers.ToDictionary(m => m.Name, m => m),
                StaticMethods = staticMethods.GroupBy(m => (m.Name, m.Signature.Length)).ToDictionary(g => g.Key, g => g.ToList()),
                StaticMembers = staticMembers.ToDictionary(m => m.Name, m => m)
            });
        }

19 Source : ToolboxPropertyHandler.cs
with MIT License
from arimger

private void ProcessBuiltInData()
        {
            //arrays cannot have custom built-in property drawers
            if (isArray)
            {
                return;
            }

            //check if this property has built-in property drawer
            if (!(hasBuiltInPropertyDrawer = ToolboxDrawerModule.HasNativeTypeDrawer(type)))
            {
                var propertyAttributes = fieldInfo.GetCustomAttributes<PropertyAttribute>();
                foreach (var attribute in propertyAttributes)
                {
                    var attributeType = attribute.GetType();
                    if (hasBuiltInPropertyDrawer = ToolboxDrawerModule.HasNativeTypeDrawer(attributeType))
                    {
                        break;
                    }
                }
            }
        }

19 Source : ToolboxPropertyHandler.cs
with MIT License
from arimger

private void ProcessToolboxData()
        {
            //get all possible attributes and handle each directly by type
            var attributes = fieldInfo.GetCustomAttributes<ToolboxAttribute>();
            foreach (var attribute in attributes)
            {
                HandleNewAttribute(attribute);
            }

            //check if property has a custom attribute or target type drawer
            hasToolboxPropertyreplacedignableDrawer = propertyAttribute != null;
            hasToolboxPropertyTargetTypeDrawer = ToolboxDrawerModule.HasTargetTypeDrawer(type);
            //check if property has any of it and cache value
            hasToolboxPropertyDrawer = hasToolboxPropertyreplacedignableDrawer ||
                                       hasToolboxPropertyTargetTypeDrawer;

            //check if property has custom decorators and keep them in order
            if (decoratorAttributes != null)
            {
                decoratorAttributes.Sort((a1, a2) => a1.Order.CompareTo(a2.Order));
                hasToolboxDecoratorDrawer = true;
            }

            //check if property has custom conditon drawer
            hasToolboxConditionDrawer = conditionAttribute != null;
        }

19 Source : AggregateHelper.cs
with MIT License
from ARKlab

private static string _getName() 
                => typeof(TEvent)
                .GetTypeInfo()
                .GetCustomAttributes<EventNameAttribute>().SingleOrDefault()?.Name 
                ?? typeof(TEvent).Name;

19 Source : AggregateHelper.cs
with MIT License
from ARKlab

private static string _getName()
        {
            return typeof(TAggregate)
                .GetTypeInfo()
                .GetCustomAttributes<AggregateNameAttribute>().SingleOrDefault()?.Name
                ?? typeof(TAggregate).Name;
        }

19 Source : Program.cs
with GNU Affero General Public License v3.0
from arklumpus

static async Task Main(string[] args)
        {
            ConsoleColor defaultBackground = Console.BackgroundColor;
            ConsoleColor defaultForeground = Console.ForegroundColor;

            Console.WriteLine();
            Console.WriteLine("MuPDFCore test suite");
            Console.WriteLine();
            Console.WriteLine("Loading tests...");

            replacedembly testreplacedembly = replacedembly.Getreplacedembly(typeof(MuPDFWrapperTests));

            Type[] types = testreplacedembly.GetTypes();

            List<(string, Func<Task>)> tests = new List<(string, Func<Task>)>();
            HashSet<string> filesToDeploy = new HashSet<string>();

            for (int i = 0; i < types.Length; i++)
            {
                bool found = false;

                Attribute[] typeAttributes = Attribute.GetCustomAttributes(types[i]);

                foreach (Attribute attr in typeAttributes)
                {
                    if (attr is TestClreplacedAttribute)
                    {
                        found = true;
                        break;
                    }
                }

                if (found)
                {
                    MethodInfo[] methods = types[i].GetMethods(BindingFlags.Public | BindingFlags.Instance);

                    foreach (MethodInfo method in methods)
                    {
                        bool foundMethod = false;

                        foreach (Attribute attr in method.GetCustomAttributes())
                        {
                            if (attr is TestMethodAttribute)
                            {
                                foundMethod = true;
                            }

                            if (attr is DeploymenreplacedemAttribute dia)
                            {
                                filesToDeploy.Add(dia.Path);
                            }
                        }

                        if (foundMethod)
                        {
                            Type type = types[i];

                            tests.Add((types[i].Name + "." + method.Name, async () =>
                            {
                                object obj = Activator.CreateInstance(type);
                                object returnValue = method.Invoke(obj, null);

                                if (returnValue is Task task)
                                {
                                    await task;
                                }
                            }
                            ));
                        }
                    }
                }
            }

            int longestTestNameLength = (from el in tests select el.Item1.Length).Max();

            Console.WriteLine();
            Console.BackgroundColor = ConsoleColor.Blue;
            Console.Write("  Found {0} tests.  ", tests.Count.ToString());
            Console.BackgroundColor = defaultBackground;
            Console.WriteLine();
            Console.WriteLine();

            Console.WriteLine("{0} files will be deployed:", filesToDeploy.Count.ToString());

            foreach (string sr in filesToDeploy)
            {
                Console.WriteLine("    " + sr);
            }

            Console.WriteLine();

            string deploymentPath = Path.GetTempFileName();
            File.Delete(deploymentPath);
            Directory.CreateDirectory(deploymentPath);

            foreach (string sr in filesToDeploy)
            {
                File.Copy(sr, Path.Combine(deploymentPath, Path.GetFileName(sr)));
            }

            string originalCurrentDirectory = Directory.GetCurrentDirectory();
            Directory.SetCurrentDirectory(deploymentPath);

            Console.WriteLine("Deployment completed.");
            Console.WriteLine();
            Console.WriteLine("Running tests...");
            Console.WriteLine();

            List<(string, Func<Task>)> failedTests = new List<(string, Func<Task>)>();

            for (int i = 0; i < tests.Count; i++)
            {
                Console.Write(tests[i].Item1 + new string(' ', longestTestNameLength - tests[i].Item1.Length + 1));

                bool failed = false;

                Stopwatch sw = Stopwatch.StartNew();

                try
                {
                    await tests[i].Item2();
                    sw.Stop();
                }
                catch (Exception ex)
                {
                    sw.Stop();
                    failed = true;
                    failedTests.Add(tests[i]);

                    Console.BackgroundColor = ConsoleColor.Red;
                    Console.Write("   Failed    ");
                    Console.BackgroundColor = defaultBackground;

                    Console.Write("    {0}ms", sw.ElapsedMilliseconds.ToString());

                    Console.WriteLine();

                    while (ex.InnerException != null)
                    {
                        Console.WriteLine(ex.Message);
                        ex = ex.InnerException;
                    }

                    Console.WriteLine(ex.Message);
                }

                if (!failed)
                {
                    Console.BackgroundColor = ConsoleColor.Green;
                    Console.Write("  Succeeded  ");
                    Console.BackgroundColor = defaultBackground;
                    Console.Write("    {0}ms", sw.ElapsedMilliseconds.ToString());
                }

                Console.WriteLine();
            }

            Console.WriteLine();

            if (failedTests.Count < tests.Count)
            {
                Console.BackgroundColor = ConsoleColor.Green;
                Console.Write("  {0} tests succeeded  ", tests.Count - failedTests.Count);
                Console.BackgroundColor = defaultBackground;
                Console.WriteLine();
            }

            if (failedTests.Count > 0)
            {
                Console.BackgroundColor = ConsoleColor.Red;
                Console.Write("  {0} tests failed  ", failedTests.Count);
                Console.BackgroundColor = defaultBackground;
                Console.WriteLine();

                Console.WriteLine();
                Console.WriteLine("Failed tests:");
                Console.ForegroundColor = ConsoleColor.Red;

                for (int i= 0; i < failedTests.Count; i++)
                {
                    Console.WriteLine("    {0}", failedTests[i].Item1);
                }

                Console.WriteLine();
                Console.ForegroundColor = defaultForeground;

                Console.WriteLine();
                Console.WriteLine("The failed tests will now be repeated one by one.");

                for (int i = 0; i < failedTests.Count; i++)
                {
                    Console.WriteLine();
                    Console.WriteLine("Press any key to continue...");
                    Console.WriteLine();
                    Console.ReadKey();
                    Console.Write(failedTests[i].Item1 + new string(' ', longestTestNameLength - failedTests[i].Item1.Length + 1));

                    bool failed = false;

                    try
                    {
                        await failedTests[i].Item2();
                    }
                    catch (Exception ex)
                    {
                        failed = true;

                        Console.BackgroundColor = ConsoleColor.Red;
                        Console.Write("   Failed    ");
                        Console.BackgroundColor = defaultBackground;

                        Console.WriteLine();

                        while (ex.InnerException != null)
                        {
                            Console.WriteLine(ex.Message);
                            ex = ex.InnerException;
                        }

                        Console.WriteLine(ex.Message);
                    }

                    if (!failed)
                    {
                        Console.BackgroundColor = ConsoleColor.Green;
                        Console.Write("  Succeeded  ");
                        Console.BackgroundColor = defaultBackground;
                    }

                    Console.WriteLine();
                }
            }

            Directory.SetCurrentDirectory(originalCurrentDirectory);
            Directory.Delete(deploymentPath, true);
        }

19 Source : AuthorizationBehaviour.cs
with MIT License
from armanab

public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
        {
            var authorizeAttributes = request.GetType().GetCustomAttributes<AuthorizeAttribute>();

            if (authorizeAttributes.Any())
            {
                // Must be authenticated user
                if (_currentUserService.UserId != Guid.Empty)
                {
                    throw new UnauthorizedAccessException();
                }

                // Role-based authorization
                var authorizeAttributesWithRoles = authorizeAttributes.Where(a => !string.IsNullOrWhiteSpace(a.Roles));

                if (authorizeAttributesWithRoles.Any())
                {
                    foreach (var roles in authorizeAttributesWithRoles.Select(a => a.Roles.Split(',')))
                    {
                        var authorized = false;
                        foreach (var role in roles)
                        {
                            var isInRole = await _idenreplacedyService.IsInRoleAsync(_currentUserService.UserId, role.Trim());
                            if (isInRole)
                            {
                                authorized = true;
                                break;
                            }
                        }

                        // Must be a member of at least one role in roles
                        if (!authorized)
                        {
                            throw new ForbiddenAccessException();
                        }
                    }
                }

                // Policy-based authorization
                var authorizeAttributesWithPolicies = authorizeAttributes.Where(a => !string.IsNullOrWhiteSpace(a.Policy));
                if (authorizeAttributesWithPolicies.Any())
                {
                    foreach(var policy in authorizeAttributesWithPolicies.Select(a => a.Policy))
                    {
                        var authorized = await _idenreplacedyService.AuthorizeAsync(_currentUserService.UserId, policy);

                        if (!authorized)
                        {
                            throw new ForbiddenAccessException();
                        }
                    }
                }
            }

            // User is authorized / authorization not required
            return await next();
        }

19 Source : MediatrMvcFeatureProvider.cs
with MIT License
from Artem-Romanenia

private bool ShouldSkipInternal(IList<TypeInfo> controllers, Type requestType)
        {
            if (!_settings.DiscoverHandledRequestsByAttribute || !_settings.DiscoverHandledRequestsByActionParams)
                return false;

            foreach (var controller in controllers)
            {
                foreach (var action in controller.DeclaredMethods)
                {
                    if (_settings.DiscoverHandledRequestsByAttribute)
                    {
                        var attr = action.GetCustomAttributes().FirstOrDefault(a => a.GetType() == typeof(HandlesRequestAttribute)) as HandlesRequestAttribute;

                        if (attr != null && attr.RequestType == requestType)
                            return true;
                    }

                    if (_settings.DiscoverHandledRequestsByActionParams)
                    {
                        foreach (var param in action.GetParameters())
                        {
                            if (param.ParameterType == requestType)
                                return true;
                        }
                    }
                }
            }

            return false;
        }

See More Examples