public RecordInfo(Type type) { if (!typeof(Record).IsAssignableFrom(type)) { throw new ArgumentException("Record type is not derived from Record: " + type.FullName); } var attribute = type.GetCustomAttributes(typeof(RecordAttribute), false).Cast<RecordAttribute>().FirstOrDefault();// .NET 4.5: type.GetCustomAttribute<RecordAttribute>(); if (attribute == null) { throw new ArgumentException("Record type is missing required atribute: " + type.FullName); } signature = attribute.Signature; var va = type.GetCustomAttributes(typeof(VersionAttribute), false).Cast<VersionAttribute>().FirstOrDefault();// .NET 4.5: type.GetCustomAttribute<RecordAttribute>(); if (va != null) { version = va.Version; } var da = type.GetCustomAttributes(typeof(DummyAttribute), false).Cast<DummyAttribute>().FirstOrDefault(); isDummyRecord = da != null; ctor = type.GetConstructor(paramlessTypes); compound = InfoProvider.GetCompoundInfo(type); }
/// <summary> /// Returns column view for specified type /// </summary> /// <param name="aType"> /// Class type <see cref="System.Type"/> /// </param> /// <returns> /// Array of column view names <see cref="System.String"/> /// </returns> public static string[] GetColumnViews(this System.Type aType) { List <string> lst = new List <string>(); ColumnViewAttribute[] attrs = (ColumnViewAttribute[])aType.GetCustomAttributes(typeof(ColumnViewAttribute), false); foreach (ColumnViewAttribute attr in attrs) { if (lst.IndexOf(attr.Name) > -1) { lst.Add(attr.Name); } } attrs = (ColumnViewAttribute[])aType.GetCustomAttributes(typeof(ColumnViewAttribute), true); foreach (ColumnViewAttribute attr in attrs) { if (lst.IndexOf(attr.Name) > -1) { lst.Add(attr.Name); } } if (lst.Count == 0) { return(null); } string[] res = new string[lst.Count]; for (int i = 0; i < lst.Count; i++) { res[i] = lst[i]; } lst.Clear(); return(res); }
private static ControllerRouteInfo GetControllerRouteInfo(Type controllerType) { string getRoute = null; string postRoute = null; string putRoute = null; string deleteRoute = null; var attributes = controllerType.GetCustomAttributes(typeof(GetAttribute), false); if (attributes.Length > 0) getRoute = ((GetAttribute)attributes[0]).Route; attributes = controllerType.GetCustomAttributes(typeof(PostAttribute), false); if (attributes.Length > 0) postRoute = ((PostAttribute)attributes[0]).Route; attributes = controllerType.GetCustomAttributes(typeof(PutAttribute), false); if (attributes.Length > 0) putRoute = ((PutAttribute)attributes[0]).Route; attributes = controllerType.GetCustomAttributes(typeof(DeleteAttribute), false); if (attributes.Length > 0) deleteRoute = ((DeleteAttribute)attributes[0]).Route; return !string.IsNullOrEmpty(getRoute) || !string.IsNullOrEmpty(postRoute) || !string.IsNullOrEmpty(putRoute) || !string.IsNullOrEmpty(deleteRoute) ? new ControllerRouteInfo(getRoute, postRoute, putRoute, deleteRoute) : null; }
public FunctionMetadata GetMetadata(Type functionType) { FunctionMetadata functionMetadata = new FunctionMetadata(functionType); functionMetadata.Id = MD5.GetHashString(functionType.FullName); var displayNameAttr = functionType.GetCustomAttribute<DisplayNameAttribute>(); functionMetadata.DisplayName = displayNameAttr != null ? displayNameAttr.DisplayName : null; var categoryAttr = functionType.GetCustomAttribute<CategoryAttribute>(); functionMetadata.Category = categoryAttr != null ? categoryAttr.Category : null; var sectionAttr = functionType.GetCustomAttribute<SectionAttribute>(); functionMetadata.Section = sectionAttr != null ? sectionAttr.Name : null; var descriptionAttr = functionType.GetCustomAttribute<DescriptionAttribute>(); functionMetadata.Description = descriptionAttr != null ? descriptionAttr.Description : null; foreach (var signature in functionType.GetCustomAttributes<FunctionSignatureAttribute>()) { functionMetadata.Signatures.Add(GetFunctionSignatureMetadata(signature)); } foreach (var exampleUsage in functionType.GetCustomAttributes<ExampleUsageAttribute>()) { functionMetadata.ExampleUsages.Add(new ExampleUsage(exampleUsage.Expression, exampleUsage.Result) { CanMultipleResults = exampleUsage.CanMultipleResults }); } return functionMetadata; }
ServiceMeta ServiceToMeta(Type type, int pos) { var test = type.GetCustomAttributes(); var serviceAttr = type.GetCustomAttributes() .FirstOrDefault(attr => attr.GetType().BaseType?.Name == "ServiceAttribute" || attr.GetType().Name == "ServiceAttribute"); var divisionalAttr = type.GetCustomAttributes() .FirstOrDefault(attr => attr.GetType().Name == "DivisionalAttribute"); var divisional = true; if (serviceAttr == null) { return null; } if (divisionalAttr != null) { divisional = (bool) divisionalAttr.GetType().GetProperty("Divisional").GetValue(divisionalAttr, null); } var typeName = type.Name; var svcMeta = new ServiceMeta() { Id = (uint)pos+1, Name = TypeNameToName(typeName, serviceAttr.GetType()), Type = ServiceTypeToEnum(serviceAttr.GetType()), Scope = ServiceNameToEnum(serviceAttr), Divisional = divisional, Multicast = serviceAttr.GetType().Name.Equals("SyncAttribute") && (bool)serviceAttr.GetType().GetProperty("Multicast").GetValue(serviceAttr, null), }; svcMeta.Methods = type.GetMethods().Select((m, p) => MethodToMeta(svcMeta, m, p)).Where(meta => meta != null).ToList(); return svcMeta; }
private static System.Type[] GetAllIncludedTypes(System.Type webService) { System.Type[] typeArray = includedTypesLookup[webService] as System.Type[]; if (typeArray == null) { ArrayList list = new ArrayList(); SoapIncludeAttribute[] customAttributes = webService.GetCustomAttributes(typeof(SoapIncludeAttribute), true) as SoapIncludeAttribute[]; foreach (SoapIncludeAttribute attribute in customAttributes) { list.Add(attribute.Type); } XmlIncludeAttribute[] attributeArray2 = webService.GetCustomAttributes(typeof(XmlIncludeAttribute), true) as XmlIncludeAttribute[]; foreach (XmlIncludeAttribute attribute2 in attributeArray2) { list.Add(attribute2.Type); } foreach (System.Type type in systemTypes) { list.Add(type); } typeArray = (System.Type[])list.ToArray(typeof(System.Type)); includedTypesLookup[webService] = typeArray; } return(typeArray); }
private static bool IsEnumType(Type t, string name) { return t.IsEnum && t.Name.Equals(name) && t.GetCustomAttributes(typeof(DataContractAttribute), false).Length > 0 && t.GetCustomAttributes(typeof(System.CodeDom.Compiler.GeneratedCodeAttribute), false).Length > 0; }
internal static string GetFullNameForModel(Type modelType, string host) { string ret = null; foreach (ModelNamespace mn in modelType.GetCustomAttributes(typeof(ModelNamespace), false)) { if (mn.Host == host) { ret = mn.Namespace; break; } } if (ret == null) { foreach (ModelNamespace mn in modelType.GetCustomAttributes(typeof(ModelNamespace), false)) { if (mn.Host == "*") { ret = mn.Namespace; break; } } } ret = (ret == null ? modelType.Namespace : ret); return ret+(ret.EndsWith(".") ? "" : ".")+modelType.Name; }
public void SetPluginInfo(System.Type type) { Name = type.Name; Filename = type.Name; var info_attributes = type.GetCustomAttributes(typeof(InfoAttribute), true); if (info_attributes.Length > 0) { var info = info_attributes[0] as InfoAttribute; Title = info.Title; Author = info.Author; Version = info.Version; ResourceId = info.ResourceId; } var description_attributes = type.GetCustomAttributes(typeof(DescriptionAttribute), true); if (description_attributes.Length > 0) { var info = description_attributes[0] as DescriptionAttribute; Description = info.Description; } var method = type.GetMethod("LoadDefaultConfig", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); HasConfig = method.DeclaringType != typeof(Plugin); }
// Methods private RestEndPoint(Type endPointType, bool isAsync) { this._endPointType = endPointType; this._operations = new Dictionary<string, RestOperation>(); this._operationList = new List<RestOperation>(); this._types = new Dictionary<Type, RestType>(); this._isAsync = isAsync; object[] customAttributes = endPointType.GetCustomAttributes(typeof(RestEndPointAttribute), true); if ((customAttributes != null) && (customAttributes.Length != 0)) { this._metaInfo = (RestEndPointAttribute)customAttributes[0]; this._name = this._metaInfo.Name; } if (string.IsNullOrEmpty(this._name)) { this._name = endPointType.Name; } customAttributes = endPointType.GetCustomAttributes(typeof(RestDescriptionAttribute), true); if ((customAttributes != null) && (customAttributes.Length != 0)) { this._description = ((RestDescriptionAttribute)customAttributes[0]).Description; } if (this._description == null) { this._description = string.Empty; } }
/// <summary> /// Gets the namespace from an attribute marked on the type's definition /// </summary> /// <param name="type"></param> /// <returns>Namespace of type</returns> public static string GetNamespace(Type type) { Attribute[] attrs = (Attribute[])type.GetCustomAttributes(typeof(DataContractAttribute), true); if (attrs.Length > 0) { DataContractAttribute dcAttr = (DataContractAttribute)attrs[0]; return dcAttr.Namespace; } attrs = (Attribute[])type.GetCustomAttributes(typeof(XmlRootAttribute), true); if (attrs.Length > 0) { XmlRootAttribute xmlAttr = (XmlRootAttribute)attrs[0]; return xmlAttr.Namespace; } attrs = (Attribute[])type.GetCustomAttributes(typeof(XmlTypeAttribute), true); if (attrs.Length > 0) { XmlTypeAttribute xmlAttr = (XmlTypeAttribute)attrs[0]; return xmlAttr.Namespace; } attrs = (Attribute[])type.GetCustomAttributes(typeof(XmlElementAttribute), true); if (attrs.Length > 0) { XmlElementAttribute xmlAttr = (XmlElementAttribute)attrs[0]; return xmlAttr.Namespace; } return null; }
protected ProxyAction(ModuleManager manager, Type classType, Type attributeType) { if (classType == null) throw new ArgumentNullException("classType"); if (attributeType == null) throw new ArgumentNullException("attributeType"); _Manager = manager; _ClassType = classType; object[] attrs; // Guid attribute; get it this way, not as Type.GUID, to be sure the attribute is applied attrs = _ClassType.GetCustomAttributes(typeof(GuidAttribute), false); if (attrs.Length == 0) throw new ModuleException(string.Format(null, "Apply the Guid attribute to the '{0}' class.", _ClassType.Name)); _Id = new Guid(((GuidAttribute)attrs[0]).Value); // Module* attribure attrs = _ClassType.GetCustomAttributes(attributeType, false); if (attrs.Length == 0) throw new ModuleException(string.Format(null, "Apply the '{0}' attribute to the '{1}' class.", attributeType.Name, _ClassType.Name)); _Attribute = (ModuleActionAttribute)attrs[0]; Initialize(); if (_Attribute.Resources) { _Manager.CachedResources = true; string name = _Manager.GetString(_Attribute.Name); if (!string.IsNullOrEmpty(name)) _Attribute.Name = name; } }
/// <summary> /// Extracts the attribute from the specified type. /// </summary> /// <param name="interfaceType"> /// The interface type. /// </param> /// <returns> /// The <see cref="ComProgIdAttribute"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="interfaceType"/> is <see langword="null"/>. /// </exception> public static ComProgIdAttribute GetAttribute(Type interfaceType) { if (null == interfaceType) { throw new ArgumentNullException("interfaceType"); } Type attributeType = typeof(ComProgIdAttribute); object[] attributes = interfaceType.GetCustomAttributes(attributeType, false); if (null == attributes || 0 == attributes.Length) { Type[] interfaces = interfaceType.GetInterfaces(); for (int i = 0; i < interfaces.Length; i++) { interfaceType = interfaces[i]; attributes = interfaceType.GetCustomAttributes(attributeType, false); if (null != attributes && 0 != attributes.Length) { break; } } } if (null == attributes || 0 == attributes.Length) { return null; } return (ComProgIdAttribute)attributes[0]; }
internal PluginInformation(Type type) { var displayNameAttributes = type.GetCustomAttributes(typeof(DisplayNameAttribute), false) as DisplayNameAttribute[]; var descriptionAttributes = type.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[]; Type = type; DisplayName = string.Intern(displayNameAttributes.Length > 0 ? displayNameAttributes[0].DisplayName : type.Name); Description = descriptionAttributes.Length > 0 ? descriptionAttributes[0].Description : null; }
/// <summary> /// Retrieves data source information. /// </summary> /// <param name="item"></param> /// <returns></returns> internal DataSourceInfo GetDataSourceInfo(Type type) { DataSourceInfo info; if (type == null) throw new ArgumentNullException("type"); try { CacheManager mappingCache = CacheFactory.GetCacheManager(); if (mappingCache.Contains(string.Format("GetDataSourceInfo({0})", type.FullName))) return (DataSourceInfo)mappingCache[string.Format("GetDataSourceInfo({0})", type.FullName)]; Debug.WriteLine(string.Format("Getting data source information for type {0}", type.Name)); info = new DataSourceInfo(); DataSourceAttribute[] datasource = (DataSourceAttribute[])type.GetCustomAttributes(typeof(DataSourceAttribute), true); info.DataSourceName = datasource.Length > 0 ? datasource[0].Name : string.Empty; // Retrieving table name to map the object in the database. TableAttribute[] tables = (TableAttribute[])type.GetCustomAttributes(typeof(TableAttribute), true); info.DeleteCommandName = datasource.Length > 0 && !string.IsNullOrEmpty(datasource[0].DeleteCommandName) ? datasource[0].DeleteCommandName : "Delete" + (tables.Length > 0 && !string.IsNullOrEmpty(tables[0].Name) ? tables[0].Name : type.Name); info.InsertCommandName = datasource.Length > 0 && !string.IsNullOrEmpty(datasource[0].InsertCommandName) ? datasource[0].InsertCommandName : "Insert" + (tables.Length > 0 && !string.IsNullOrEmpty(tables[0].Name) ? tables[0].Name : type.Name); info.UpdateCommandName = datasource.Length > 0 && !string.IsNullOrEmpty(datasource[0].UpdateCommandName) ? datasource[0].UpdateCommandName : "Update" + (tables.Length > 0 && !string.IsNullOrEmpty(tables[0].Name) ? tables[0].Name : type.Name); info.SelectCommandName = datasource.Length > 0 && !string.IsNullOrEmpty(datasource[0].SelectCommandName) ? datasource[0].SelectCommandName : "Select" + (tables.Length > 0 && !string.IsNullOrEmpty(tables[0].Name) ? tables[0].Name : type.Name); info.DataSetAdapterName = datasource.Length > 0 && !string.IsNullOrEmpty(datasource[0].DataSetAdapterName) ? datasource[0].DataSetAdapterName : (tables.Length > 0 && !string.IsNullOrEmpty(tables[0].Name) ? tables[0].Name : type.Name) + "Adapter"; mappingCache.Add(string.Format("GetDataSourceInfo({0})", type.FullName), info, CacheItemPriority.None, null, new SlidingTime(TimeSpan.FromMinutes(15))); } catch (Exception ex) { throw ex; } return info; }
public ConfigDataTypeAttribute( Type configDataType ) { if ( configDataType == null ) { throw new ArgumentNullException( "configDataType", "The given config data type must not be null." ); } bool isSerializable = false; bool isXmlRoot = false; bool overridesEquals = false; //bool isEquatable = false; // check if overrides object.Equals() foreach ( var info in configDataType.GetMethods() ) { if ( info.Name.Equals( "Equals" ) && info.DeclaringType.Equals( configDataType ) && info.GetBaseDefinition().DeclaringType.Equals( typeof( object ) ) ) { overridesEquals = true; break; } } // check if serializable if ( configDataType.GetCustomAttributes( typeof( SerializableAttribute ), false ).Length > 0 ) { isSerializable = true; } // check if xmlroot if ( configDataType.GetCustomAttributes( typeof( System.Xml.Serialization.XmlRootAttribute ), false ).Length > 0 ) { isXmlRoot = true; } // make sure config data type overrides object.Equals() if ( !overridesEquals ) { throw new ArgumentException( "The given configuratioun data type '" + configDataType.FullName + "' must override 'object.Equals(object obj)'.", "configDataType" ); } // make sure config data type is serializable if ( !isSerializable ) { throw new ArgumentException( "The given configuratioun data type '" + configDataType.FullName + "' must be decorated with the 'System.SerializableAttribute'.", "configDataType" ); } // make sure the config data type is an xml root if ( !isXmlRoot ) { throw new ArgumentException( "The given configuration data type '" + configDataType.FullName + "' must be decorated with the 'System.Xml.Serialization.XmlRootAttribute'.", "configDataType" ); } // store data type this.ConfigDataType = configDataType; }
private void _AppendAttributes(Type modelType, WrappedStringBuilder sb,bool minimize) { if (modelType.GetCustomAttributes(typeof(ModelViewAttribute), false).Length > 0) { sb.Append((minimize ? "attributes:{":"\tattributes: {")); object[] atts = modelType.GetCustomAttributes(typeof(ModelViewAttribute),false); for (int x = 0; x < atts.Length; x++) sb.Append((minimize ? "" : "\t\t")+"\"" + ((ModelViewAttribute)atts[x]).Name + "\" : '" + ((ModelViewAttribute)atts[x]).Value + "'" + (x < atts.Length - 1 ? "," : "")); sb.Append((minimize ? "" : "\t")+"},"); } }
private TaskDefinition LoadAttributesAsDomainModel(Type type) { object[] taskAttributes = type.GetCustomAttributes(typeof(TaskAttribute), true); object[] settingAttributes = type.GetCustomAttributes(typeof(TaskSettingAttribute), true); bool typeHasAttributes = (taskAttributes.Count() > 0 && taskAttributes is TaskAttribute[]); if (!typeHasAttributes) return null; return ToDomainModel(((TaskAttribute[])taskAttributes)[0], settingAttributes); }
public PossibleLogger(Assembly assembly, Type typeInAssembly) { Assembly = assembly; TypeInAssembly = typeInAssembly; ExtensionUri = typeInAssembly.GetCustomAttributes(typeof(ExtensionUriAttribute), false) .OfType<ExtensionUriAttribute>() .FirstOrDefault(); FriendlyName = typeInAssembly.GetCustomAttributes(typeof(FriendlyNameAttribute), false) .OfType<FriendlyNameAttribute>() .FirstOrDefault(); }
public static FileHelperEngine GetEngineForType(Type recordType) { FileHelperEngine rtnVal; if (recordType.GetCustomAttributes(false).Count(p => p.GetType() == typeof(DelimitedRecordAttribute)) == 1) rtnVal = new DelimitedFileEngine(recordType); else if (recordType.GetCustomAttributes(false).Count(p => p.GetType() == typeof(FixedLengthRecordAttribute)) == 1) rtnVal = new FixedFileEngine(recordType); else throw new InvalidOperationException(String.Format("Record type {0} is not a Filehelpers class", recordType)); return rtnVal; }
IEnumerable<ITypeAmendment> IAmendmentAttribute.GetAmendments(Type target) { // Class does not implement INotifyPropertyChanged. Implement it for the user. if (target.GetCustomAttributes(typeof(NotifyPropertyChangedAttribute), true).Length > 0 && target.GetInterface("System.ComponentModel.INotifyPropertyChanged") == null) yield return (ITypeAmendment)typeof(NotificationAmendment<>).MakeGenericType(target).GetConstructor(Type.EmptyTypes).Invoke(new object[0]); // Class implements INotifyPropertyChangedAmendment so that user can fire custom notificaitons if (target.GetCustomAttributes(typeof(NotifyPropertyChangedAttribute), true).Length > 0 && target.GetInterface("NotifyPropertyChanged.INotifyPropertyChangedAmendment") != null) yield return (ITypeAmendment)typeof(SimpleNotificationAmendment<>).MakeGenericType(target).GetConstructor(Type.EmptyTypes).Invoke(new object[0]); }
public override bool IsComponent(Type type) { if (type.GetCustomAttributes(typeof(ComponentAttribute), false).Any()) { return true; } if (type.GetCustomAttributes(typeof(EntityAttribute), false).Any()) { return false; } return base.IsComponent(type); }
public void GenerateRoutesForController(RouteTree routeTree, Type controllerType) { var routeAttributes = controllerType.GetCustomAttributes(typeof(RouteAttribute), true); var routeAttribute = routeAttributes.Length > 0 ? (RouteAttribute)routeAttributes[0] : null; string route; if (routeAttribute == null) route = GenerateDefaultRouteForController(controllerType); else route = routeAttribute.Value; var routePath = new RoutePath(route); var currentNode = (IRouteNode)routeTree; var leafNodes = new List<RouteNode>(); do { RouteNode nextNode = null; if (routePath.Current != null) { var routePart = routePath.Consume(); var part = new RouteLiteral(routePart, true); nextNode = new RouteNode(part); AddNode(currentNode, nextNode); if (routePath.Current == null) { part.RouteData[RouteData.ControllerKey] = controllerType; leafNodes.Add(nextNode); } } // If defined as a default route, then we don't require the last path part if (routePath.Current == null) { var defaultAttributes = controllerType.GetCustomAttributes(typeof(DefaultAttribute), true); if (defaultAttributes.Length > 0) { var defaultNode = new RouteNode(new RouteDefault(RouteData.ControllerKey, controllerType)); AddNode(currentNode, defaultNode); leafNodes.Add(defaultNode); } } currentNode = nextNode; } while (routePath.Current != null); foreach (var method in controllerType.GetMethods().Where(x => x.IsPublic && !x.IsStatic && (typeof(ActionResult).IsAssignableFrom(x.ReturnType) || typeof(Task<ActionResult>).IsAssignableFrom(x.ReturnType)))) { GenerateRoutesForAction(routeTree, controllerType, leafNodes, method); } }
/// <summary> /// Returns the xml qualified name for the specified system type id. /// </summary> /// <remarks> /// Returns the xml qualified name for the specified system type id. /// </remarks> /// <param name="systemType">The underlying type to query and return the Xml qualified name of</param> public static XmlQualifiedName GetXmlName(System.Type systemType) { if (systemType == null) { return(null); } object[] attributes = systemType.GetCustomAttributes(typeof(DataContractAttribute), true); if (attributes != null) { for (int ii = 0; ii < attributes.Length; ii++) { DataContractAttribute contract = attributes[ii] as DataContractAttribute; if (contract != null) { if (String.IsNullOrEmpty(contract.Name)) { return(new XmlQualifiedName(systemType.Name, contract.Namespace)); } return(new XmlQualifiedName(contract.Name, contract.Namespace)); } } } attributes = systemType.GetCustomAttributes(typeof(CollectionDataContractAttribute), true); if (attributes != null) { for (int ii = 0; ii < attributes.Length; ii++) { CollectionDataContractAttribute contract = attributes[ii] as CollectionDataContractAttribute; if (contract != null) { if (String.IsNullOrEmpty(contract.Name)) { return(new XmlQualifiedName(systemType.Name, contract.Namespace)); } return(new XmlQualifiedName(contract.Name, contract.Namespace)); } } } return(new XmlQualifiedName(systemType.FullName)); }
IEnumerable<ITypeAmendment> IAmendmentAttribute.GetAmendments(Type target) { if (target.GetCustomAttributes(typeof(AuditableAttribute), true).Length > 0) { ConstructorInfo constructorInfo = typeof(AuditableAmender<>).MakeGenericType(target).GetConstructor(Type.EmptyTypes); if (constructorInfo != null) yield return (ITypeAmendment)constructorInfo.Invoke(new object[0]); } if (target.GetCustomAttributes(typeof(ArchivableAttribute), true).Length > 0) { ConstructorInfo constructorInfo = typeof(ArchivableAmender<>).MakeGenericType(target).GetConstructor(Type.EmptyTypes); if (constructorInfo != null) yield return (ITypeAmendment)constructorInfo.Invoke(new object[0]); } }
IEnumerable<ITypeAmendment> IAmendmentAttribute.GetAmendments(Type target) { if (target.GetCustomAttributes(typeof(ExplicitImplementationAttribute), true).Length > 0) { ConstructorInfo constructorInfo = typeof(ExplicitInterfaceAmendment<>).MakeGenericType(target).GetConstructor(Type.EmptyTypes); if (constructorInfo != null) yield return (ITypeAmendment)constructorInfo.Invoke(new object[0]); } if (target.GetCustomAttributes(typeof(ImplicitImplementationAttribute), true).Length > 0) { ConstructorInfo constructorInfo = typeof(ImplicitInterfaceAmendment<>).MakeGenericType(target).GetConstructor(Type.EmptyTypes); if (constructorInfo != null) yield return (ITypeAmendment)constructorInfo.Invoke(new object[0]); } }
public static TypeMap CreateTypeMap (Type type) { object [] atts = type.GetCustomAttributes (typeof (DataContractAttribute), true); if (atts.Length == 1) return CreateTypeMap (type, (DataContractAttribute) atts [0]); atts = type.GetCustomAttributes (typeof (SerializableAttribute), false); if (atts.Length == 1) return CreateTypeMap (type, null); if (IsPrimitiveType (type)) return null; return CreateDefaultTypeMap (type); }
private static GUIContent GetGUIContentFormObject(System.Object obj, string name, int index = 0) { GUIContent guiContent; if (obj == null) { if (name != null) { guiContent = new GUIContent(ObjectNames.NicifyVariableName(name)); } else { guiContent = new GUIContent("Element " + index); } } else { System.Type type = obj.GetType(); if (name != null) { guiContent = new GUIContent(ObjectNames.NicifyVariableName(name)); } else { FieldInfo nameField = type.GetField("name", BindingFlags.IgnoreCase); if (nameField != null && nameField.FieldType == typeof(string)) { guiContent = new GUIContent(ObjectNames.NicifyVariableName((string)nameField.GetValue(obj))); } else { guiContent = new GUIContent("Element " + index); } } bool hideInInspector = (type.GetCustomAttributes(typeof(HideInInspector), true) as HideInInspector[]).Length > 0; if (hideInInspector) { return(null); } TooltipAttribute[] tooltips = type.GetCustomAttributes(typeof(TooltipAttribute), true) as TooltipAttribute[]; if (tooltips != null && tooltips.Length > 0) { guiContent.tooltip = tooltips[0].Tooltip; } } return(guiContent); }
private static List <MemberData <T> > GetMembers <T>(System.Type type, Func <BindingFlags, T[]> getter, BindingFlags defaultFlags) where T : MemberInfo { var attributes = type.GetCustomAttributes(typeof(CoherentType), true); if (attributes.Length > 0) { var coherentType = (CoherentType)attributes[0]; var members = getter(coherentType.GetBindingFlags()); var result = new List <MemberData <T> >(members.Length); foreach (var member in members) { var memberAttributes = member.GetCustomAttributes(typeof(CoherentProperty), false); if (memberAttributes.Length > 0) { var attribute = (CoherentProperty)memberAttributes[0]; result.Add(new MemberData <T>(member, attribute.PropertyName)); } else if (coherentType.Flags != PropertyBindingFlags.Explicit) { result.Add(new MemberData <T>(member)); } } return(result); } var defaultMembers = getter(defaultFlags); var defaultResult = new List <MemberData <T> >(defaultMembers.Length); foreach (var member in defaultMembers) { defaultResult.Add(new MemberData <T>(member)); } return(defaultResult); }
public void Start() { // 收集所有网络协议的类型 List <Type> types = ILRManager.Instance.HotfixAssemblyTypes; for (int i = 0; i < types.Count; i++) { System.Type type = types[i]; // 判断属性标签 if (Attribute.IsDefined(type, typeof(NetMessageAttribute))) { var attributeArray = type.GetCustomAttributes(typeof(NetMessageAttribute), false); NetMessageAttribute attribute = attributeArray[0] as NetMessageAttribute; // 判断是否重复 if (_msgTypes.ContainsKey(attribute.MsgType)) { throw new Exception($"Message {type} has same value : {attribute.MsgType}"); } // 添加到集合 _msgTypes.Add(attribute.MsgType, type); } } // 注册消息接收回调 NetManager.Instance.HotfixProtoCallback += OnHandleHotfixMsg; }
// In order to not break references when a class is renamed, we want to use the GUID instead. If the class is // a MonoBehaviour that does not live in its own file (it won't have its own GUID), throw an error unless // the users has waived this protection by using the WeakClassReferenceAttribute. public static int ClassHashFromType(System.Type t) { if (typeof(MonoBehaviour).IsAssignableFrom(t)) { // If the type has been decorated with the WeakClassReferenceAttribute, it's ok to just use the name if (t.GetCustomAttributes().Any(a => { return(a.GetType() == typeof(WeakClassReferenceAttribute)); })) { // Use name for hash } else { // Check player prefs to see if we've cached this GUID before string cachedGUID = GetCachedClassGUID(t); if (!string.IsNullOrEmpty(cachedGUID)) { return(cachedGUID.GetHashCode()); } // Scan the filesystem for a file matching the type, assuming that MonoBehaviours live in script // files with the same name var path = FileSystemUtil.FindScriptFileForClass(t); Debug.Assert(!string.IsNullOrEmpty(path), $"Unable to find script representing class {t.Name}. Either put this class in its own script file, or use the [WeakClassReferenceAttribute] attribute. This attribute means you accept the risk of breaking any references to these classes if they are renamed."); path = FileSystemUtil.SystemPathToAssetPath(path); string guid = AssetDatabase.AssetPathToGUID(path); Debug.Assert(!string.IsNullOrEmpty(guid), $"Unable to locate GUID for file {path}"); SetCachedClassGUID(t, guid); return(guid.GetHashCode()); } } return(t.FullName.GetHashCode()); }
private static void InvokeClassInitializers(GType gtype, System.Type t) { object[] parms = { gtype, t }; BindingFlags flags = BindingFlags.Static | BindingFlags.NonPublic; foreach (TypeInitializerAttribute tia in t.GetCustomAttributes(typeof(TypeInitializerAttribute), true)) { MethodInfo m = tia.Type.GetMethod(tia.MethodName, flags); if (m != null) { m.Invoke(null, parms); } } for (Type curr = t; curr != typeof(GLib.Object); curr = curr.BaseType) { if (curr.Assembly.IsDefined(typeof(IgnoreClassInitializersAttribute), false)) { continue; } foreach (MethodInfo minfo in curr.GetMethods(flags)) { if (minfo.IsDefined(typeof(ClassInitializerAttribute), true)) { minfo.Invoke(null, parms); } } } }
public Type(System.Type buildFrom) { cachedType = buildFrom; neo4JAttributes = buildFrom.GetCustomAttributes(true) .Where(x => x is INeo4jAttribute) .Cast <INeo4jAttribute>() .ToArray(); props = buildFrom.GetProperties() .ToDictionary( x => x.Name, x => new Property(x) ); parentNodeRequired = neo4JAttributes.Where(x => { DbRequireParentAttribute dbRequireParent = x as DbRequireParentAttribute; return(dbRequireParent != null && dbRequireParent.parentNodeRequired); }).Any(); try { ID = props.Where(x => x.Value.isID).Single().Value; } catch { if (typeof(INeo4jNode).IsAssignableFrom(buildFrom)) { throw new ArgumentException("All types of INeo4jNode must declare an ID (and only one ID)"); } else { ID = null; } } }
protected override void Init(MyObjectBuilder_DefinitionBase builder) { base.Init(builder); var ob = builder as MyObjectBuilder_EnvironmentItemsDefinition; MyDebug.AssertDebug(ob != null); m_itemDefinitions = new HashSet <MyStringHash>(MyStringHash.Comparer); m_definitionList = new List <MyStringHash>(); System.Type classType = builder.Id.TypeId; var attribs = classType.GetCustomAttributes(typeof(MyEnvironmentItemsAttribute), inherit: false); Debug.Assert(attribs.Length <= 1, "Environment item class can only have one EnvironmentItemDefinition attribute!"); if (attribs.Length == 1) { var attrib = attribs[0] as MyEnvironmentItemsAttribute; m_itemDefinitionType = attrib.ItemDefinitionType; } else { m_itemDefinitionType = typeof(MyObjectBuilder_EnvironmentItemDefinition); } Channel = ob.Channel; MaxViewDistance = ob.MaxViewDistance; SectorSize = ob.SectorSize; ItemSize = ob.ItemSize; Material = MyStringHash.GetOrCompute(ob.PhysicalMaterial); Frequencies = new List <float>(); }
public BuildStepProviderEntry(System.Type pType) { if (pType == null) { mName = "None"; return; } mType = pType; mName = mType.Name; mNamespace = mType.Namespace; foreach (var a in mType.GetCustomAttributes(true)) { if (a is BuildStepDescriptionAttribute) { mDescription = a as BuildStepDescriptionAttribute; } else if (a is BuildStepPlatformFilterAttribute) { mPlatformFilter = a as BuildStepPlatformFilterAttribute; } else if (a is BuildStepTypeFilterAttribute) { mTypeFilter = a as BuildStepTypeFilterAttribute; } else if (a is BuildStepParameterFilterAttribute) { mParameterFilter = a as BuildStepParameterFilterAttribute; } } }
private static bool BuildConfigConvertClass(System.Type t) { if (t == null) { return(false); } // 先找标记了的类 bool ret = false; object[] attrs = t.GetCustomAttributes(false); if (attrs != null && attrs.Length > 0) { for (int i = 0; i < attrs.Length; ++i) { ConfigConvertAttribute attr = attrs[i] as ConfigConvertAttribute; if (attr == null || string.IsNullOrEmpty(attr.ConfigName)) { continue; } ConvertClassInfo info = new ConvertClassInfo(t, attr); m_ConvertClassMap[attr.ConfigName] = info; m_TargetNameMap[info.convertName] = info; ret = true; break; } } return(ret); }
public static bool IsAuthorizedForAction(string actionName, string controllerName) { bool isAuthorized = false; SystemType controller = SystemType.GetType(string.Format(ControllerIdentifier, controllerName)); if (controller != null) { MethodInfo[] mArr = controller.GetMethods().Where(mi => mi.Name == actionName).ToArray <MethodInfo>(); foreach (MethodInfo m in mArr) { RoleAttribute[] authTagList = m.GetCustomAttributes(typeof(RoleAttribute), true) as RoleAttribute[]; if (authTagList.Length < 1) { authTagList = controller.GetCustomAttributes(typeof(RoleAttribute), true) as RoleAttribute[]; } RoleEnum[] authTagArray = authTagList.Select(t => t.Role).ToArray <RoleEnum>(); SimpleUserModel currentUser = (SimpleUserModel)HttpContext.Current.Session["user"]; if (currentUser == null) { currentUser = new SimpleUserModel(); } isAuthorized = Authorize(currentUser, authTagArray); if (isAuthorized) { break; } } } return(isAuthorized); }
public static string CreateTable(System.Type SystemType) { int Seed = 1; foreach (var Attribute in SystemType.GetCustomAttributes(true)) { if (Attribute is AutoAttribute) { AutoAttribute AutoAttribute = (AutoAttribute)Attribute; Seed = AutoAttribute.Seed; break; } } string Query = "\nCREATE TABLE [dbo].[" + EncryptTableName(SystemType.Name) + "] ([ID] INT IDENTITY(" + Seed + ",1) NOT NULL PRIMARY KEY CLUSTERED); "; foreach (System.Reflection.PropertyInfo SystemAttribute in SystemType.GetProperties()) { if (Attribute.IsDefined(SystemAttribute, typeof(NoDataAttribute))) { continue; } if (SystemAttribute.Name != "ID") { Query += AddColumn(SystemAttribute, SystemType.Name, ""); } } return(Query); }
/// <summary> /// Checks specified type if it provides factory or not and then registers it /// if needed /// </summary> /// <param name="aType"> /// Factory type <see cref="System.Type"/> /// </param> public static void RegisterClass(System.Type aType) { if (aType == null) { return; } object[] attrs = (object[])aType.GetCustomAttributes(false); if ((attrs == null) || (attrs.Length == 0)) { return; } Attribute attr; try { foreach (object attrobj in attrs) { if (TypeValidator.IsCompatible(attrobj.GetType(), typeof(Attribute)) == false) { continue; } attr = (Attribute)attrobj; if (TypeValidator.IsCompatible(attr.GetType(), typeof(WidgetFactoryProviderAttribute)) == true) { AddClass(aType, (WidgetFactoryProviderAttribute)attr); } if (TypeValidator.IsCompatible(attr.GetType(), typeof(CellFactoryProviderAttribute)) == true) { AddClass(aType, (CellFactoryProviderAttribute)attr); } } } catch {} }
public void AddUsableEffectHandler(UsableEffectHandler handler) { System.Type type = handler.GetType(); if (type.GetCustomAttribute <DefaultEffectHandlerAttribute>() != null) { throw new System.Exception("Default handler cannot be added"); } EffectHandlerAttribute[] array = type.GetCustomAttributes <EffectHandlerAttribute>().ToArray <EffectHandlerAttribute>(); if (array.Length == 0) { throw new System.Exception(string.Format("EffectHandler '{0}' has no EffectHandlerAttribute", type.Name)); } System.Reflection.ConstructorInfo constructor = type.GetConstructor(new System.Type[] { typeof(EffectBase), typeof(Character), typeof(BasePlayerItem) }); if (constructor == null) { throw new System.Exception("No valid constructors found !"); } foreach (EffectsEnum current in from entry in array select entry.Effect) { this.m_usablesEffectHandler.Add(current, constructor.CreateDelegate <EffectManager.UsableEffectConstructor>()); if (!this.m_effectsHandlers.ContainsKey(current)) { this.m_effectsHandlers.Add(current, new System.Collections.Generic.List <System.Type>()); } this.m_effectsHandlers[current].Add(type); } }
public static WADLResource GetWADLResource(System.Type type, Uri baseUri) { WADLResource resource = (WADLResource)type.GetCustomAttributes(typeof(WADLResource), true).Single <object>(); resource.BaseUri = baseUri; return(resource); }
private void WriteAttributes(System.Type t, StreamWriter s) { foreach (System.Object attr in t.GetCustomAttributes(false)) { System.Type attribType = attr.GetType(); s.Write("["); s.Write(GetTypeName(attribType)); ConstructorInfo[] constructors = attribType.GetConstructors(BindingFlags.Public); if (constructors.Length > 0) { s.Write("("); bool first = true; foreach (ParameterInfo pi in constructors[0].GetParameters()) { if (first) { first = false; } else { s.Write(", "); } GetTypeDefault(pi.ParameterType); } s.Write(")"); } s.Write("]\n"); } }
public static WADLApplication GetWADLApplication(System.Type type) { WADLApplication application = (WADLApplication)type.GetCustomAttributes(typeof(WADLApplication), true).Single <object>(); application.Doc = WADLDoc.GetWADLDoc(type); return(application); }
private static System.Type[] GetRequiredComponents(System.Type klass) { List <System.Type> list = null; while ((klass != null) && (klass != typeof(MonoBehaviour))) { RequireComponent[] customAttributes = (RequireComponent[])klass.GetCustomAttributes(typeof(RequireComponent), false); System.Type baseType = klass.BaseType; foreach (RequireComponent component in customAttributes) { if (((list == null) && (customAttributes.Length == 1)) && (baseType == typeof(MonoBehaviour))) { return(new System.Type[] { component.m_Type0, component.m_Type1, component.m_Type2 }); } if (list == null) { list = new List <System.Type>(); } if (component.m_Type0 != null) { list.Add(component.m_Type0); } if (component.m_Type1 != null) { list.Add(component.m_Type1); } if (component.m_Type2 != null) { list.Add(component.m_Type2); } } klass = baseType; } return(list?.ToArray()); }
public static void DisplayFixes(System.Type t) { object[] fixes = t.GetCustomAttributes(typeof(BugFixAttribute), false); Console.WriteLine("Displaying fixes for {0}", t); foreach (BugFixAttribute bugFix in fixes) { Console.WriteLine(" {0}", bugFix); } foreach (MemberInfo member in t.GetMembers(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)) { object[] memberFixes = member.GetCustomAttributes(typeof(BugFixAttribute), false); if (memberFixes.Length > 0) { Console.WriteLine(" {0}", member.Name); foreach (BugFixAttribute memberFix in memberFixes) { Console.WriteLine(" {0}", memberFix); } } } }
/// <summary> /// Verifies the ConfirmImpact level on a cmdlet. /// </summary> /// <param name="cmdlet">The cmdlet to check.</param> /// <param name="confirmImpact">The expected confirm impact.</param> public static void CheckConfirmImpact(Type cmdlet, ConfirmImpact confirmImpact) { object[] cmdletAttributes = cmdlet.GetCustomAttributes(typeof(CmdletAttribute), true); Assert.AreEqual(1, cmdletAttributes.Length); CmdletAttribute attribute = (CmdletAttribute)cmdletAttributes[0]; Assert.AreEqual(confirmImpact, attribute.ConfirmImpact); }
//make sure the class has the proper declaration. public string _get_primary_key_name(System.Type t) { object[] attributes = t.GetCustomAttributes(typeof(OOD.SchemaDefine), true); if (attributes != null && attributes.Length == 1) { SchemaDefine declared = (SchemaDefine)attributes[0]; string pk = declared.PrimaryKey; FieldInfo pkField = t.GetField(pk, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); if (pkField == null) { throw new OOD.Exception.MissingPrimaryKey( this, "Primary key field is not found."); } if (pkField.IsStatic || pkField.IsInitOnly) { throw new OOD.Exception.MissingPrimaryKey( this, "Primary key can not defined on the static field member or initialize only field."); } return(pk); } else { throw new OOD.Exception.MissingPrimaryKey( this, "Primary key is not defined."); } }
public void Add(Type serviceType, Type requestType, Type responseType) { this.ServiceTypes.Add(serviceType); this.RequestTypes.Add(requestType); var restrictTo = requestType.GetCustomAttributes(true) .OfType<RestrictAttribute>().FirstOrDefault() ?? serviceType.GetCustomAttributes(true) .OfType<RestrictAttribute>().FirstOrDefault(); var operation = new Operation { ServiceType = serviceType, RequestType = requestType, ResponseType = responseType, RestrictTo = restrictTo, Actions = GetImplementedActions(serviceType, requestType), Routes = new List<RestPath>(), }; this.OperationsMap[requestType] = operation; this.OperationNamesMap[requestType.Name.ToLower()] = operation; if (responseType != null) { this.ResponseTypes.Add(responseType); this.OperationsResponseMap[responseType] = operation; } }
/// <summary> /// Genera el nombre del armador. /// </summary> /// <param name="t"></param> protected void GenerarNombreArmador(Type t) { try { foreach (object tab in t.GetCustomAttributes(true)) { if (tab.GetType().Equals(typeof(Tabla))) { this.Nombre = ((Tabla)tab).Nombre; break; } } } catch { this.Nombre = ""; } finally { if (this.Nombre.Equals("")) { this.Nombre = t.Name; } } }
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName) { var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName); if (containerType == null || propertyName == null) return metadata; if (containerType.GetCustomAttributes(typeof(LocalizedAttribute), true).Length == 0) return metadata; if (CultureInfo.CurrentCulture.LCID == DefaultCulture.Value.LCID) return metadata; var obj = LocalizationManager.Instance.FormatScope(containerType); var translation = LocalizationManager.Instance.Translate(obj, propertyName + "_DisplayName"); metadata.DisplayName = string.IsNullOrEmpty(translation) ? metadata.DisplayName ?? propertyName : translation; // process other metadata if it needed // Watermark, Description, NullDisplayText, ShortDisplayName return metadata; }
private static IControllerBinding[] GetControllerBindings(Type type) { IControllerBinding[] bindings; if (!_typeControllers.TryGetValue(type, out bindings)) { lock(_typeControllers) { object[] attributes = type.GetCustomAttributes(typeof(IControllerBinding), false); if (attributes.Length == 0) { if (typeof(IController).IsAssignableFrom(type)) { IControllerBinding b = new ControllerAttribute(); b.Initialize(type); bindings = new IControllerBinding[] { b }; } else return null; } else { bindings = new IControllerBinding[attributes.Length]; for (int i = 0; i < attributes.Length; i++) { IControllerBinding b = (IControllerBinding)attributes[i]; b.Initialize(type); bindings[i] = b; } } _typeControllers.Add(type, bindings); } } return bindings; }
private void ProcessObjectForDelete(object objectToDelete, Type objectType, Stack<SqlCommand> deleteFirstCommands, Stack<SqlCommand> deleteCommands) { PersistentClass persistentClassAttribute = (PersistentClass)objectType.GetCustomAttributes(typeof(PersistentClass), false).Single(); PropertyInfo keyProperty = objectType.GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(PersistentPrimaryKeyProperty))).Single(); PropertyBridge keyPropertyBridge = PropertyBridgeFactory.GetPropertyBridge(keyProperty, objectToDelete); if (persistentClassAttribute.IsPersisted == true) { if (persistentClassAttribute.IsManyToManyRelationship == true) { deleteFirstCommands.Push(this.CreateSqlCommand(keyPropertyBridge, persistentClassAttribute.StorageName)); } else { deleteCommands.Push(this.CreateSqlCommand(keyPropertyBridge, persistentClassAttribute.StorageName)); } } if (persistentClassAttribute.HasPersistentBaseClass == true) { if (persistentClassAttribute.IsManyToManyRelationship == true) { deleteFirstCommands.Push(this.CreateSqlCommand(keyPropertyBridge, persistentClassAttribute.BaseStorageName)); } else { deleteCommands.Push(this.CreateSqlCommand(keyPropertyBridge, persistentClassAttribute.BaseStorageName)); } } }
private int GetPriority(Type type) { var attribute = type.GetCustomAttributes(typeof (InstallerPriorityAttribute), false).FirstOrDefault() as InstallerPriorityAttribute; return attribute != null ? attribute.Priority : InstallerPriorityAttribute.DefaultPriority; }
private static void FindTypeAttributes <T>(ShadowAssemblyType shadowAssembly, System.Type type, List <AttributeResult <T> > attributesFound) where T : Attribute { try { var typeAttributes = type .GetCustomAttributes(true) .Where( attr => attr.GetType().FullName == typeof(T).FullName) .ToList(); if (typeAttributes.Count > 0) { var attribute = typeAttributes.Cast <T>().First(); var info = new AttributeResult <T>(shadowAssembly, type, attribute); attributesFound.Add(info); } } catch (Exception err1) { "CryoAOP -> Warning! First chance exception ocurred while searching for Mixin Methods. \r\n{0}" .Warn(err1); } }
/// <summary> /// Redirects the a type to another type. Attempts to create an Old /// will result in a New being created instead. /// </summary> /// <param name="oldType">Old type, being redirected.</param> /// <param name="newType">The new type to redirect to.</param> public void Redirect(System.Type oldType, System.Type newType) { if (oldType.GetCustomAttributes(typeof(LockedContentAttribute), true).Length != 0) { return; } this._redirections[oldType] = newType; }
/// <summary>Removes a type from the type pool.</summary> /// <param name="type">The type.</param> public void Remove(System.Type type) { if (!this._types.Contains(type) || type.GetCustomAttributes(typeof(LockedContentAttribute), true).Length != 0) { return; } this._types.Remove(type); }
private string TableOf(Type type) { var name = type .GetCustomAttributes(typeof (TableMappingAttribute), false) .Cast<TableMappingAttribute>() .Single().Name; return nameBuilder.ApplyNamingRules(name); }
private RealTimeCacheHelper ParseCacheTimelinessHelper(System.Type t) { RealTimeCacheHelper realTimeCacheHelper = null; object[] customAttributes = t.GetCustomAttributes(typeof(CacheSettingAttribute), true); if (customAttributes.Length > 0) { CacheSettingAttribute cacheSettingAttribute = customAttributes[0] as CacheSettingAttribute; if (cacheSettingAttribute != null) { realTimeCacheHelper = new RealTimeCacheHelper(cacheSettingAttribute.EnableCache, this.TypeHashID); if (cacheSettingAttribute.EnableCache) { switch (cacheSettingAttribute.ExpirationPolicy) { case EntityCacheExpirationPolicies.Stable: realTimeCacheHelper.CachingExpirationType = CachingExpirationType.Stable; goto IL_89; case EntityCacheExpirationPolicies.Usual: realTimeCacheHelper.CachingExpirationType = CachingExpirationType.UsualSingleObject; goto IL_89; } realTimeCacheHelper.CachingExpirationType = CachingExpirationType.SingleObject; IL_89: System.Collections.Generic.List <System.Reflection.PropertyInfo> list = new System.Collections.Generic.List <System.Reflection.PropertyInfo>(); if (!string.IsNullOrEmpty(cacheSettingAttribute.PropertyNamesOfArea)) { string[] array = cacheSettingAttribute.PropertyNamesOfArea.Split(new char[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries); string[] array2 = array; for (int i = 0; i < array2.Length; i++) { string name = array2[i]; System.Reflection.PropertyInfo property = t.GetProperty(name); if (property != null) { list.Add(property); } } } realTimeCacheHelper.PropertiesOfArea = list; if (!string.IsNullOrEmpty(cacheSettingAttribute.PropertyNameOfBody)) { System.Reflection.PropertyInfo property2 = t.GetProperty(cacheSettingAttribute.PropertyNameOfBody); realTimeCacheHelper.PropertyNameOfBody = property2; } } } } if (realTimeCacheHelper == null) { realTimeCacheHelper = new RealTimeCacheHelper(true, this.TypeHashID); } return(realTimeCacheHelper); }
private static EntityAttribute GetEntityAttribute(System.Type entity_type) { object[] attr_array = entity_type.GetCustomAttributes(typeof(EntityAttribute), false); if (attr_array.Length > 0) { return(attr_array[0] as EntityAttribute); } throw new ApplicationException(string.Format("{0} does not implementation Entity Attribute.", entity_type.FullName)); }
public static ITypeSerialize GetByType(System.Type type) { ITypeSerialize ts = null; string fullname = type.FullName; if (AllTypes.TryGetValue(fullname, out ts)) { return(ts); } if (Help.isType(type, typeof(UnityEngine.Object))) { ts = unityObjectSerialize; } else { if (type.IsEnum) { #if USE_HOT if (type is ILRuntimeType) { ts = new HotEnumTypeSerialize((ILRuntimeType)type); } else { #endif ts = new EnumTypeSerialize(type); #if USE_HOT } #endif } else if (type.IsArray) { ts = new ArrayAnyType(type); } else if (Help.isListType(type)) { ts = new ListAnyType(type); } else { var atts = type.GetCustomAttributes(typeof(SmartAttribute), false); if (atts != null && atts.Length > 0) { ts = new SmartSerializer(type, new AnyTypeSerialize(type, Help.GetSerializeField(type))); } else { List <FieldInfo> fieldinfos = Help.GetSerializeField(type); ts = new AnyTypeSerialize(type, fieldinfos); } } } AllTypes.Add(fullname, ts); return(ts); }