System.Reflection.MemberInfo.GetCustomAttributes(System.Type, bool)

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

2492 Examples 7

19 View Source File : Frontend.cs
License : MIT License
Project Creator : 0x0ade

public override void Init(CelesteNetServerModuleWrapper wrapper) {
            base.Init(wrapper);

            Logger.Log(LogLevel.VVV, "frontend", "Scanning for endpoints");
            foreach (Type t in CelesteNetUtils.GetTypes()) {
                foreach (MethodInfo m in t.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) {
                    foreach (RCEndpointAttribute epa in m.GetCustomAttributes(typeof(RCEndpointAttribute), false)) {
                        RCEndpoint ep = epa.Data;
                        Logger.Log(LogLevel.VVV, "frontend", $"Found endpoint: {ep.Path} - {ep.Name} ({m.Name}::{t.FullName})");
                        ep.Handle = (f, c) => m.Invoke(null, new object[] { f, c });
                        EndPoints.Add(ep);
                    }
                }
            }

            Server.OnConnect += OnConnect;
            Server.OnSessionStart += OnSessionStart;
            using (Server.ConLock.R())
                foreach (CelesteNetPlayerSession session in Server.Sessions)
                    session.OnEnd += OnSessionEnd;
            Server.OnDisconnect += OnDisconnect;

            Server.Channels.OnBroadcastList += OnBroadcastChannels;

            ChatModule chat = Server.Get<ChatModule>();
            chat.OnReceive += OnChatReceive;
            chat.OnForceSend += OnForceSend;
        }

19 View Source File : DbMetaInfoProvider.cs
License : Apache License 2.0
Project Creator : 1448376744

public DbTableMetaInfo GetTable(Type type)
        {
            return _tables.GetOrAdd(type, t =>
            {
                var name = t.Name;
                if (t.GetCustomAttributes(typeof(TableAttribute), true).FirstOrDefault() != null)
                {
                    var attribute = t.GetCustomAttributes(typeof(TableAttribute), true)
                        .FirstOrDefault() as TableAttribute;
                    name = attribute.Name;
                }
                var table = new DbTableMetaInfo()
                {
                    TableName = name,
                    CsharpName = t.Name
                };
                return table;
            });
        }

19 View Source File : DbMetaInfoProvider.cs
License : Apache License 2.0
Project Creator : 1448376744

public List<DbColumnMetaInfo> GetColumns(Type type)
        {
            return _columns.GetOrAdd(type, t =>
            {
                var list = new List<DbColumnMetaInfo>();
                var properties = type.GetProperties();
                foreach (var item in properties)
                {
                    var columnName = item.Name;
                    var isPrimaryKey = false;
                    var isDefault = false;
                    var isIdenreplacedy = false;
                    var isNotMapped = false;
                    var isConcurrencyCheck = false;
                    var isComplexType = false;
                    if (item.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault() != null)
                    {
                        var attribute = item.GetCustomAttributes(typeof(ColumnAttribute), true)
                            .FirstOrDefault() as ColumnAttribute;
                        columnName = attribute.Name;
                    }
                    if (item.GetCustomAttributes(typeof(PrimaryKeyAttribute), true).FirstOrDefault() != null)
                    {
                        isPrimaryKey = true;
                    }
                    if (item.GetCustomAttributes(typeof(IdenreplacedyAttribute), true).FirstOrDefault() != null)
                    {
                        isIdenreplacedy = true;
                    }
                    if (item.GetCustomAttributes(typeof(DefaultAttribute), true).FirstOrDefault() != null)
                    {
                        isDefault = true;
                    }
                    if (item.GetCustomAttributes(typeof(ConcurrencyCheckAttribute), true).FirstOrDefault() != null)
                    {
                        isConcurrencyCheck = true;
                    }
                    if (item.GetCustomAttributes(typeof(NotMappedAttribute), true).FirstOrDefault() != null)
                    {
                        isNotMapped = true;
                    }
                    if (item.GetCustomAttributes(typeof(ComplexTypeAttribute), true).FirstOrDefault() != null)
                    {
                        isComplexType = true;
                    }
                    list.Add(new DbColumnMetaInfo()
                    {
                        CsharpType = item.PropertyType,
                        IsDefault = isDefault,
                        ColumnName = columnName,
                        CsharpName = item.Name,
                        IsPrimaryKey = isPrimaryKey,
                        IsIdenreplacedy = isIdenreplacedy,
                        IsNotMapped = isNotMapped,
                        IsConcurrencyCheck = isConcurrencyCheck,
                        IsComplexType = isComplexType
                    });
                }
                return list;
            });
        }

19 View Source File : EnumExtensions.cs
License : MIT License
Project Creator : 17MKH

public static string ToDescription(this Enum value)
    {
        var type = value.GetType();
        var info = type.GetField(value.ToString());
        var key = type.FullName + info.Name;
        if (!DescriptionCache.TryGetValue(key, out string desc))
        {
            var attrs = info.GetCustomAttributes(typeof(DescriptionAttribute), true);
            if (attrs.Length < 1)
                desc = string.Empty;
            else
                desc = attrs[0] is DescriptionAttribute
                    descriptionAttribute
                    ? descriptionAttribute.Description
                    : value.ToString();

            DescriptionCache.TryAdd(key, desc);
        }

        return desc;
    }

19 View Source File : EventManager.cs
License : MIT License
Project Creator : 404Lcc

public void InitManager()
        {
            foreach (Type item in Manager.Instance.types.Values)
            {
                if (item.IsAbstract) continue;
                EventHandlerAttribute[] eventHandlerAttributes = (EventHandlerAttribute[])item.GetCustomAttributes(typeof(EventHandlerAttribute), false);
                if (eventHandlerAttributes.Length > 0)
                {
                    IEvent iEvent = (IEvent)Activator.CreateInstance(item);
                    events.Add(iEvent.EventType(), iEvent);
                }
            }
        }

19 View Source File : NumericEventManager.cs
License : MIT License
Project Creator : 404Lcc

public void InitManager()
        {
            foreach (Type item in Manager.Instance.types.Values)
            {
                if (item.IsAbstract) continue;
                NumericEventHandlerAttribute[] numericEventHandlerAttributes = (NumericEventHandlerAttribute[])item.GetCustomAttributes(typeof(NumericEventHandlerAttribute), false);
                foreach (NumericEventHandlerAttribute numericEventHandlerAttributeItem in numericEventHandlerAttributes)
                {
                    INumericEvent iNumericEvent = (INumericEvent)Activator.CreateInstance(item);
                    if (!numericEvents.ContainsKey(numericEventHandlerAttributeItem.numericType))
                    {
                        numericEvents.Add(numericEventHandlerAttributeItem.numericType, new List<INumericEvent>());
                    }
                    ((List<INumericEvent>)numericEvents[numericEventHandlerAttributeItem.numericType]).Add(iNumericEvent);
                }
            }
        }

19 View Source File : UIEventManager.cs
License : MIT License
Project Creator : 404Lcc

public void InitManager()
        {
            foreach (Type item in Manager.Instance.types.Values)
            {
                if (item.IsAbstract) continue;
                UIEventHandlerAttribute[] uiEventHandlerAttributes = (UIEventHandlerAttribute[])item.GetCustomAttributes(typeof(UIEventHandlerAttribute), false);
                if (uiEventHandlerAttributes.Length > 0)
                {
                    UIEvent uiEvent = (UIEvent)Activator.CreateInstance(item);
                    uiEvents.Add(uiEventHandlerAttributes[0].uiEventType, uiEvent);
                }
            }
        }

19 View Source File : ConfigManager.cs
License : MIT License
Project Creator : 404Lcc

public void InitManager()
        {
            foreach (Type item in Manager.Instance.types.Values)
            {
                if (item.IsAbstract) continue;
                ConfigAttribute[] configAttributes = (ConfigAttribute[])item.GetCustomAttributes(typeof(ConfigAttribute), false);
                if (configAttributes.Length > 0)
                {
                    Textreplacedet replacedet = replacedetManager.Instance.Loadreplacedet<Textreplacedet>(item.Name, ".bytes", false, false, replacedetType.Config);
                    object obj = ProtobufUtil.Deserialize(item, replacedet.bytes, 0, replacedet.bytes.Length);
                    configs.Add(item, obj);
                }
            }
        }

19 View Source File : ConfigManager.cs
License : MIT License
Project Creator : 404Lcc

public void InitManager()
        {
            foreach (Type item in Manager.Instance.types.Values)
            {
                if (item.IsAbstract) continue;
                ConfigAttribute[] configAttributes = (ConfigAttribute[])item.GetCustomAttributes(typeof(ConfigAttribute), false);
                if (configAttributes.Length > 0)
                {
                    Textreplacedet replacedet = replacedetManager.Instance.Loadreplacedet<Textreplacedet>(item.Name, ".bytes", false, true, replacedetType.Config);
                    object obj = ProtobufUtil.Deserialize(item, replacedet.bytes, 0, replacedet.bytes.Length);
                    configs.Add(item, obj);
                }
            }
        }

19 View Source File : JsonExtension.cs
License : MIT License
Project Creator : 4egod

public static string ToEnumString<T>(this T type)
        {
            var enumType = typeof (T);
            var name = Enum.GetName(enumType, type);
            var enumMemberAttribute = ((EnumMemberAttribute[])enumType.GetField(name).GetCustomAttributes(typeof(EnumMemberAttribute), true)).Single();
            return enumMemberAttribute.Value;
        }

19 View Source File : JsonExtension.cs
License : MIT License
Project Creator : 4egod

public static T ToEnum<T>(this string str)
        {
            var enumType = typeof(T);
            foreach (var name in Enum.GetNames(enumType))
            {
                var enumMemberAttribute = ((EnumMemberAttribute[])enumType.GetField(name).GetCustomAttributes(typeof(EnumMemberAttribute), true)).Single();
                if (enumMemberAttribute.Value == str) return (T)Enum.Parse(enumType, name);
            }
            //throw exception or whatever handling you want or
            return default(T);
        }

19 View Source File : EnumExtensions.cs
License : MIT License
Project Creator : 52ABP

public static string ToEnumDescriptionString(this short value, Type enumType)
        {
            var nvc = new NameValueCollection();
            var typeDescription = typeof (DescriptionAttribute);
            var fields = enumType.GetFields();
            var strText = string.Empty;
            var strValue = string.Empty;
            foreach (var field in fields)
            {
                if (field.FieldType.IsEnum)
                {
                    strValue =
                        ((int) enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString();
                    var arr = field.GetCustomAttributes(typeDescription, true);
                    if (arr.Length > 0)
                    {
                        var aa = (DescriptionAttribute) arr[0];
                        strText = aa.Description;
                    }
                    else
                    {
                        strText = "";
                    }
                    nvc.Add(strValue, strText);
                }
            }
            return nvc[value.ToString()];
        }

19 View Source File : TypeExtensions.cs
License : MIT License
Project Creator : 52ABP

public static bool AttributeExists<T>(this MemberInfo memberInfo, bool inherit = false) where T : Attribute
        {
            return memberInfo.GetCustomAttributes(typeof (T), inherit).Any(m => m as T != null);
        }

19 View Source File : TypeExtensions.cs
License : MIT License
Project Creator : 52ABP

public static T GetAttribute<T>(this MemberInfo memberInfo, bool inherit = false) where T : Attribute
        {
            var descripts = memberInfo.GetCustomAttributes(typeof (T), inherit);
            return descripts.FirstOrDefault() as T;
        }

19 View Source File : TypeExtensions.cs
License : MIT License
Project Creator : 52ABP

public static T[] GetAttributes<T>(this MemberInfo memberInfo, bool inherit = false) where T : Attribute
        {
            return memberInfo.GetCustomAttributes(typeof (T), inherit).Cast<T>().ToArray();
        }

19 View Source File : Server.cs
License : MIT License
Project Creator : 5minlab

private void RegisterRoutes() {
            if (registeredRoutes == null) {
                registeredRoutes = new List<RouteAttribute>();

                foreach (replacedembly replacedembly in AppDomain.CurrentDomain.Getreplacedemblies()) {
                    foreach (Type type in replacedembly.GetTypes()) {
                        // FIXME add support for non-static methods (FindObjectByType?)
                        foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.Static)) {
                            RouteAttribute[] attrs = method.GetCustomAttributes(typeof(RouteAttribute), true) as RouteAttribute[];
                            if (attrs.Length == 0)
                                continue;

                            RouteAttribute.Callback cbm = Delegate.CreateDelegate(typeof(RouteAttribute.Callback), method, false) as RouteAttribute.Callback;
                            if (cbm == null) {
                                Debug.LogError(string.Format("Method {0}.{1} takes the wrong arguments for a console route.", type, method.Name));
                                continue;
                            }

                            // try with a bare action
                            foreach (RouteAttribute route in attrs) {
                                if (route.m_route == null) {
                                    Debug.LogError(string.Format("Method {0}.{1} needs a valid route regexp.", type, method.Name));
                                    continue;
                                }

                                route.m_callback = cbm;
                                registeredRoutes.Add(route);
                            }
                        }
                    }
                }
                RegisterFileHandlers();
            }
        }

19 View Source File : Shell.cs
License : MIT License
Project Creator : 5minlab

private void RegisterAttributes() {
#if !NETFX_CORE
            foreach (replacedembly replacedembly in AppDomain.CurrentDomain.Getreplacedemblies()) {
                // HACK: IL2CPP crashes if you attempt to get the methods of some clreplacedes in these replacedemblies.
                if (replacedembly.FullName.StartsWith("System") || replacedembly.FullName.StartsWith("mscorlib")) {
                    continue;
                }
                foreach (Type type in replacedembly.GetTypes()) {
                    // FIXME add support for non-static methods (FindObjectByType?)
                    foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.Static)) {
                        CommandAttribute[] attrs = method.GetCustomAttributes(typeof(CommandAttribute), true) as CommandAttribute[];
                        if (attrs.Length == 0)
                            continue;

                        CommandAttribute.Callback cb = Delegate.CreateDelegate(typeof(CommandAttribute.Callback), method, false) as CommandAttribute.Callback;
                        if (cb == null) {
                            CommandAttribute.CallbackSimple cbs = Delegate.CreateDelegate(typeof(CommandAttribute.CallbackSimple), method, false) as CommandAttribute.CallbackSimple;
                            if (cbs != null) {
                                cb = delegate (string[] args) {
                                    cbs();
                                };
                            }
                        }

                        if (cb == null) {
                            Debug.LogError(string.Format("Method {0}.{1} takes the wrong arguments for a console command.", type, method.Name));
                            continue;
                        }

                        // try with a bare action
                        foreach (CommandAttribute cmd in attrs) {
                            if (string.IsNullOrEmpty(cmd.m_command)) {
                                Debug.LogError(string.Format("Method {0}.{1} needs a valid command name.", type, method.Name));
                                continue;
                            }

                            cmd.m_callback = cb;
                            m_commands.Add(cmd);
                        }
                    }
                }
            }
#endif
        }

19 View Source File : Utility.Reflection.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static T GetMethodAttribute<T>(Type type,string methodName)where T: Attribute
            {
                var mi = type.GetMethod(methodName);
                if (null!=mi)
                {
                    var attributes = mi.GetCustomAttributes(typeof(T),false);
                    if (0<attributes.Length)
                    {
                        return attributes[0] as T;
                    }
                }
                return null;
            }

19 View Source File : EnumMethods.cs
License : MIT License
Project Creator : 8T4

[ExcludeFromCodeCoverage]
        public static string GetDescription(this Enum genericEnum)
        {
            var genericEnumType = genericEnum.GetType();
            var memberInfo = genericEnumType.GetMember(genericEnum.ToString());

            if (memberInfo.Length <= 0)
            {
                return genericEnum.ToString();
            }

            var attribs = memberInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
            
            return attribs.Any() 
                ? ((System.ComponentModel.DescriptionAttribute)attribs.ElementAt(0)).Description 
                : genericEnum.ToString();
        }

19 View Source File : ResourceRepository.cs
License : MIT License
Project Creator : 99x

internal static void Initialize(replacedembly callingreplacedembly)
        {
            Repo = new ResourceRepository();

            var ignorereplacedemblies = new string[] {"RadiumRest", "RadiumRest.Core", "RadiumRest.Selfhost", "mscorlib"};
            var referencedreplacedemblies = callingreplacedembly.GetReferencedreplacedemblies();
            var currentAsm = replacedembly.GetExecutingreplacedembly().GetName();

            var scanreplacedemblies = new List<replacedemblyName>() { callingreplacedembly.GetName()};

            foreach (var asm in referencedreplacedemblies)
            {
                if (asm == currentAsm)
                    continue;

                if (!ignorereplacedemblies.Contains(asm.Name))
                    scanreplacedemblies.Add(asm);
            }

            foreach (var refAsm in scanreplacedemblies)
            {
                try
                {
                    var asm = replacedembly.Load(refAsm.FullName);


                    foreach (var typ in asm.GetTypes())
                    {
                        if (typ.IsSubclreplacedOf(typeof(RestResourceHandler)))
                        {
                            var clreplacedAttribObj = typ.GetCustomAttributes(typeof(RestResource), false).FirstOrDefault();
                            string baseUrl;
                            if (clreplacedAttribObj != null)
                            {
                                var clreplacedAttrib = (RestResource)clreplacedAttribObj;
                                baseUrl = clreplacedAttrib.Path;
                                baseUrl = baseUrl.StartsWith("/") ? baseUrl : "/" + baseUrl;
                            }
                            else baseUrl = "";

                            var methods = typ.GetMethods();


                            foreach (var method in methods)
                            {
                                var methodAttribObject = method.GetCustomAttributes(typeof(RestPath), false).FirstOrDefault();

                                if (methodAttribObject != null)
                                {
                                    var methodAttrib = (RestPath)methodAttribObject;
                                    string finalUrl = baseUrl + (methodAttrib.Path ?? "");
                                    
                                    var finalMethod = methodAttrib.Method;

                                    PathExecutionInfo exeInfo = new PathExecutionInfo
                                    {
                                        Type = typ,
                                        Method = method
                                    };
                                    AddExecutionInfo(finalMethod, finalUrl, exeInfo);
                                }
                            }
                        }

                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
        }

19 View Source File : Inspector.cs
License : GNU General Public License v3.0
Project Creator : a2659802

private static void _reflectProps(Type t, BindingFlags flags = BindingFlags.Public | BindingFlags.Instance)
        {
            if (cache_prop.ContainsKey(t))
                return;
            var propInfos =t.GetProperties(flags)
                .Where(x =>
                {
                    var handlers = x.GetCustomAttributes(typeof(HandleAttribute), true).OfType<HandleAttribute>();
                    bool handflag = handlers.Any();
                    bool ignoreflag = x.GetCustomAttributes(typeof(InspectIgnoreAttribute), true).OfType<InspectIgnoreAttribute>().Any();
                    if(handflag && (!ignoreflag))
                    {
                        if(!handler.ContainsKey(x))
                            handler.Add(x, handlers.FirstOrDefault().handleType);
                    }

                    return handflag && (!ignoreflag);
                });
            foreach(var p in propInfos)
            {
                if(cache_prop.TryGetValue(t,out var npair))
                {
                    npair.Add(p.Name, p);
                }
                else
                {
                    var d = new Dictionary<string, PropertyInfo>();
                    d.Add(p.Name, p);
                    cache_prop.Add(t, d);
                }

                //Logger.LogDebug($"Cache PropInfo:T:{t},name:{p.Name}");
            }
            //Logger.LogDebug($"_reflectProp_resutl:{propInfos.ToArray().Length}");
        }

19 View Source File : Inspector.cs
License : GNU General Public License v3.0
Project Creator : a2659802

public static void Show()
        {
            OpLock.Apply();
            try
            {
                Item item = ItemManager.Instance.currentSelect.GetComponent<CustomDecoration>().item;
                

                if (!cache_prop.ContainsKey(item.GetType()))
                {
                    _reflectProps(item.GetType());
                }
                if (cache_prop.TryGetValue(item.GetType(), out var itemProps))
                {
                    var insp = new InspectPanel();
                    currentEdit = insp;
                    int idx = 0;
                    foreach (var kv in itemProps)
                    {
                        string name = kv.Key;
                        Type propType = kv.Value.PropertyType;
                        object value = kv.Value.GetValue(item, null);
                        value = Convert.ToSingle(value);
                        ConstraintAttribute con = kv.Value.GetCustomAttributes(typeof(ConstraintAttribute), true).OfType<ConstraintAttribute>().FirstOrDefault();

                        LogProp(propType, name, value);

                        if(idx == 0)
                        {
                            insp.UpdateName(idx,name);
                            if(con is IntConstraint)
                            {
                                //Logger.LogDebug($"Check1 {con.Min}-{con.Max}");
                                insp.UpdateSliderConstrain(name,idx, (float)Convert.ChangeType(con.Min, typeof(float)), Convert.ToInt32(con.Max), true);
                            }
                            else if(con is FloatConstraint)
                            {
                                //Logger.LogDebug($"Check2 {con.Min}-{con.Max}");
                                insp.UpdateSliderConstrain(name,idx, (float)(con.Min), (float)(con.Max), false);
                            }
                            else
                            {
                                throw new ArgumentException();
                            }
                            //Logger.LogDebug($"Check3 {value}-{value.GetType()}");
                            insp.UpdateValue(idx, (float)value);
                        }
                        else
                        {
                            insp.AppendPropPanel(name);
                            if (con is IntConstraint)
                            {
                                insp.UpdateSliderConstrain(name,idx, (int)con.Min, (int)con.Max, true);
                            }
                            else if (con is FloatConstraint)
                            {
                                insp.UpdateSliderConstrain(name,idx, (float)con.Min, (float)con.Max, false);
                            }
                            else
                            {
                                throw new ArgumentException();
                            }
                            insp.UpdateValue(idx, (float)value);
                            insp.UpdateTextDelegate(idx);//insp.AddListener(idx, insp.UpdateTextDelegate(idx));

                        }
                        //insp.AddListener(idx, (v) => { kv.Value.SetValue(item, Convert.ChangeType(v, kv.Value.PropertyType), null); });
                        insp.AddListener(idx, (v) => {
                            if (ItemManager.Instance.currentSelect == null)
                                return;
                            object val;
                            try
                            {
                                if (kv.Value.PropertyType.IsSubclreplacedOf(typeof(Enum)))
                                {
                                    val = Enum.Parse(kv.Value.PropertyType, v.ToString("0"));
                                }
                                else
                                    val = Convert.ChangeType(v, kv.Value.PropertyType);
                                ItemManager.Instance.currentSelect.GetComponent<CustomDecoration>().Setup(handler[kv.Value], val);
                            }
                            catch
                            {
                                Logger.LogError("Error occour at Inspect OnValue Chnaged");
                                Hide();
                            }
                        });
                        idx++;
                    }
                }
                else
                {
                    Logger.LogError($"KeyNotFount at cache_prop,{item.GetType()}");
                }
                
            }
            catch(NullReferenceException e)
            {
                Logger.LogError($"NulRef Error at Inspector.Show:{e}");
                OpLock.Undo();
            }
       
        }

19 View Source File : ObjectManager.cs
License : GNU General Public License v3.0
Project Creator : a2659802

public static void RegisterBehaviour<T>()
        {
            var behaviours = typeof(T).GetNestedTypes(BindingFlags.Public).Where(x => x.IsSubclreplacedOf(typeof(CustomDecoration)));
            var items = typeof(ItemDef).GetNestedTypes(BindingFlags.Public | BindingFlags.Instance).Where(x => x.IsSubclreplacedOf(typeof(Item)));

            foreach (Type b in behaviours)
            {
                DecorationAttribute attr = b.GetCustomAttributes(typeof(DecorationAttribute), false).OfType<DecorationAttribute>().FirstOrDefault();
                if (attr == null)
                    continue;

                string poolname = attr.Name;

                Type DataStruct = null;
                foreach (Type i in items) // Search Item Defination in ItemDef
                {
                    DecorationAttribute[] i_attr = i.GetCustomAttributes(typeof(DecorationAttribute), false).OfType<DecorationAttribute>().ToArray();
                    if (i_attr == null || i_attr.Length == 0)
                        continue;
                        
                    if(i_attr.Contains(attr))
                    {
                        DataStruct = i;
                        break;
                    }
                }
                if(DataStruct == null) // Search Item Defination in Behaviour
                {
                    DataStruct = b.GetNestedTypes(BindingFlags.Public).Where(x => x.IsSubclreplacedOf(typeof(Item))).FirstOrDefault();
                }
                if (DataStruct == null) // Search Item Defination in T
                {
                    DataStruct = typeof(T).GetNestedTypes(BindingFlags.Public).Where(x => x.IsSubclreplacedOf(typeof(Item))).FirstOrDefault();
                }
                if (DataStruct == null) // Fill with defatult Item
                {
                    Logger.LogWarn($"Could Not Found an Item that match {b.FullName},Attr:{attr.Name},will use default item instance");
                    DataStruct = typeof(ItemDef.Defaulreplacedem);
                }

                Register(poolname, b, DataStruct);
            }
        }

19 View Source File : ReflectionCache.cs
License : GNU General Public License v3.0
Project Creator : a2659802

public static List<PropertyInfo> GereplacedemProps(Type t,Operation op)
        {
            
            if(ItemPropCache.TryGetValue(t,out var props))
            {
                if (props.TryGetValue(op, out var res))
                    return res;
                else
                    return null; 
            }
            var handle_prop = t.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => x.GetCustomAttributes(typeof(HandleAttribute), true).Any());
            Dictionary<Operation, List<PropertyInfo>> opbind = new Dictionary<Operation, List<PropertyInfo>>();
            foreach(var p in handle_prop)
            {
                Operation p_op = p.GetCustomAttributes(typeof(HandleAttribute), true).OfType<HandleAttribute>().FirstOrDefault().handleType;
                if (opbind.TryGetValue(p_op, out var list))
                {
                    list.Add(p);
                }
                else
                {
                    opbind.Add(p_op, new List<PropertyInfo> { p });
                }
                //Logger.LogDebug($"Cache: {p_op}:{p.Name},{t}");
            }
            ItemPropCache.Add(t, opbind);

            if (ItemPropCache.TryGetValue(t, out var props2))
            {
                if (props2.TryGetValue(op, out var res2))
                    return res2;
                else
                    return null;
            }
            else
                return null;
        }

19 View Source File : ObjectManager.cs
License : GNU General Public License v3.0
Project Creator : a2659802

public static void RegisterSharedBehaviour<T>() where T : CustomDecoration
        {
            var shareAttr = typeof(T).GetCustomAttributes(typeof(DecorationAttribute), false).OfType<DecorationAttribute>();
            foreach(var attr in shareAttr)
            {
                if (attr == null)
                    continue;
                string poolname = attr.Name;

                var ti = typeof(T).GetNestedTypes(BindingFlags.Public).Where(x => x.IsSubclreplacedOf(typeof(Item))).FirstOrDefault();

                Register<T>(poolname, ti);
            }
        }

19 View Source File : ReflectionCache.cs
License : GNU General Public License v3.0
Project Creator : a2659802

public static List<MethodInfo> GetMethods(Type t, Operation op)
        {

            if (BehaviourMethodCache.TryGetValue(t, out var props))
            {
                if (props.TryGetValue(op, out var res))
                    return res;
                else
                    return null;
            }
            var handle_methods = t.GetMethods(BindingFlags.Public | BindingFlags.Instance).Where(x => x.GetCustomAttributes(typeof(HandleAttribute), true).Any());
            Dictionary<Operation, List<MethodInfo>> opbind = new Dictionary<Operation, List<MethodInfo>>();
            foreach (var m in handle_methods)
            {
                var ops = m.GetCustomAttributes(typeof(HandleAttribute), true).OfType<HandleAttribute>().Select(x=>x.handleType);//.FirstOrDefault().handleType;
                foreach(var p_op in ops)
                {
                    if (opbind.TryGetValue(p_op, out var list))
                    {
                        list.Add(m);
                    }
                    else
                    {
                        opbind.Add(p_op, new List<MethodInfo> { m });
                    }
                    
                }

            }
            BehaviourMethodCache.Add(t, opbind);

            if (BehaviourMethodCache.TryGetValue(t, out var props2))
            {
                if (props2.TryGetValue(op, out var res2))
                    return res2;
                else
                    return null;
            }
            else
                return null;
        }

19 View Source File : EntityCache.cs
License : Apache License 2.0
Project Creator : aadreja

internal static TableAttribute PrepareTableAttribute(Type enreplacedy)
        {
            TableAttribute result = (TableAttribute)enreplacedy.GetCustomAttributes(typeof(TableAttribute), false).FirstOrDefault();
            if (result == null)
            {
                result = new TableAttribute
                {
                    Name = enreplacedy.Name, //replaceduming enreplacedy clreplaced name is table name
                    NeedsHistory = Config.NeedsHistory,
                    NoCreatedBy = Config.NoCreatedBy,
                    NoCreatedOn = Config.NoCreatedOn,
                    NoUpdatedBy = Config.NoUpdatedBy,
                    NoUpdatedOn = Config.NoUpdatedOn,
                    NoVersionNo = Config.NoVersionNo,
                    NoIsActive = Config.NoIsActive
                };
            }

            if (string.IsNullOrEmpty(result.Name)) result.Name = enreplacedy.Name;

            //find all properties
            var properties = enreplacedy.GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (PropertyInfo property in properties)
            {
                //TODO: check for valid property types to be added in list
                if ((property.Name.Equals("keyid", StringComparison.OrdinalIgnoreCase) ||
                    property.Name.Equals("operation", StringComparison.OrdinalIgnoreCase)))
                    continue;

                //check for ignore property attribute
                var ignoreInfo = (IgnoreColumnAttribute)property.GetCustomAttribute(typeof(IgnoreColumnAttribute));
                var primaryKey = (PrimaryKeyAttribute)property.GetCustomAttribute(typeof(PrimaryKeyAttribute));
                var column = (ColumnAttribute)property.GetCustomAttribute(typeof(ColumnAttribute));


                if (column == null) column = new ColumnAttribute();

                if (string.IsNullOrEmpty(column.Name)) column.Name = property.Name;

                if (property.Name.Equals("CreatedBy", StringComparison.OrdinalIgnoreCase))
                    column.Name = Config.CreatedByColumnName;
                else if (property.Name.Equals("CreatedByName"))
                    column.Name = Config.CreatedByNameColumnName;
                else if (property.Name.Equals("CreatedOn"))
                    column.Name = Config.CreatedOnColumnName;
                else if (property.Name.Equals("UpdatedBy"))
                    column.Name = Config.UpdatedByColumnName;
                else if (property.Name.Equals("UpdatedByName"))
                    column.Name = Config.UpdatedByNameColumnName;
                else if (property.Name.Equals("UpdatedOn"))
                    column.Name = Config.UpdatedOnColumnName;
                else if (property.Name.Equals("VersionNo"))
                    column.Name = Config.VersionNoColumnName;
                else if (property.Name.Equals("IsActive"))
                    column.Name = Config.IsActiveColumnName;

                if (!column.IsColumnDbTypeDefined)
                {
                    if (column.Name.Equals(Config.CreatedByColumnName, StringComparison.OrdinalIgnoreCase) ||
                        column.Name.Equals(Config.UpdatedByColumnName, StringComparison.OrdinalIgnoreCase))
                        column.ColumnDbType = Config.CreatedUpdatedByColumnType;
                    else if (property.PropertyType.IsEnum)
                        column.ColumnDbType = TypeCache.TypeToDbType[property.PropertyType.GetEnumUnderlyingType()];
                    else if (property.PropertyType.IsValueType)
                        column.ColumnDbType = TypeCache.TypeToDbType[property.PropertyType];
                    else
                    {
                        TypeCache.TypeToDbType.TryGetValue(property.PropertyType, out DbType columnDbType);
                        column.ColumnDbType = columnDbType;
                    }
                }

                column.SetPropertyInfo(property, enreplacedy);

                column.IgnoreInfo = ignoreInfo ?? new IgnoreColumnAttribute(false);

                //Primary Key details
                if (primaryKey != null)
                {
                    column.PrimaryKeyInfo = primaryKey;

                    var virtualForeignKeys = (IEnumerable<ForeignKey>)property.GetCustomAttributes(typeof(ForeignKey));
                    if (virtualForeignKeys != null && virtualForeignKeys.Count() > 0)
                    {
                        if (result.VirtualForeignKeys == null) result.VirtualForeignKeys = new List<ForeignKey>();
                        result.VirtualForeignKeys.AddRange(virtualForeignKeys);
                    }
                }

                if (result.NoCreatedBy && (column.Name.Equals(Config.CreatedByColumnName, StringComparison.OrdinalIgnoreCase)
                    || column.Name.Equals(Config.CreatedByNameColumnName, StringComparison.OrdinalIgnoreCase)))
                    continue;
                else if (result.NoCreatedOn && column.Name.Equals(Config.CreatedOnColumnName, StringComparison.OrdinalIgnoreCase))
                    continue;
                else if (result.NoUpdatedBy && ((column.Name.Equals(Config.UpdatedByColumnName, StringComparison.OrdinalIgnoreCase)
                    || column.Name.Equals(Config.UpdatedByNameColumnName, StringComparison.OrdinalIgnoreCase))))
                    continue;
                else if (result.NoUpdatedOn && column.Name.Equals(Config.UpdatedOnColumnName, StringComparison.OrdinalIgnoreCase))
                    continue;
                else if (result.NoIsActive && column.Name.Equals(Config.IsActiveColumnName, StringComparison.OrdinalIgnoreCase))
                    continue;
                else if (result.NoVersionNo && column.Name.Equals(Config.VersionNoColumnName, StringComparison.OrdinalIgnoreCase))
                    continue;
                else
                {
                    if (!column.IgnoreInfo.Insert)
                        result.DefaultInsertColumns.Add(column.Name);

                    //isactive,createdon,createdby column shall not be included in default update columns
                    if (!column.IgnoreInfo.Update
                        && !column.Name.Equals(Config.IsActiveColumnName, StringComparison.OrdinalIgnoreCase)
                        && !column.Name.Equals(Config.CreatedByColumnName, StringComparison.OrdinalIgnoreCase)
                        && !column.Name.Equals(Config.CreatedOnColumnName, StringComparison.OrdinalIgnoreCase))
                        result.DefaultUpdateColumns.Add(column.Name);

                    if (!column.IgnoreInfo.Read)
                        result.DefaultReadColumns.Add(column.Name);

                    result.Columns[column.Name] = column;
                }
            }

            if(result.Columns.LongCount(p=>p.Value.IsPrimaryKey && p.Value.PrimaryKeyInfo.IsIdenreplacedy) > 1)
            {
                throw new NotSupportedException("Primary key with multiple Idenreplacedy is not supported on " + result.Name);
            }

            if (result.Columns.LongCount(p => p.Value.IsPrimaryKey) > 1 && result.NeedsHistory)
            {
                throw new NotSupportedException($"History for {result.Name} is not supported as it has composite Primary key");
            }

            return result;
        }

19 View Source File : VxFormGroup.cs
License : MIT License
Project Creator : Aaltuj

private static void PatchLayoutWithBuiltInAttributes(VxFormElementLayoutAttribute layoutAttr, PropertyInfo prop)
        {
            var displayAttribute = prop
                   .GetCustomAttributes(typeof(DisplayAttribute), false)
                   .FirstOrDefault() as DisplayAttribute;

            if (displayAttribute != null)
            {
                layoutAttr.Label = displayAttribute.GetName();
                layoutAttr.Order = displayAttribute.GetOrder().GetValueOrDefault();
            }
        }

19 View Source File : VxFormGroup.cs
License : MIT License
Project Creator : Aaltuj

private static string GetLabel(string fieldIdentifier, object modelInstance)
        {
            var modelType = modelInstance.GetType();

            if (modelType == typeof(ExpandoObject))
            {
                return fieldIdentifier;
            }
            else
            {
                var prop = modelInstance
                .GetType()
                .GetProperty(fieldIdentifier);

                var displayAttribute = prop
                    .GetCustomAttributes(typeof(DisplayAttribute), false)
                    .FirstOrDefault() as DisplayAttribute;

                return displayAttribute != null ? displayAttribute.Name : fieldIdentifier;
            }

        }

19 View Source File : VxHelpers.cs
License : MIT License
Project Creator : Aaltuj

public static T GetAttribute<T>(this Enum value) where T : Attribute
        {
            var type = value.GetType();
            var memberInfo = type.GetMember(value.ToString());
            var attributes = memberInfo[0].GetCustomAttributes(typeof(T), false);
            return attributes.Length > 0
              ? (T)attributes[0]
              : null;
        }

19 View Source File : MixedRealityControllerAttribute.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static MixedRealityControllerAttribute Find(Type type)
        {
            return type.GetCustomAttributes(typeof(MixedRealityControllerAttribute), true).FirstOrDefault() as MixedRealityControllerAttribute;
        }

19 View Source File : InspectorFieldsUtility.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static List<InspectorFieldData> GetInspectorFields(System.Object target)
        {
            List<InspectorFieldData> fields = new List<InspectorFieldData>();
            Type myType = target.GetType();

            foreach (PropertyInfo prop in myType.GetProperties())
            {
                var attrs = (InspectorField[])prop.GetCustomAttributes(typeof(InspectorField), false);
                foreach (var attr in attrs)
                {
                    fields.Add(new InspectorFieldData() { Name = prop.Name, Attributes = attr, Value = prop.GetValue(target, null) });
                }
            }

            foreach (FieldInfo field in myType.GetFields())
            {
                var attrs = (InspectorField[])field.GetCustomAttributes(typeof(InspectorField), false);
                foreach (var attr in attrs)
                {
                    fields.Add(new InspectorFieldData() { Name = field.Name, Attributes = attr, Value = field.GetValue(target) });
                }
            }

            return fields;
        }

19 View Source File : InspectorGenericFields.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static void LoadSettings(T target, List<InspectorPropertySetting> settings)
        {
            Type myType = target.GetType();

            List<PropertyInfo> propInfoList = new List<PropertyInfo>(myType.GetProperties());
            for (int i = 0; i < propInfoList.Count; i++)
            {
                PropertyInfo propInfo = propInfoList[i];
                var attrs = (InspectorField[])propInfo.GetCustomAttributes(typeof(InspectorField), false);
                foreach (var attr in attrs)
                {
                    object value = InspectorField.GetSettingValue(settings, propInfo.Name);
                    if (value != null)
                    {
                        propInfo.SetValue(target, value);
                    }
                }
            }

            List<FieldInfo> fieldInfoList = new List<FieldInfo>(myType.GetFields());
            for (int i = 0; i < fieldInfoList.Count; i++)
            {
                FieldInfo fieldInfo = fieldInfoList[i];
                var attrs = (InspectorField[])fieldInfo.GetCustomAttributes(typeof(InspectorField), false);
                foreach (var attr in attrs)
                {
                    object value = InspectorField.GetSettingValue(settings, fieldInfo.Name);
                    if (value != null)
                    {
                        fieldInfo.SetValue(target, value);
                    }
                }
            }
        }

19 View Source File : InspectorGenericFields.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static List<InspectorPropertySetting> GetSettings(T source)
        {
            Type myType = source.GetType();
            List<InspectorPropertySetting> settings = new List<InspectorPropertySetting>();

            List<PropertyInfo> propInfoList = new List<PropertyInfo>(myType.GetProperties());
            for (int i = 0; i < propInfoList.Count; i++)
            {
                PropertyInfo propInfo = propInfoList[i];
                var attrs = (InspectorField[])propInfo.GetCustomAttributes(typeof(InspectorField), false);
                foreach (var attr in attrs)
                {
                    settings.Add(InspectorField.FieldToProperty(attr, propInfo.GetValue(source, null), propInfo.Name));
                }
            }

            List<FieldInfo> fieldInfoList = new List<FieldInfo>(myType.GetFields());
            for (int i = 0; i < fieldInfoList.Count; i++)
            {
                FieldInfo fieldInfo = fieldInfoList[i];
                var attrs = (InspectorField[])fieldInfo.GetCustomAttributes(typeof(InspectorField), false);
                foreach (var attr in attrs)
                {
                    settings.Add(InspectorField.FieldToProperty(attr, fieldInfo.GetValue(source), fieldInfo.Name));
                }
            }

            return settings;
        }

19 View Source File : TypeReferencePropertyDrawer.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private static string FormatGroupedTypeName(Type type, TypeGrouping grouping)
        {
            string name = type.FullName;

            switch (grouping)
            {
                case TypeGrouping.None:
                    return name;
                case TypeGrouping.ByNamespace:
                    return string.IsNullOrEmpty(name) ? string.Empty : name.Replace('.', '/');
                case TypeGrouping.ByNamespaceFlat:
                    int lastPeriodIndex = string.IsNullOrEmpty(name) ? -1 : name.LastIndexOf('.');
                    if (lastPeriodIndex != -1)
                    {
                        name = string.IsNullOrEmpty(name)
                            ? string.Empty
                            : $"{name.Substring(0, lastPeriodIndex)}/{name.Substring(lastPeriodIndex + 1)}";
                    }

                    return name;
                case TypeGrouping.ByAddComponentMenu:
                    var addComponentMenuAttributes = type.GetCustomAttributes(typeof(AddComponentMenu), false);
                    if (addComponentMenuAttributes.Length == 1)
                    {
                        return ((AddComponentMenu)addComponentMenuAttributes[0]).componentMenu;
                    }

                    Debug.replacedert(type.FullName != null);
                    return $"Scripts/{type.FullName.Replace('.', '/')}";
                default:
                    throw new ArgumentOutOfRangeException(nameof(grouping), grouping, null);
            }
        }

19 View Source File : ServiceFacadeInspector.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private bool DrawDataProviders(Type serviceType)
        {
            // If this is a data provider being used by other services, mention that now
            dataProviderList.Clear();
            foreach (MixedRealityDataProviderAttribute dataProviderAttribute in serviceType.GetCustomAttributes(typeof(MixedRealityDataProviderAttribute), true))
            {
                dataProviderList.Add(" • " + dataProviderAttribute.ServiceInterfaceType.Name);
            }

            if (dataProviderList.Count > 0)
            {
                EditorGUILayout.HelpBox("This data provider is used by the following services:\n " + String.Join("\n", dataProviderList.ToArray()), MessageType.Info);
                EditorGUILayout.Space();
                return true;
            }
            return false;
        }

19 View Source File : MixedRealityProfileUtility.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static bool IsProfileForService(Type profileType, Type serviceType)
        {
            foreach (MixedRealityServiceProfileAttribute serviceProfileAttribute in profileType.GetCustomAttributes(typeof(MixedRealityServiceProfileAttribute), true))
            {
                bool requirementsMet = true;
                foreach (Type requiredType in serviceProfileAttribute.RequiredTypes)
                {
                    if (!requiredType.IsreplacedignableFrom(serviceType))
                    {
                        requirementsMet = false;
                        break;
                    }
                }

                if (requirementsMet)
                {
                    foreach (Type excludedType in serviceProfileAttribute.ExcludedTypes)
                    {
                        if (excludedType.IsreplacedignableFrom(serviceType))
                        {
                            requirementsMet = false;
                            break;
                        }

                    }
                }

                return requirementsMet;
            }
            return false;
        }

19 View Source File : EnumDescriptionConverter.cs
License : MIT License
Project Creator : ABTSoftware

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Enum e = value as Enum;
            if (e == null) return null;

            var type = e.GetType();
            var memInfo = type.GetMember(e.ToString());
            var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
            var description = ((DescriptionAttribute)attributes[0]).Description;
            return description;
        }

19 View Source File : PropertyInfoExtensions.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static T GetAttributeOfType<T>(this PropertyInfo prop) where T : System.Attribute
        {
            var attributes = prop.GetCustomAttributes(typeof(T), false);
            return (attributes.Length > 0) ? (T)attributes[0] : null;
        }

19 View Source File : DatTests.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

[TestMethod]
        public void UnpackCellDatFiles_NoExceptions()
        {
            var replacedembly = typeof(DatDatabase).GetTypeInfo().replacedembly;
            var types = replacedembly.GetTypes().Where(t => t.GetCustomAttributes(typeof(DatFileTypeAttribute), false).Length > 0).ToList();

            if (types.Count == 0)
                throw new Exception("Failed to locate any types with DatFileTypeAttribute.");

            DatDatabase dat = new DatDatabase(cellDatLocation);

            foreach (var kvp in dat.AllFiles)
            {
                if (kvp.Key == 0xFFFF0001) // Not sure what this is, EOF record maybe?
                    continue;

                if (kvp.Value.FileSize == 0) // DatFileType.LandBlock files can be empty
                    continue;

                var fileType = kvp.Value.GetFileType(DatDatabaseType.Cell);

                if ((kvp.Key & 0xFFFF) == 0xFFFE) fileType = DatFileType.LandBlockInfo;
                if ((kvp.Key & 0xFFFF) == 0xFFFF) fileType = DatFileType.LandBlock;

                //replacedert.IsNotNull(fileType, $"Key: 0x{kvp.Key:X8}, ObjectID: 0x{kvp.Value.ObjectId:X8}, FileSize: {kvp.Value.FileSize}, BitFlags:, 0x{kvp.Value.BitFlags:X8}");
                replacedert.IsNotNull(fileType, $"Key: 0x{kvp.Key:X8}, ObjectID: 0x{kvp.Value.ObjectId:X8}, FileSize: {kvp.Value.FileSize}");

                var type = types
                    .SelectMany(m => m.GetCustomAttributes(typeof(DatFileTypeAttribute), false), (m, a) => new { m, a })
                    .Where(t => ((DatFileTypeAttribute)t.a).FileType == fileType)
                    .Select(t => t.m);

                var first = type.FirstOrDefault();

                if (first == null)
                    throw new Exception($"Failed to Unpack fileType: {fileType}");

                var obj = Activator.CreateInstance(first);

                var unpackable = obj as IUnpackable;

                if (unpackable == null)
                    throw new Exception($"Clreplaced for fileType: {fileType} does not implement IUnpackable.");

                var datReader = new DatReader(cellDatLocation, kvp.Value.FileOffset, kvp.Value.FileSize, dat.Header.BlockSize);

                using (var memoryStream = new MemoryStream(datReader.Buffer))
                using (var reader = new BinaryReader(memoryStream))
                {
                    unpackable.Unpack(reader);

                    if (memoryStream.Position != kvp.Value.FileSize)
                        throw new Exception($"Failed to parse all bytes for fileType: {fileType}, ObjectId: 0x{kvp.Value.ObjectId:X8}. Bytes parsed: {memoryStream.Position} of {kvp.Value.FileSize}");
                }
            }
        }

19 View Source File : DatTests.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

[TestMethod]
        public void UnpackPortalDatFiles_NoExceptions()
        {
            var replacedembly = typeof(DatDatabase).GetTypeInfo().replacedembly;
            var types = replacedembly.GetTypes().Where(t => t.GetCustomAttributes(typeof(DatFileTypeAttribute), false).Length > 0).ToList();

            if (types.Count == 0)
                throw new Exception("Failed to locate any types with DatFileTypeAttribute.");

            DatDatabase dat = new DatDatabase(portalDatLocation);

            foreach (var kvp in dat.AllFiles)
            {
                if (kvp.Key == 0xFFFF0001) // Not sure what this is, EOF record maybe?
                    continue;

                var fileType = kvp.Value.GetFileType(DatDatabaseType.Portal);

                //replacedert.IsNotNull(fileType, $"Key: 0x{kvp.Key:X8}, ObjectID: 0x{kvp.Value.ObjectId:X8}, FileSize: {kvp.Value.FileSize}, BitFlags:, 0x{kvp.Value.BitFlags:X8}");
                replacedert.IsNotNull(fileType, $"Key: 0x{kvp.Key:X8}, ObjectID: 0x{kvp.Value.ObjectId:X8}, FileSize: {kvp.Value.FileSize}");

                // These file types aren't converted yet
                if (fileType == DatFileType.KeyMap) continue;
                if (fileType == DatFileType.RenderMaterial) continue;
                if (fileType == DatFileType.MaterialModifier) continue;
                if (fileType == DatFileType.MaterialInstance) continue;
                if (fileType == DatFileType.ActionMap) continue;
                if (fileType == DatFileType.MasterProperty) continue;
                if (fileType == DatFileType.DbProperties) continue;

                var type = types
                    .SelectMany(m => m.GetCustomAttributes(typeof(DatFileTypeAttribute), false), (m, a) => new {m, a})
                    .Where(t => ((DatFileTypeAttribute) t.a).FileType == fileType)
                    .Select(t => t.m);

                var first = type.FirstOrDefault();

                if (first == null)
                    throw new Exception($"Failed to Unpack fileType: {fileType}");

                var obj = Activator.CreateInstance(first);

                var unpackable = obj as IUnpackable;

                if (unpackable == null)
                    throw new Exception($"Clreplaced for fileType: {fileType} does not implement IUnpackable.");

                var datReader = new DatReader(portalDatLocation, kvp.Value.FileOffset, kvp.Value.FileSize, dat.Header.BlockSize);

                using (var memoryStream = new MemoryStream(datReader.Buffer))
                using (var reader = new BinaryReader(memoryStream))
                {
                    unpackable.Unpack(reader);

                    if (memoryStream.Position != kvp.Value.FileSize)
                        throw new Exception($"Failed to parse all bytes for fileType: {fileType}, ObjectId: 0x{kvp.Value.ObjectId:X8}. Bytes parsed: {memoryStream.Position} of {kvp.Value.FileSize}");
                }
            }
        }

19 View Source File : DatTests.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

[TestMethod]
        public void UnpackLocalEnglishDatFiles_NoExceptions()
        {
            var replacedembly = typeof(DatDatabase).GetTypeInfo().replacedembly;
            var types = replacedembly.GetTypes().Where(t => t.GetCustomAttributes(typeof(DatFileTypeAttribute), false).Length > 0).ToList();

            if (types.Count == 0)
                throw new Exception("Failed to locate any types with DatFileTypeAttribute.");

            DatDatabase dat = new DatDatabase(localEnglishDatLocation);

            foreach (var kvp in dat.AllFiles)
            {
                if (kvp.Key == 0xFFFF0001) // Not sure what this is, EOF record maybe?
                    continue;

                var fileType = kvp.Value.GetFileType(DatDatabaseType.Language);

                //replacedert.IsNotNull(fileType, $"Key: 0x{kvp.Key:X8}, ObjectID: 0x{kvp.Value.ObjectId:X8}, FileSize: {kvp.Value.FileSize}, BitFlags:, 0x{kvp.Value.BitFlags:X8}");
                replacedert.IsNotNull(fileType, $"Key: 0x{kvp.Key:X8}, ObjectID: 0x{kvp.Value.ObjectId:X8}, FileSize: {kvp.Value.FileSize}");

                // These file types aren't converted yet
                if (fileType == DatFileType.UiLayout) continue;

                var type = types
                    .SelectMany(m => m.GetCustomAttributes(typeof(DatFileTypeAttribute), false), (m, a) => new { m, a })
                    .Where(t => ((DatFileTypeAttribute)t.a).FileType == fileType)
                    .Select(t => t.m);

                var first = type.FirstOrDefault();

                if (first == null)
                    throw new Exception($"Failed to Unpack fileType: {fileType}");

                var obj = Activator.CreateInstance(first);

                var unpackable = obj as IUnpackable;

                if (unpackable == null)
                    throw new Exception($"Clreplaced for fileType: {fileType} does not implement IUnpackable.");

                var datReader = new DatReader(localEnglishDatLocation, kvp.Value.FileOffset, kvp.Value.FileSize, dat.Header.BlockSize);

                using (var memoryStream = new MemoryStream(datReader.Buffer))
                using (var reader = new BinaryReader(memoryStream))
                {
                    unpackable.Unpack(reader);

                    if (memoryStream.Position != kvp.Value.FileSize)
                        throw new Exception($"Failed to parse all bytes for fileType: {fileType}, ObjectId: 0x{kvp.Value.ObjectId:X8}. Bytes parsed: {memoryStream.Position} of {kvp.Value.FileSize}");
                }
            }
        }

19 View Source File : AttributeExtensions.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static T GetAttributeOfType<T>(this System.Enum enumVal) where T : System.Attribute
        {
            var type = enumVal.GetType();
            var memInfo = type.GetMember(enumVal.ToString());
            var attributes = memInfo[0].GetCustomAttributes(typeof(T), false);
            return (attributes.Length > 0) ? (T)attributes[0] : null;
        }

19 View Source File : UnknownEnum.cs
License : MIT License
Project Creator : actions

public static object Parse(Type enumType, string stringValue)
        {
            var underlyingType = Nullable.GetUnderlyingType(enumType);
            enumType = underlyingType != null ? underlyingType : enumType;

            var names = Enum.GetNames(enumType);
            if (!string.IsNullOrEmpty(stringValue))
            {
                var match = names.FirstOrDefault(name => string.Equals(name, stringValue, StringComparison.OrdinalIgnoreCase));
                if (match != null)
                {
                    return Enum.Parse(enumType, match);
                }

                // maybe we have an enum member with an EnumMember attribute specifying a custom name
                foreach (var field in enumType.GetFields())
                {
                    var enumMemberAttribute = field.GetCustomAttributes(typeof(EnumMemberAttribute), false).FirstOrDefault() as EnumMemberAttribute;
                    if (enumMemberAttribute != null && string.Equals(enumMemberAttribute.Value, stringValue, StringComparison.OrdinalIgnoreCase))
                    {
                        // we already have the field, no need to do enum.parse on it
                        return field.GetValue(null);
                    }
                }
            }

            return Enum.Parse(enumType, UnknownName);
        }

19 View Source File : FlagsEnum.cs
License : MIT License
Project Creator : actions

public static object ParseKnownFlags(Type enumType, string stringValue)
        {
            ArgumentUtility.CheckForNull(enumType, nameof(enumType));
            if (!enumType.IsEnum)
            {
                throw new ArgumentException(PipelinesWebApiResources.FlagEnumTypeRequired());
            }

            // Check for the flags attribute in debug. Skip this reflection in release.
            Debug.replacedert(enumType.GetCustomAttributes(typeof(FlagsAttribute), inherit: false).Any(), "FlagsEnum only intended for enums with the Flags attribute.");

            // The exception types below are based on Enum.TryParseEnum (http://index/?query=TryParseEnum&rightProject=mscorlib&file=system%5Cenum.cs&rightSymbol=bhaeh2vnegwo)
            if (stringValue == null)
            {
                throw new ArgumentNullException(stringValue);
            }

            if (String.IsNullOrWhiteSpace(stringValue))
            {
                throw new ArgumentException(PipelinesWebApiResources.NonEmptyEnumElementsRequired(stringValue));
            }

            if (UInt64.TryParse(stringValue, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out ulong ulongValue))
            {
                return Enum.Parse(enumType, stringValue);
            }

            var enumNames = Enum.GetNames(enumType).ToHashSet(name => name, StringComparer.OrdinalIgnoreCase);
            var enumMemberMappings = new Lazy<IDictionary<string, string>>(() =>
            {
                IDictionary<string, string> mappings = null;
                foreach (var field in enumType.GetFields())
                {
                    if (field.GetCustomAttributes(typeof(EnumMemberAttribute), false).FirstOrDefault() is EnumMemberAttribute enumMemberAttribute)
                    {
                        if (mappings == null)
                        {
                            mappings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                        }
                        mappings.Add(enumMemberAttribute.Value, field.GetValue(null).ToString());
                    }
                }

                return mappings;
            });

            var values = stringValue.Split(s_enumSeparatorCharArray);

            var matches = new List<string>();
            for (int i = 0; i < values.Length; i++)
            {
                string value = values[i].Trim();

                if (String.IsNullOrEmpty(value))
                {
                    throw new ArgumentException(PipelinesWebApiResources.NonEmptyEnumElementsRequired(stringValue));
                }

                if (enumNames.Contains(value))
                {
                    matches.Add(value);
                }
                else if (enumMemberMappings.Value != null && enumMemberMappings.Value.TryGetValue(value, out string matchingValue))
                {
                    matches.Add(matchingValue);
                }
            }

            if (!matches.Any())
            {
                return Enum.Parse(enumType, "0");
            }

            string matchesString = String.Join(", ", matches);
            return Enum.Parse(enumType, matchesString, ignoreCase: true);
        }

19 View Source File : EnumDescriptionTypeConverter.cs
License : MIT License
Project Creator : Actipro

public static String GetDescription(Type type, string fieldName) {
			if (null != type && null != fieldName) {
				FieldInfo fieldInfo = type.GetField(fieldName);
				if (null != fieldInfo) {
					DescriptionAttribute[] attributes = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
					if (null != attributes && 0 != attributes.Length)
						return attributes[0].Description;
				}

				return fieldName;
			}

			return string.Empty;
		}

19 View Source File : EnumDescriptionTypeConverter.cs
License : MIT License
Project Creator : Actipro

public static Object GetValue(Type type, String description) {
			FieldInfo[] fieldInfos = type.GetFields();
			foreach (FieldInfo fieldInfo in fieldInfos) {
				DescriptionAttribute[] attributes = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
				if (null != attributes && 0 != attributes.Length) {
					if (attributes[0].Description == description)
						return fieldInfo.GetValue(fieldInfo.Name);
				}

				if (fieldInfo.Name == description)
					return fieldInfo.GetValue(fieldInfo.Name);
			}

			return description;
		}

19 View Source File : ParentLexicalStateId.g.cs
License : MIT License
Project Creator : Actipro

public override String GetDescription(Int32 id) {
            FieldInfo[] fields = GetFields();
            for (Int32 index = 0; (index < fields.Length); index = (index + 1)) {
                FieldInfo field = fields[index];
                if (id.Equals(field.GetValue(null))) {
                    Object descriptionAttr = field.GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault();
                    if ((descriptionAttr != null)) {
                        return ((DescriptionAttribute)(descriptionAttr)).Description;
                    }
                    else {
                        return field.Name;
                    }
                }
            }
            return null;
        }

19 View Source File : SimpleLexicalStateId.g.cs
License : MIT License
Project Creator : Actipro

public override String GetDescription(Int32 id) {
            FieldInfo[] fields = typeof(SimpleLexicalStateId).GetFields((BindingFlags.Public | BindingFlags.Static));
            for (Int32 index = 0; (index < fields.Length); index = (index + 1)) {
                FieldInfo field = fields[index];
                if (id.Equals(field.GetValue(null))) {
                    Object[] customAttributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
                    if (((customAttributes != null) 
                                && (customAttributes.Length > 0))) {
                        return ((DescriptionAttribute)(customAttributes[0])).Description;
                    }
                    else {
                        return field.Name;
                    }
                }
            }
            return null;
        }

19 View Source File : SimpleAstNodeId.g.cs
License : MIT License
Project Creator : Actipro

public override String GetDescription(Int32 id) {
            FieldInfo[] fields = typeof(SimpleAstNodeId).GetFields((BindingFlags.Public | BindingFlags.Static));
            for (Int32 index = 0; (index < fields.Length); index = (index + 1)) {
                FieldInfo field = fields[index];
                if (id.Equals(field.GetValue(null))) {
                    Object[] customAttributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
                    if (((customAttributes != null) 
                                && (customAttributes.Length > 0))) {
                        return ((DescriptionAttribute)(customAttributes[0])).Description;
                    }
                    else {
                        return field.Name;
                    }
                }
            }
            return null;
        }

See More Examples