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;
        }
        /// <summary>
        /// Copies the EventSourceAttribute from the interfaceType to a CustomAttributeBuilder.
        /// </summary>
        /// <param name="type">The interfaceType to copy.</param>
        /// <returns>A CustomAttributeBuilder that can be assigned to a type.</returns>
        internal static CustomAttributeBuilder GetEventSourceAttributeBuilder(Type type)
        {
            var attribute = type.GetCustomAttribute<EventSourceAttribute>() ?? new EventSourceAttribute();
            var implementation = type.GetCustomAttribute<EventSourceImplementationAttribute>() ?? new EventSourceImplementationAttribute();

            // by default, we will use a null guid, which will tell EventSource to generate the guid from the name
            // but if we have already generated this type, we will have to generate a new one
            string guid = implementation.Guid ?? attribute.Guid ?? null;
            if (guid == null)
            {
                lock (_typesImplemented)
                {
                    if (_typesImplemented.Contains(type))
                        guid = Guid.NewGuid().ToString();
                    else
                        _typesImplemented.Add(type);
                }
            }

            var propertyValues = new object[]
            {
                implementation.Name ?? attribute.Name ?? (type.IsGenericType ? type.FullName : type.Name),
                guid,
                implementation.LocalizationResources ?? attribute.LocalizationResources ?? null
            };

            CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(
                _eventSourceAttributeConstructor,
                _emptyParameters,
                _eventSourceAttributePropertyInfo,
                propertyValues);

            return attributeBuilder;
        }
Ejemplo n.º 3
0
        public static TypeInfo Create(Type rootType, Func<Type, IEntityMetaDataProvider> provider)
        {
            if (null == rootType)
                throw new ArgumentNullException(nameof(rootType));
            if (null == provider)
                throw new ArgumentNullException(nameof(provider));

            TypeInfo typeInfo = new TypeInfo();

            typeInfo.Id = rootType.FullName; //NosQL Id.

            typeInfo.Pageable = rootType.GetCustomAttribute<GridPageableAttribute>();


            typeInfo.Sortable = rootType.GetCustomAttribute<GridSortableAttribute>();

            typeInfo.Filterable = rootType.GetCustomAttribute<GridFilterableAttribute>();

            typeInfo.Editable = rootType.GetCustomAttribute<GridEditableAttribute>();

            GridAttribute ga = rootType.GetCustomAttribute<GridAttribute>();
            if (null != ga)
            {
                typeInfo.Groupable = ga.Groupable;
                typeInfo.Height = ga.Height;
            }


            LoadFields(typeInfo, null, rootType, provider);

            return typeInfo;
        }
        internal static string BuildResourceKey(Type containerType, string propertyName, string separator = ".")
        {
            var modelAttribute = containerType.GetCustomAttribute<LocalizedModelAttribute>();

            var pi = containerType.GetProperty(propertyName);
            if(pi != null)
            {
                var propertyResourceKeyAttribute = pi.GetCustomAttribute<ResourceKeyAttribute>();
                if(propertyResourceKeyAttribute != null)
                {
                    // check if container type has resource key set
                    var prefix = string.Empty;
                    if(!string.IsNullOrEmpty(modelAttribute?.KeyPrefix))
                        prefix = modelAttribute.KeyPrefix;

                    var resourceAttributeOnClass = containerType.GetCustomAttribute<LocalizedResourceAttribute>();
                    if(!string.IsNullOrEmpty(resourceAttributeOnClass?.KeyPrefix))
                        prefix = resourceAttributeOnClass.KeyPrefix;

                    return prefix.JoinNonEmpty(string.Empty, propertyResourceKeyAttribute.Key);
                }
            }

            // we need to understand where to look for the property
            // 1. verify that property is declared on the passed in container type
            if(modelAttribute == null || modelAttribute.Inherited)
                return containerType.FullName.JoinNonEmpty(separator, propertyName);

            // 2. if not - then we scan through discovered and cached properties during initial scanning process and try to find on which type that property is declared
            var declaringTypeName = FindPropertyDeclaringTypeName(containerType, propertyName);
            return declaringTypeName != null
                       ? declaringTypeName.JoinNonEmpty(separator, propertyName)
                       : containerType.FullName.JoinNonEmpty(separator, propertyName);
        }
Ejemplo n.º 5
0
        public static void Register(Type type)
        {
            var actor  = type.GetCustomAttribute<ActorAttribute>();
            var worker = type.GetCustomAttribute<WorkerAttribute>();

            if (actor != null && worker != null)
                throw new InvalidOperationException("A type cannot be configured to be both Actor and Worker: " + type);

            factories.Add(type, worker != null 
                                    ? GetWorkerFactory() 
                                    : GetActorFactory(actor));
        }
Ejemplo n.º 6
0
        private void LoadForInside (Type type)
        {

            
            var atts2 = type.GetCustomAttribute<SaguaAllowXiakeTypeAttribute>();
            if (atts2 != null)
                XiakeTypes = atts2.XiakeType;

            var att3 = type.GetCustomAttribute<SaguaLoadWhenLoginModuleAttribute>();
            if (att3 != null)
                IsMustLoged = true;
        }
Ejemplo n.º 7
0
        /// <summary>
        /// get buttons of all services
        /// </summary>
        /// <returns></returns>
        private List <List <BotButtonInfo> > GetListOfServicesButtons(TelegramClientInfo clientInfo)
        {
            List <BotButtonInfo> columns = new List <BotButtonInfo>();

            List <List <BotButtonInfo> > rows = new List <List <BotButtonInfo> >();

            int columnIndex             = 0;
            List <System.Type> services = _serverBase.GetListOfRegistredTypes().ToList();

            for (int i = 0; i < services.Count; i++)
            {
                System.Type item = services[i];
                ServiceContractAttribute attribute = item.GetCustomAttribute <ServiceContractAttribute>();
                if (attribute.ServiceType != ServiceType.HttpService)
                {
                    continue;
                }
                string serviceName = "";
                if (CurrentBotStructureInfo.InitializeServicesFromAttributes)
                {
                    BotDisplayNameAttribute nameAttribute = item.GetCustomAttribute <BotDisplayNameAttribute>();
                    if (nameAttribute == null)
                    {
                        continue;
                    }
                    //serviceName = nameAttribute.Content;
                }

                serviceName = attribute.Name;
                if (!CurrentBotStructureInfo.OnServiceGenerating(serviceName, clientInfo))
                {
                    continue;
                }
                if (!Services.ContainsKey(attribute.Name))
                {
                    Services.Add(serviceName, item);
                }
                if (columnIndex == 3)
                {
                    columnIndex = 0;
                    rows.Add(columns.ToList());
                    columns.Clear();
                }
                columns.Add(GetServiceCaption(item));
                columnIndex++;
            }
            if (rows.Count == 0)
            {
                rows.Add(columns);
            }
            return(rows);
        }
        public static string GetRootElementName(Type objectType, out string rootNamespace)
        {           
            var xmlRootAttribute = objectType.GetCustomAttribute<XmlRootAttribute>(true);
            string elementName;

            if (xmlRootAttribute != null)
            {
                elementName = !String.IsNullOrEmpty(xmlRootAttribute.ElementName) ? xmlRootAttribute.ElementName : objectType.Name;
                rootNamespace = xmlRootAttribute.Namespace;
            }
            else
            {
                elementName = objectType.Name;
                rootNamespace = null;
            }

            var pluralization = PluralizationService.CreateService(CultureInfo.CurrentCulture);

            if (!pluralization.IsPlural(elementName))
            {
                elementName = pluralization.Pluralize(elementName);
            }

            return elementName;
        }
Ejemplo n.º 9
0
 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);
     }
 }
Ejemplo n.º 10
0
        private static bool HasFlagsInternal(Type type)
        {
            Contract.Assert(type != null);

            FlagsAttribute attribute = type.GetCustomAttribute<FlagsAttribute>(inherit: false);
            return attribute != null;
        }
 public override void Process(IReflector reflector, Type type, IMethodRemover methodRemover, ISpecificationBuilder spec) {
     var attr = type.GetCustomAttribute<NakedObjectsTypeAttribute>();
     if (attr == null) {
         RemoveExplicitlyIgnoredMembers(type, methodRemover);
     } else {
         switch (attr.ReflectionScope) {
             case ReflectOver.All:
                 RemoveExplicitlyIgnoredMembers(type, methodRemover);
             break;
             case ReflectOver.TypeOnlyNoMembers:
                 foreach (MethodInfo method in type.GetMethods()) {
                     methodRemover.RemoveMethod(method);
                 }
                 break;
             case ReflectOver.ExplicitlyIncludedMembersOnly:
                 foreach (MethodInfo method in type.GetMethods()) {
                     if (method.GetCustomAttribute<NakedObjectsIncludeAttribute>() == null) {
                         methodRemover.RemoveMethod(method);
                     }
                 }
                 break;
             case ReflectOver.None:
                 throw new ReflectionException("Attempting to introspect a class that has been marked with NakedObjectsType with ReflectOver.None");
             default:
                 throw new ReflectionException(String.Format("Unhandled value for ReflectOver: {0}", attr.ReflectionScope));
         }
     }
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Makes grid from attribute
        /// </summary>
        /// <param name="t">Entity for reflection</param>
        /// <param name="mode">Template render mode</param>
        /// <returns>Grid class</returns>
        public Grid Reflect(Type t, TemplateMode mode)
        {
            var attribute = (GridPropertiesAttribute)t.GetCustomAttribute(typeof(GridPropertiesAttribute));
            if (attribute != null)
            {
                var grid = new Grid(attribute);
                var rows = new List<GridRow>();
                foreach (var property in t.GetProperties())
                {
                    var rowAttribute = (RowDisplayAttribute)property.GetCustomAttribute(typeof(RowDisplayAttribute));
                    if (rowAttribute != null)
                    {
                        if (mode == TemplateMode.ExtendedDisplay || !rowAttribute.ExtendedView)
                        {
                            if (mode == TemplateMode.Edit && rowAttribute.ColumnEditType == GridColumnTypes.DropDown)
                            {
                                rows.Add(new GridRow(t.GetProperty(rowAttribute.DropdownPropertyName), rowAttribute, mode));
                            }
                            else
                            {
                                rows.Add(new GridRow(property, rowAttribute, mode));
                            }
                        }
                    }
                }

                grid.Rows = rows.ToList();
                return grid;
            }

            return null;
        }
Ejemplo n.º 13
0
 public static string GetResourceType(Type t)
 {
     ResourceBaseAttribute propertyResourceAttribute = t.GetCustomAttribute<ResourceBaseAttribute>();
     if (propertyResourceAttribute == null)
         throw new Exception("Invalid relation object in class");
     return propertyResourceAttribute.Id;
 }
Ejemplo n.º 14
0
        /// <summary>
        /// 获取生命周期
        /// </summary>
        public static Lifecycle GetLifecycle(Type type)
        {
            if (!type.IsDefined(typeof(LifeCycleAttribute), false))
                return Lifecycle.Singleton;

            return type.GetCustomAttribute<LifeCycleAttribute>(false).Lifetime;
        }
Ejemplo n.º 15
0
		/// <summary>
		/// Returns the metadata for a PluginController
		/// </summary>
		/// <param name="type"></param>
		/// <returns></returns>
		internal static PluginControllerMetadata GetMetadata(Type type)
		{
			if (!TypeHelper.IsTypeAssignableFrom<PluginController>(type))
			{
				throw new InvalidOperationException("Cannot get metadata from a type that is not a PluginController");
			}

			PluginControllerMetadata meta;
			if (MetadataStorage.TryGetValue(type, out meta))
			{
				return meta;
			}

			var attribute = type.GetCustomAttribute<PluginControllerAttribute>(false);

			meta = new PluginControllerMetadata()
			{
				AreaName = attribute == null ? null : attribute.AreaName,
				ControllerName = ControllerExtensions.GetControllerName(type),
				ControllerNamespace = type.Namespace,
				ControllerType = type
			};

			MetadataStorage.TryAdd(type, meta);

			return meta;
		}
Ejemplo n.º 16
0
 /// <summary>
 /// Creates a new instance based on the specified cmdlet type.
 /// </summary>
 /// <param name="cmdletType">The type of the cmdlet. Must be a sub-class of <see cref="Cmdlet"/>
 /// and have a <see cref="CmdletAttribute"/>.</param>
 public Command(Type cmdletType)
 {
     if (cmdletType == null) throw new ArgumentNullException("cmdletType");
     CmdletType = cmdletType;
     _attribute = CmdletType.GetCustomAttribute<CmdletAttribute>();
     if (_attribute == null) throw new ArgumentException("Missing CmdletAttribute", "cmdletType");
 }
        /// <summary>
        /// Returns a value indicating whether or not a server-side dispatcher should be generated for the provided <paramref name="method"/>.
        /// </summary>
        /// <param name="containingType">
        /// The containing type.
        /// </param>
        /// <param name="method">
        /// The method.
        /// </param>
        /// <returns>
        /// A value indicating whether or not a server-side dispatcher should be generated for the provided <paramref name="method"/>.
        /// </returns>
        public static bool IsVisible(Type containingType, MethodInfo method)
        {
            var typeLevelAttribute = method.DeclaringType.GetCustomAttribute<VisibleAttribute>()
                                     ?? containingType.GetCustomAttribute<VisibleAttribute>();
            var hasTypeOverride = typeLevelAttribute != null && typeLevelAttribute.Visible.HasValue;
            var typeVisibility = typeLevelAttribute != null && typeLevelAttribute.Visible.HasValue
                                 && typeLevelAttribute.Visible.Value;

            var methodLevelAttribute = method.GetCustomAttribute<VisibleAttribute>();
            var hasMethodOverride = methodLevelAttribute != null && methodLevelAttribute.Visible.HasValue;
            var methodVisibility = methodLevelAttribute != null && methodLevelAttribute.Visible.HasValue
                                   && methodLevelAttribute.Visible.Value;

            if (hasMethodOverride)
            {
                return methodVisibility;
            }

            if (hasTypeOverride)
            {
                return typeVisibility;
            }

            return true;
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Creates one instance of the Relation Object from the PropertyInfo object of the reflected class
        /// </summary>
        /// <param name="propInfo"></param>
        /// <returns></returns>
        public static Structure CreateStructureObject(Type structureType)
        {
            Structure result = new VSPlugin.Structure();

            StructureAttribute structAttribute = structureType.GetCustomAttribute<StructureAttribute>();


            result.Type = structAttribute == null ? "object" : structAttribute.Type;
            result.Properties = new Dictionary<string, StructureProperty>();
            foreach(PropertyInfo pinfo in structureType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance))
            {
                PropertyAttribute propertyAttribute = pinfo.GetCustomAttribute<PropertyAttribute>();

                string itemsType = "";
                StructureProperty structure = new StructureProperty();
                structure.Required = propertyAttribute == null ? false : propertyAttribute.Required;
                Structure includedStructure;
                structure.Type = Utility.HandleProperty(pinfo, out itemsType, out includedStructure);
                if (!string.IsNullOrEmpty(itemsType))
                {
                    structure.Items = new ArraySchema()
                    {
                        Type = itemsType
                    };
                }
                result.Properties.Add(pinfo.Name, structure);                
            }

            return result;
        }
Ejemplo n.º 19
0
        public static CommandDefinition FromType(Type type)
        {
            var descAttr = type.GetCustomAttribute<DescriptionAttribute>();
            var match = NameParser.Match(type.FullName);

            string name;
            string group;
            if (!match.Success)
            {
                name = type.Name;
                group = null;
            }
            else
            {
                name = match.Groups["command"].Value.ToLowerInvariant();
                if (match.Groups["group"].Success)
                {
                    group = match.Groups["group"].Value.ToLowerInvariant();
                }
                else
                {
                    group = null;
                }
            }

            return new CommandDefinition(group, name, descAttr == null ? null : descAttr.Description, type);
        }
        private static bool IsMemberType(TypeInfo typeInfo)
        {
            if (typeInfo.IsGenericType)
            {
                var implementingType  = GetImplementingType(typeInfo);
                var genericDefinition = implementingType.GetGenericTypeDefinition();

                var arguments = implementingType.GetGenericArguments();
                return(genericDefinition == typeof(RdSignal <>) ||
                       genericDefinition == typeof(RdProperty <>) ||
                       genericDefinition == typeof(RdList <>) ||
                       genericDefinition == typeof(RdSet <>) ||
                       genericDefinition == typeof(RdMap <,>) ||
                       (genericDefinition == typeof(RdCall <,>) && IsScalar(arguments[0]) && IsScalar(arguments[1])) ||
                       // UProperty support
                       typeInfo.GetInterface("JetBrains.Collections.Viewable.IViewableProperty`1")?.GetGenericTypeDefinition() == typeof(IViewableProperty <>) ||
                       // USignal support
                       typeInfo.GetInterface("JetBrains.Collections.Viewable.ISignal`1")?.GetGenericTypeDefinition() == typeof(ISignal <>));
            }

            var hasRdExt = typeInfo.GetCustomAttribute <RdExtAttribute>() != null;

            if (hasRdExt)
            {
                return(true);
            }

            return(false);
        }
Ejemplo n.º 21
0
        public static void RegisterVisualizer(Type type)
        {
            var attribute = type.GetCustomAttribute<ResponseVisualizerAttribute>();
            if (attribute != null)
            {
                foreach (var contentType in attribute.ContentTypes)
                {
                    List<Type> list;
                    if (!visualizersByContentType.TryGetValue(contentType, out list))
                    {
                        list = new List<Type>();
                        visualizersByContentType[contentType] = list;
                    }
                    list.Add(type);
                }
            }

            var predicateMethod = type.GetMethods().Where(x => x.IsDefined(typeof(ResponseVisualizerPredicateAttribute))).SingleOrDefault();
            if (predicateMethod != null)
            {
                if (!predicateMethod.IsStatic)
                    throw new Exception("ResponseActionPredicate must be a static method");
                if (predicateMethod.ReturnType != typeof(bool))
                    throw new Exception("Return type of a ResponseActionPredicate must be bool");
                if (predicateMethod.GetParameters().Length != 1 || predicateMethod.GetParameters()[0].ParameterType != typeof(ApiResponseModel))
                    throw new Exception("ResponseActionPredicate must declare one parameter of type ApiResponseModel");
                RegisterVisualizer(type, x => (bool)predicateMethod.Invoke(null, new[] { x }));
            }
        }
        public static bool HasRdModelAttribute(TypeInfo type)
        {
            var modelAttribute = type.GetCustomAttribute <RdModelAttribute>();
            var isDataModel    = modelAttribute != null;

            return(isDataModel);
        }
Ejemplo n.º 23
0
        internal static ModelTypeData ReflectClass(System.Type type)
        {
            ModelTypeData modelTypeData = new ModelTypeData();

            System.Reflection.PropertyInfo[] properties             = type.GetProperties();
            DisplayColumnAttribute           displayColumnAttribute = type.GetCustomAttribute(typeof(DisplayColumnAttribute), true) as DisplayColumnAttribute;

            if (displayColumnAttribute != null)
            {
                string displayColumnPropertyName = displayColumnAttribute.DisplayColumn;
                modelTypeData.DisplayColumnProperty = properties.FirstOrDefault((System.Reflection.PropertyInfo x) => x.Name == displayColumnPropertyName);
            }
            System.Reflection.PropertyInfo[] array = properties;
            for (int i = 0; i < array.Length; i++)
            {
                System.Reflection.PropertyInfo propertyInfo = array[i];
                object obj = propertyInfo.GetCustomAttributes(typeof(IdAttribute), true).FirstOrDefault <object>();
                if (obj != null)
                {
                    modelTypeData.IdProperty = propertyInfo;
                    break;
                }
            }
            System.Reflection.PropertyInfo propertyInfo2 = properties.FirstOrDefault((System.Reflection.PropertyInfo x) => x.IsDefined(typeof(SuperordinateIdAttribute), true));
            if (propertyInfo2 != null)
            {
                modelTypeData.SuperordinateIdProperty = propertyInfo2;
            }
            return(modelTypeData);
        }
Ejemplo n.º 24
0
 /// <summary>
 /// Primary constructor.
 /// </summary>
 /// <param name="type">The flag-based enumeration type to describe.
 /// </param>
 public FlagsEnumArgumentType(Type type) : base(type)
 {
     if (type.GetCustomAttribute<FlagsAttribute>() == null)
     {
         throw new ArgumentOutOfRangeException(nameof(type));
     }
 }
Ejemplo n.º 25
0
 public DatabaseProviderInfo(Type type)
 {
     Description = type.GetDescription();
     RequiresConnectionStringBuilding =
         type.GetCustomAttribute<NoConnectionStringBuilderAttribute>() == null;
     TypeName = type.FullName;
 }
        protected override bool TryConvertClass(IReferenceMap referenceMap, object value, out object result)
        {
            if (value == null)
            {
                result = null;
                return(true);
            }

            System.Type type = value.GetType();

            if (type.GetCustomAttribute <JsiiTypeProxyAttribute>() != null)
            {
                throw new ArgumentException
                      (
                          "Interface proxies are one-way (jsii to framework). " +
                          "They may not be converted back to jsii. " +
                          "Instead, use a concrete type that implements the interface.",
                          nameof(value)
                      );
            }

            if (value is DeputyBase deputyValue)
            {
                result = deputyValue.Reference;
                return(true);
            }

            result = null;
            return(false);
        }
        public ModelDescription Generate(Type modelType, ModelDescriptionGenerator generator)
        {
            var enumDescription = new EnumTypeModelDescription
            {
                Name = ModelNameHelper.GetModelName(modelType),
                ModelType = modelType,
                Documentation = generator.CreateDefaultDocumentation(modelType)
            };
            var hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
            foreach (var field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
            {
                if (!ModelDescriptionGenerator.ShouldDisplayMember(field, hasDataContractAttribute)) continue;
                var enumValue = new EnumValueDescription
                {
                    Name = field.Name,
                    Value = field.GetRawConstantValue().ToString()
                };
                if (generator.DocumentationProvider != null)
                {
                    enumValue.Documentation = generator.DocumentationProvider.GetDocumentation(field);
                }
                enumDescription.Values.Add(enumValue);
            }
            generator.GeneratedModels.Add(enumDescription.Name, enumDescription);

            return enumDescription;
        }
Ejemplo n.º 28
0
        private static bool IsMemberType(TypeInfo typeInfo)
        {
            if (typeInfo.IsGenericType)
            {
                var implementingType  = GetImplementingType(typeInfo);
                var genericDefinition = implementingType.GetGenericTypeDefinition();

                var arguments = implementingType.GetGenericArguments();
                return(genericDefinition == typeof(RdSignal <>) ||
                       genericDefinition == typeof(RdProperty <>) ||
                       genericDefinition == typeof(RdList <>) ||
                       genericDefinition == typeof(RdSet <>) ||
                       genericDefinition == typeof(RdMap <,>) ||                 // TResponse can be LiveModel
                       (genericDefinition == typeof(RdCall <,>) && IsScalar(arguments[0]) /*&& IsScalar(arguments[1])*/) ||
                       // Custom classes support
                       (typeInfo.IsClass && typeInfo.IsSealed && typeof(IRdBindable).IsAssignableFrom(typeInfo)));
            }

            var hasRdExt = typeInfo.GetCustomAttribute <RdExtAttribute>() != null;

            if (hasRdExt)
            {
                return(true);
            }

            return(false);
        }
Ejemplo n.º 29
0
        // Modify this to provide custom model name mapping.
        public static string GetModelName(Type type)
        {
            var modelNameAttribute = type.GetCustomAttribute<ModelNameAttribute>();
            if (modelNameAttribute != null && !string.IsNullOrEmpty(modelNameAttribute.Name))
            {
                return modelNameAttribute.Name;
            }

            var modelName = type.Name;
            if (type.IsGenericType)
            {
                // Format the generic type name to something like: GenericOfAgurment1AndArgument2
                var genericType = type.GetGenericTypeDefinition();
                var genericArguments = type.GetGenericArguments();
                var genericTypeName = genericType.Name;

                // Trim the generic parameter counts from the name
                genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`'));
                var argumentTypeNames = genericArguments.Select(t => GetModelName(t)).ToArray();
                modelName = string.Format(CultureInfo.InvariantCulture, "{0}Of{1}", genericTypeName,
                    string.Join("And", argumentTypeNames));
            }

            return modelName;
        }
Ejemplo n.º 30
0
 public object Deserialize(string s, Type desiredType)
 {
     if (String.IsNullOrWhiteSpace(s)) return null;
     if (desiredType.IsGenericType && desiredType.GetGenericTypeDefinition() == typeof (Nullable<>))
         desiredType = desiredType.GenericTypeArguments[0];
     string[] subExpressions;
     long underlyingValue = 0;
     if (desiredType.GetCustomAttribute<FlagsAttribute>() != null)
     {
         //��λ��ϵ�ö�٣��� Xml ���Ա��հ׷ָ�ı��ʽ����
         subExpressions = s.Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
     }
     else
     {
         subExpressions = new[] { s };
     }
     //�� XSDExpressionAttribute ȷ��ֵ
     foreach (var eachExpression in subExpressions)
     {
         foreach (var eachField in desiredType.GetFields(BindingFlags.Public | BindingFlags.Static))
         {
             if (XEnumAttribute.GetXEnumName(eachField) == eachExpression)
             {
                 underlyingValue = underlyingValue | Convert.ToInt64(eachField.GetValue(null));
                 break;
             }
         }
     }
     return Enum.ToObject(desiredType, underlyingValue);
 }
Ejemplo n.º 31
0
        internal clsMyType(Type t)
        {
            // create mytype.

            this.TypeName = t.Name;
            this.FullName = t.FullName;

            // set wmi class name to use.
            var attribWmiClassName = t.GetCustomAttribute<WmiClassNameAttribute>();
            if (attribWmiClassName != null)
                this.WmiClassName = attribWmiClassName.WmiClassName;
            else
                this.WmiClassName = t.Name;

            // Compile createobject.
            //this.CreateObject = Reflection.CompileCreateObject(t);
            this.CreateObject = Reflection.Instance.TryGetCreateObject(t.FullName, t);

            var props = t.GetProperties(BindingFlags.Instance | BindingFlags.Public); // | BindingFlags.SetProperty

            foreach(var p in props)
            {
                var myprop = new clsMyProperty(p);

                WmiProperties.Add(myprop.WmiName, myprop);
            }
        }
    internal static TableInfo GetTableInfo( Type t )
    {
      TableInfo table;
      if ( _tableNameCache.TryGetValue( t, out table ) ) return table;

      table = new TableInfo();
      table.TableName = t.Name;
      table.SchemaName = "dbo";

      // check for an attribute specifying something different
      var tableAttribute = t.GetCustomAttribute<TableAttribute>( false );
      if ( tableAttribute != null )
      {
        table.TableName = tableAttribute.Name;
        if ( !string.IsNullOrWhiteSpace( tableAttribute.Schema ) ) table.SchemaName = tableAttribute.Schema;
      }

      // get the property names that can be mapped
      foreach ( var pi in t.GetProperties( System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public ).Where( m => m.CanRead && m.CanWrite && !m.HasCustomAttribute<NotMappedAttribute>( false ) ) )
        table.FieldNames.Add( GetFieldName( pi ) );

      // get the key property names
      foreach ( var pi in t.GetProperties( System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public ).Where( m => m.CanRead && m.CanWrite && m.HasCustomAttribute<System.ComponentModel.DataAnnotations.KeyAttribute>( false )  ) )
        table.PrimaryKeyFieldNames.Add( GetFieldName( pi ) );

      // try to add the newly aquired info
      if ( _tableNameCache.TryAdd( t, table ) ) return table;
      return _tableNameCache[ t ];
    }
        private CustomJsonSerializer(Type type, bool encrypt, JsonMappings mappings, bool shouldUseAttributeDefinedInInterface)
        {
            _mappings = mappings;
            _shouldUseAttributeDefinedInInterface = shouldUseAttributeDefinedInInterface;
            _type = type;

            if (_mappings.MappingsByType.ContainsKey(type))
            {
                _type = _mappings.MappingsByType[type];
            }
            else
            {
                var mappingAttribute = _type.GetCustomAttribute<JsonMappingAttribute>();
                if (mappingAttribute != null)
                {
                    _type = mappingAttribute.Type;
                }
            }

            _encrypt = encrypt || type.GetCustomAttribute<EncryptAttribute>() != null;

            var serializableProperties = GetSerializableProperties(_type);
            _deserializingPropertiesMap = serializableProperties.ToDictionary(p => p.Name);

            if (!_type.IsAbstract)
            {
                _serializingPropertiesMap[_type] = serializableProperties;
            }

            _createObjectFactory = new Lazy<Func<IObjectFactory>>(GetCreateObjectFactoryFunc);
        }
Ejemplo n.º 34
0
        public string Generate(Type resource)
        {
            Schema schema = new Schema();

            ResourceBaseAttribute resourceAttr = resource.GetCustomAttribute<ResourceBaseAttribute>();
            if (resourceAttr == null)
                return null;

            // Setting the schema master attributes
            schema.Name = resource.Name;
            schema.ApsVersion = resourceAttr.ApsVersion;
            schema.Implements = resourceAttr.Implements;
            schema.Id = resourceAttr.Id;

            List<PropertyInfo> properties = new List<PropertyInfo>();
            List<PropertyInfo> links = new List<PropertyInfo>();
            List<PropertyInfo> structures = new List<PropertyInfo>();

            
            schema.Properties = new Dictionary<string, Property>();
            foreach (PropertyInfo property in resource.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance))
            {
                if (property.GetCustomAttribute<SDK.Attributes.RelationAttribute>() != null)
                    schema.Relations.Add(property.Name, Relation.CreateRelationObject(property));
            }
            schema.Operations = new Dictionary<string, Operation>();
            foreach(MemberInfo method in resource.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance))
            {
                if (method.GetCustomAttribute<OperationAttribute>() != null)
                    schema.Operations.Add(method.Name, Operation.CreateOperationObject(method));
            }
            

            return JsonConvert.SerializeObject(schema, Formatting.Indented);
        }
Ejemplo n.º 35
0
        public static JobAttribute Get(Type jobType)
        {
            var attr = jobType.GetCustomAttribute<JobAttribute>();
            if (attr != null)
            {
                return attr;
            }
            else
            {
                // Infer an attribute
                string name;
                var match = NameExtractor.Match(jobType.Name);
                if (match.Success)
                {
                    name = match.Groups["shortname"].Value;
                }
                else
                {
                    name = jobType.Name;
                }

                Type jobBase = jobType.BaseType;
                while (jobBase != null && (!jobBase.IsGenericType || (jobBase.GetGenericTypeDefinition() != typeof(JobHandlerBase<>))))
                {
                    jobBase = jobBase.BaseType;
                }
                
                Type eventProvider = null;
                if (jobBase != null) {
                    eventProvider = jobBase.GetGenericArguments()[0];
                }
                return new JobAttribute(name, eventProvider);
            }
        }
        /// <summary>
        /// Initialises the Factory property based on the type to which the attribute is applied.
        /// </summary>
        /// <param name="decoratedType">The type to which the attribute is applied</param>
        public override void Initialise(Type decoratedType)
        {
            if (!decoratedType.IsEnum)
            {
                throw new CodeFirstException("EnumDataTypeAttribute can only be applied to an enum type. " + decoratedType.FullName + " is not an enum");
            }

            if (string.IsNullOrEmpty(Name))
            {
                Name = decoratedType.Name.ToProperCase();
            }

            if (string.IsNullOrEmpty(PropertyEditorAlias))
            {
                if (decoratedType.GetCustomAttribute<FlagsAttribute>() != null)
                {
                    PropertyEditorAlias = BuiltInPropertyEditorAliases.CheckBoxList;
                }
                else
                {
                    PropertyEditorAlias = BuiltInPropertyEditorAliases.DropDown;
                }
            }

            ConverterType = typeof(EnumDataTypeConverter<>).MakeGenericType(decoratedType);

            DbType = DataTypeDatabaseType.Ntext;

            Initialised = true;
        }
Ejemplo n.º 37
0
        protected override void GenerateCodeFor(Type type)
        {
            var codeNamespace = GetNamespace(type);

            Action<Action<Type>> run = action =>
            {
                cw.Indented("namespace ");
                sb.Append(codeNamespace);
                cw.InBrace(delegate
                {
                    action(type);
                });
            };

            if (type.GetIsEnum())
                run(GenerateEnum);
            else if (type.IsSubclassOf(typeof(Controller)))
                run(GenerateService);
            else
            { 
                var formScriptAttr = type.GetCustomAttribute<FormScriptAttribute>();
                if (formScriptAttr != null)
                {
                    run(t => GenerateForm(t, formScriptAttr));
                    EnqueueTypeMembers(type);

                    if (type.IsSubclassOf(typeof(ServiceRequest)))
                    {
                        AddFile(RemoveRootNamespace(codeNamespace, 
                            this.fileIdentifier + (IsTS() ? ".ts" : ".cs")));

                        this.fileIdentifier = type.Name;
                        run(GenerateBasicType);
                    }

                    return;
                }
                else if (type.GetCustomAttribute<ColumnsScriptAttribute>() != null)
                {
                    //GenerateColumns(type);
                    run(EnqueueTypeMembers);
                    return;
                }
                else
                    run(GenerateBasicType);
            }
        }
Ejemplo n.º 38
0
        internal static FieldInfo[] GetBindableMembers(TypeInfo typeInfo)
        {
/*
 *    var rpcInterface = GetRpcInterface();
 *    if (rpcInterface != null)
 *    {
 *      var rpcInterfaceMap = typeInfo.GetInterfaceMap(rpcInterface);
 *      //members = rpcInterfaceMap.TargetMethods;
 *    }
 */
            Type baseType;

            if (ReflectionSerializerVerifier.HasRdExtAttribute(typeInfo))
            {
                baseType = typeof(RdExtReflectionBindableBase);
            }
            else if (ReflectionSerializerVerifier.HasRdModelAttribute(typeInfo))
            {
                baseType = typeof(RdReflectionBindableBase);
            }
            else
            {
                baseType = typeof(RdBindableBase);
            }

            bool isRdExtImpl      = baseType == typeof(RdExtReflectionBindableBase) && !typeInfo.GetInterfaces().Contains(typeof(IProxyTypeMarker));
            bool isRdRpcInterface = typeInfo.IsInterface && typeInfo.GetCustomAttribute <RdRpcAttribute>() != null;

            var fields = GetFields(typeInfo, baseType);
            var list   = new List <FieldInfo>();

            foreach (var mi in fields)
            {
                if (typeof(RdExtReflectionBindableBase).IsAssignableFrom(mi.FieldType))
                {
                    continue;
                }

                if (
                    mi.MemberType == MemberTypes.Field &&
                    (mi.DeclaringType != null && !mi.DeclaringType.GetTypeInfo().IsAssignableFrom(baseType)) &&
                    mi.GetCustomAttribute <NonSerializedAttribute>() == null &&

                    // arbitrary data is allowed in RdExt implementations since they don't have to be serializable
                    !(isRdExtImpl && ReflectionSerializerVerifier.IsScalar(ReflectionSerializerVerifier.GetImplementingType(mi.FieldType.GetTypeInfo())))
                    )
                {
                    list.Add(mi);
                }
                else if (isRdRpcInterface)
                {
                    throw new Exception($"Invalid member in RdRpc interface: {typeInfo.ToString(true)}.{mi.Name}");
                }
            }

            return(list.ToArray());
        }
Ejemplo n.º 39
0
        private static T DynamicEnumPopup <T>(Rect rect, T inValue, System.Type enumType)
        {
            var enumCast = RuntimeCastToEnum(inValue, enumType);
            var output   =
                enumType.GetCustomAttribute <FlagsAttribute>() == null
                                        ? EditorGUI.EnumPopup(rect, GUIContent.none, enumCast)
                                        : EditorGUI.EnumFlagsField(rect, GUIContent.none, enumCast);

            return(RuntimeCastToUnderlyingType <T>(output));
        }
Ejemplo n.º 40
0
        public string TableName(System.Type table)
        {
            Object obj = table.GetCustomAttribute(typeof(Table));

            if (obj != null ? obj is Table : false)
            {
                return((obj as Table).Name);
            }

            return(null);
        }
Ejemplo n.º 41
0
        private VideoRecordingMode GetVideoRecordingModeType(System.Type currentType)
        {
            if (currentType == null)
            {
                throw new System.ArgumentNullException();
            }

            var recordingModeClassAttribute = currentType.GetCustomAttribute <VideoRecordingAttribute>(true);

            if (recordingModeClassAttribute != null)
            {
                return(recordingModeClassAttribute.VideoRecording);
            }

            return(VideoRecordingMode.Ignore);
        }
Ejemplo n.º 42
0
 public static Texture Get(System.Type type)
 {
     if (instance == null)
     {
         instance = new TypeIconCollector();
     }
     if (!instance.iconCache.TryGetValue(type, out var icon))
     {
         var typeIcon = type.GetCustomAttribute <TypeIconAttribute>();
         if (typeIcon != null && !string.IsNullOrEmpty(typeIcon.Name))
         {
             icon = EditorGUIUtility.Load(typeIcon.Name) as Texture;
         }
         instance.iconCache.Add(type, icon);
     }
     return(icon);
 }
Ejemplo n.º 43
0
        public static Type GetRpcInterface(TypeInfo typeInfo)
        {
            if (typeInfo.GetCustomAttribute <RdExtAttribute>() is RdExtAttribute rdExt && rdExt.RdRpcInterface != null)
            {
                return(rdExt.RdRpcInterface);
            }

            foreach (var @interface in typeInfo.GetInterfaces())
            {
                if (ReflectionSerializerVerifier.IsRpcAttributeDefined(@interface))
                {
                    return(@interface);
                }
            }

            return(null);
        }
Ejemplo n.º 44
0
        Type GetType <T>(string fullyQualifiedName) where T : JsiiTypeAttributeBase
        {
            Type type = null;

            lock (_lock)
            {
                Refresh();

                if (_types.ContainsKey(fullyQualifiedName))
                {
                    type = _types[fullyQualifiedName];
                }
            }

            return(type?.GetCustomAttribute <T>() == null ?
                   null :
                   type);
        }
Ejemplo n.º 45
0
        /// <summary>
        /// 指定された型に対するマッピング情報を生成します。
        /// </summary>
        /// <param name="type">対象となる型情報</param>
        /// <returns>テーブルマッピング情報</returns>
        public static This Create(System.Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            This result = null;

            lock (This.Cache)
            {
                //--- キャッシュから取得
                if (!This.Cache.TryGetValue(type, out result))
                {
                    //--- テーブル情報
                    var table = type.GetCustomAttribute <TableAttribute>(false);
                    result = new This()
                    {
                        Schema = table?.Schema ?? null,
                        Name   = table?.Name ?? type.Name,
                        Type   = type
                    };

                    //--- 列情報(モデル内に存在するコレクションは除外する
                    var flags     = BindingFlags.Instance | BindingFlags.Public;
                    var notMapped = typeof(NotMappedAttribute);

                    //typeMapに存在するカラムだけを対象にする
                    var targetProperties = type.GetProperties(flags)
                                           .Where(x => TypeMap.ContainsKey(x.PropertyType));

                    result.Columns = targetProperties
                                     .Where(x => x.CustomAttributes.All(y => y.AttributeType != notMapped))
                                     .Select(FieldMappingInfo.From)
                                     .ToArray();

                    //--- キャッシュ
                    This.Cache.TryAdd(type, result);
                }
            }
            return(result);
        }
Ejemplo n.º 46
0
        /// <summary>
        /// 获取实体影射的表名
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string GetMappingName(this System.Type type)
        {
            var key = $"batch{type.FullName}";

            var tableName = CacheService.Get(key);

            if (string.IsNullOrEmpty(tableName))
            {
                var tableAttr = type.GetCustomAttribute <TableAttribute>();
                if (tableAttr != null)
                {
                    tableName = tableAttr.Name;
                }
                else
                {
                    tableName = type.Name;
                }
                CacheService.Add(key, tableName);
            }
            return(tableName);
        }
Ejemplo n.º 47
0
        public static string GetItemCategoryName(System.Type itemType)
        {
            if (itemType == null)
            {
                return(string.Empty);
            }

            var attribute = itemType.GetCustomAttribute(typeof(MenuCategoryAttribute)) as MenuCategoryAttribute;

            if (attribute != null)
            {
                var s = attribute.category;
                if (!s.EndsWith("/"))
                {
                    s += "/";
                }
                return(s);
            }

            return(string.Empty);
        }
Ejemplo n.º 48
0
        private static bool IsMemberType(TypeInfo typeInfo)
        {
            if (typeInfo.IsGenericType)
            {
                var implementingType  = GetImplementingType(typeInfo);
                var genericDefinition = implementingType.GetGenericTypeDefinition();

                var arguments = implementingType.GetGenericArguments();
                return(genericDefinition == typeof(RdSignal <>) ||
                       genericDefinition == typeof(RdProperty <>) ||
                       genericDefinition == typeof(RdList <>) ||
                       genericDefinition == typeof(RdSet <>) ||
                       genericDefinition == typeof(RdMap <,>) ||
                       (genericDefinition == typeof(RdCall <,>) && IsScalar(arguments[0]) && IsScalar(arguments[1])) ||
                       IsFromRdProperty(typeInfo)); // hack to support UProperty in RdExt

                bool IsFromRdProperty(TypeInfo tInfo)
                {
                    var genericArguments = tInfo.GetGenericArguments();

                    if (genericArguments.Length != 1)
                    {
                        return(false);
                    }
                    var rdProperty = typeof(IViewableProperty <>).MakeGenericType(typeInfo.GetGenericArguments());

                    return(rdProperty.GetTypeInfo().IsAssignableFrom(implementingType));
                }
            }

            var hasRdExt = typeInfo.GetCustomAttribute <RdExtAttribute>() != null;

            if (hasRdExt)
            {
                return(true);
            }

            return(false);
        }
Ejemplo n.º 49
0
        public void AddItemConstructor(System.Type type)
        {
            ItemTypeAttribute customAttribute = type.GetCustomAttribute <ItemTypeAttribute>();

            if (customAttribute == null)
            {
                ItemManager.logger.Error <System.Type>("Item Constructor {0} has no attribute !", type);
            }
            else
            {
                if (this.m_itemCtorByTypes.ContainsKey(customAttribute.ItemType))
                {
                    ItemManager.logger.Error <ItemTypeEnum>("Item Constructor with Type {0} defined twice or more !", customAttribute.ItemType);
                }
                else
                {
                    this.m_itemCtorByTypes.Add(customAttribute.ItemType, type.GetConstructor(new System.Type[]
                    {
                        typeof(Character),
                        typeof(PlayerItemRecord)
                    }).CreateDelegate <ItemManager.PlayerItemConstructor>());
                }
            }
        }
Ejemplo n.º 50
0
        object IConvertible.ToType(System.Type conversionType, IFormatProvider?provider)
        {
            if (Proxies.ContainsKey(conversionType))
            {
                return(Proxies[conversionType]);
            }

            if (ToTypeCore(out var converted))
            {
                return(Proxies[conversionType] = converted !);
            }

            throw new InvalidCastException($"Unable to cast {this.GetType().FullName} into {conversionType.FullName}");

            bool ToTypeCore(out object?result)
            {
                if (conversionType.IsInstanceOfType(this))
                {
                    result = this;
                    return(true);
                }

                if (!conversionType.IsInterface || Reference.Interfaces.Length == 0)
                {
                    // We can only convert to interfaces that are declared on the Reference.
                    result = null;
                    return(false);
                }

                var interfaceAttribute = conversionType.GetCustomAttribute <JsiiInterfaceAttribute>();

                if (interfaceAttribute == null)
                {
                    // We can only convert to interfaces decorated with the JsiiInterfaceAttribute
                    result = null;
                    return(false);
                }

                var types = ServiceContainer.ServiceProvider.GetRequiredService <ITypeCache>();

                if (!TryFindSupportedInterface(interfaceAttribute.FullyQualifiedName, Reference.Interfaces, types, out var adequateFqn))
                {
                    // We can only convert to interfaces declared by this Reference
                    result = null;
                    return(false);
                }

                var proxyType       = types.GetProxyType(interfaceAttribute.FullyQualifiedName);
                var constructorInfo = proxyType.GetConstructor(
                    BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
                    null,
                    new[] { typeof(ByRefValue) },
                    null
                    );

                if (constructorInfo == null)
                {
                    throw new JsiiException($"Could not find constructor to instantiate {proxyType.FullName}");
                }

                result = constructorInfo.Invoke(new object[] { Reference.ForProxy() });
                return(true);

                bool TryFindSupportedInterface(string declaredFqn, string[] availableFqns, ITypeCache types, out string?foundFqn)
                {
                    var declaredType = types.GetInterfaceType(declaredFqn);

                    foreach (var candidate in availableFqns)
                    {
                        var candidateType = types.GetInterfaceType(candidate);
                        if (declaredType.IsAssignableFrom(candidateType))
                        {
                            foundFqn = candidate;
                            return(true);
                        }
                    }

                    foundFqn = null;
                    return(false);
                }
            }
        }
Ejemplo n.º 51
0
        private static (object?, InvalidOperationException?) TryConvertObject(string context, object?val, System.Type targetType)
        {
            var targetIsNullable = targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable <>);

            // Note: 'null's can enter the system as the representation of an 'unknown' value.
            // Before calling 'Convert' we will have already lifted the 'IsKnown' bit out, but we
            // will be passing null around as a value.
            if (val == null)
            {
                if (targetIsNullable)
                {
                    // A 'null' value coerces to a nullable null.
                    return(null, null);
                }

                if (targetType.IsValueType)
                {
                    return(Activator.CreateInstance(targetType), null);
                }

                // for all other types, can just return the null value right back out as a legal
                // reference type value.
                return(null, null);
            }

            // We're not null and we're converting to Nullable<T>, just convert our value to be a T.
            if (targetIsNullable)
            {
                return(TryConvertObject(context, val, targetType.GenericTypeArguments.Single()));
            }

            if (targetType == typeof(string))
            {
                return(TryEnsureType <string>(context, val));
            }

            if (targetType == typeof(bool))
            {
                return(TryEnsureType <bool>(context, val));
            }

            if (targetType == typeof(double))
            {
                return(TryEnsureType <double>(context, val));
            }

            if (targetType == typeof(int))
            {
                var(d, exception) = TryEnsureType <double>(context, val);
                if (exception != null)
                {
                    return(null, exception);
                }

                return((int)d, exception);
            }

            if (targetType == typeof(Asset))
            {
                return(TryEnsureType <Asset>(context, val));
            }

            if (targetType == typeof(Archive))
            {
                return(TryEnsureType <Archive>(context, val));
            }

            if (targetType == typeof(AssetOrArchive))
            {
                return(TryEnsureType <AssetOrArchive>(context, val));
            }

            if (targetType == typeof(JsonElement))
            {
                return(TryConvertJsonElement(context, val));
            }

            if (targetType.IsConstructedGenericType)
            {
                if (targetType.GetGenericTypeDefinition() == typeof(Union <,>))
                {
                    return(TryConvertOneOf(context, val, targetType));
                }

                if (targetType.GetGenericTypeDefinition() == typeof(ImmutableArray <>))
                {
                    return(TryConvertArray(context, val, targetType));
                }

                if (targetType.GetGenericTypeDefinition() == typeof(ImmutableDictionary <,>))
                {
                    return(TryConvertDictionary(context, val, targetType));
                }

                throw new InvalidOperationException(
                          $"Unexpected generic target type {targetType.FullName} when deserializing {context}");
            }

            if (targetType.GetCustomAttribute <Pulumi.OutputTypeAttribute>() == null)
            {
                return(null, new InvalidOperationException(
                           $"Unexpected target type {targetType.FullName} when deserializing {context}"));
            }

            var constructor = GetPropertyConstructor(targetType);

            if (constructor == null)
            {
                return(null, new InvalidOperationException(
                           $"Expected target type {targetType.FullName} to have [{nameof(Pulumi.OutputConstructorAttribute)}] constructor when deserializing {context}"));
            }

            var(dictionary, tempException) = TryEnsureType <ImmutableDictionary <string, object> >(context, val);
            if (tempException != null)
            {
                return(null, tempException);
            }

            var constructorParameters = constructor.GetParameters();
            var arguments             = new object?[constructorParameters.Length];

            for (int i = 0, n = constructorParameters.Length; i < n; i++)
            {
                var parameter = constructorParameters[i];

                // Note: TryGetValue may not find a value here.  That can happen for things like
                // unknown vals.  That's ok.  We'll pass that through to 'Convert' and will get the
                // default value needed for the parameter type.
                dictionary !.TryGetValue(parameter.Name !, out var argValue);
                var(temp, tempException1) = TryConvertObject($"{targetType.FullName}({parameter.Name})", argValue, parameter.ParameterType);
                if (tempException1 != null)
                {
                    return(null, tempException1);
                }

                arguments[i] = temp;
            }

            return(constructor.Invoke(arguments), null);
        }
Ejemplo n.º 52
0
        private bool MakeProxy(Type interfaceType, bool force, [NotNullWhen(true)] out object?result)
        {
            if (!interfaceType.IsInterface)
            {
                result = null;
                return(false);
            }

            var interfaceAttribute = interfaceType.GetCustomAttribute <JsiiInterfaceAttribute>();

            if (interfaceAttribute == null)
            {
                // We can only convert to interfaces decorated with the JsiiInterfaceAttribute
                result = null;
                return(false);
            }

            var types = ServiceContainer.ServiceProvider.GetRequiredService <ITypeCache>();

            if (!TryFindSupportedInterface(interfaceAttribute.FullyQualifiedName, Reference.Interfaces, types, out var adequateFqn))
            {
                // We can only convert to interfaces declared by this Reference
                result = null;
                return(false);
            }

            var proxyType       = types.GetProxyType(interfaceAttribute.FullyQualifiedName);
            var constructorInfo = proxyType.GetConstructor(
                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
                null,
                new[] { typeof(ByRefValue) },
                null
                );

            if (constructorInfo == null)
            {
                throw new JsiiException($"Could not find constructor to instantiate {proxyType.FullName}");
            }

            result = constructorInfo.Invoke(new object[] { Reference.ForProxy() });
            return(true);

            bool TryFindSupportedInterface(string declaredFqn, string[] availableFqns, ITypeCache types, out string?foundFqn)
            {
                var declaredType = types.GetInterfaceType(declaredFqn);

                foreach (var candidate in availableFqns)
                {
                    var candidateType = types.GetInterfaceType(candidate);
                    if (!declaredType.IsAssignableFrom(candidateType))
                    {
                        continue;
                    }
                    foundFqn = candidate;
                    return(true);
                }

                foundFqn = declaredFqn;
                return(force);
            }
        }
        internal static String GetClassName(TypeInfo type)
        {
            var attribute = type.GetCustomAttribute <ParseClassNameAttribute>();

            return(attribute != null ? attribute.ClassName : null);
        }
Ejemplo n.º 54
0
        private static IType GetBySystemType(System.Type typeClass, IDictionary <string, string> parameters, int?length)
        {
            if (typeof(IType).IsAssignableFrom(typeClass))
            {
                try
                {
                    var type = (IType)Environment.ObjectsFactory.CreateInstance(typeClass);
                    InjectParameters(type, parameters);

                    var obsolete = typeClass.GetCustomAttribute <ObsoleteAttribute>(false);
                    if (obsolete != null)
                    {
                        _log.Warn("{0} ({1}) is obsolete. {2}", typeClass.FullName, type.Name, obsolete.Message);
                    }

                    return(type);
                }
                catch (HibernateException)
                {
                    throw;
                }
                catch (Exception e)
                {
                    throw new MappingException("Could not instantiate IType " + typeClass.Name + ": " + e, e);
                }
            }

            if (typeof(ICompositeUserType).IsAssignableFrom(typeClass))
            {
                return(new CompositeCustomType(typeClass, parameters));
            }

            if (typeof(IUserType).IsAssignableFrom(typeClass))
            {
                return(new CustomType(typeClass, parameters));
            }

            if (typeof(ILifecycle).IsAssignableFrom(typeClass))
            {
                return(NHibernateUtil.Entity(typeClass));
            }

            var unwrapped = typeClass.UnwrapIfNullable();

            if (unwrapped.IsEnum)
            {
                return((IType)Activator.CreateInstance(typeof(EnumType <>).MakeGenericType(unwrapped)));
            }

            if (!typeClass.IsSerializable)
            {
                return(null);
            }

            if (length.HasValue)
            {
                return(GetSerializableType(typeClass, length.Value));
            }

            return(GetSerializableType(typeClass));
        }
Ejemplo n.º 55
0
        public Type Resolve(System.Type type)
        {
            if (type == null)
            {
                return(null);
            }

            if (type.IsByRef)
            {
                return(Resolve(type.GetElementType()));
            }
            if (type.IsArray)
            {
                return(Resolve(type.GetElementType()));
            }

            Type ret;

            if (_typeMap.TryGetValue(type, out ret))
            {
                return(ret);
            }

            ret = BasicTypes.Of(type);
            if (ret != null)
            {
                _typeMap[type] = ret;
                return(ret);
            }

            switch (ConstructOf(type))
            {
            case Construct.Void:
                ret = new Void();
                break;

            case Construct.Primitive:
                ret = new Primitive();
                break;

            case Construct.Enum:
                ret = new Enum();
                break;

            case Construct.String:
                ret = new String();
                break;

            case Construct.Delegate:
                ret = new Delegate();
                break;

            case Construct.Task:
                ret = new Task();
                break;

            case Construct.Struct:
                ret = new Struct();
                break;

            case Construct.Object:
                ret = new Object();
                break;

            default:
                Debug.Assert(false);
                return(null);
            }

            _typeMap[type] = ret;
            Product.AllTypes.Add(ret);
            ret.Name        = type.Name;
            ret.Namespace   = Resolve(type.Namespace);
            ret.Assembly    = Resolve(type.Assembly);
            ret.XmlDoc      = XmlDocReader.XMLFromType(type);
            ret.IsAttribute = typeof(System.Attribute).IsAssignableFrom(type);

            var nativeAttr = type.GetCustomAttribute <NativeAttribute>();


            if (ret.IsDelegate && ((AST.Delegate)ret).IsGeneric || ret.IsTask)
            {
                ret.Origin = TypeOrigin.Mapped;
            }
            else if (!ret.Assembly.IsGluonDefinition)
            {
                if (ret.ConstructType == Construct.Object)
                {
                    ret.IsPureReference = true;
                }

                ret.Origin = TypeOrigin.Managed;
            }
            else if (nativeAttr == null)
            {
                ret.Origin = TypeOrigin.Gluon;
            }
            else
            {
                if (ret.ConstructType == Construct.Object)
                {
                    ret.IsPureReference = true;
                }

                ret.Origin = TypeOrigin.Native;

                ret.CppHeader = nativeAttr.Header;
                ret.CppLib    = nativeAttr.StaticLibrary;
            }

            foreach (var attr in type.GetCustomAttributesData())
            {
                ret.Attributes.Add(Resolve(attr));
            }

            int isPublic    = (type.GetCustomAttribute <PublicAttribute>() != null ? 1 : 0);
            int isProtected = (type.GetCustomAttribute <ProtectedAttribute>() != null ? 1 : 0);
            int isInternal  = (type.GetCustomAttribute <InternalAttribute>() != null ? 1 : 0);
            int isPrivate   = (type.GetCustomAttribute <PrivateAttribute>() != null ? 1 : 0);

            ret.Access = Access.Public;

            if (isPublic + isProtected + isInternal + isPrivate > 1)
            {
                Errors.Generic(type.FullName + " has multiple, conflicting access attributes");
            }
            else if (isPublic == 1)
            {
                ret.Access = Access.Public;
            }
            else if (isProtected == 1)
            {
                ret.Access = Access.Protected;
            }
            else if (isInternal == 1)
            {
                ret.Access = Access.Internal;
            }
            else if (isPrivate == 1)
            {
                ret.Access = Access.Private;
            }

            if (!ret.IsPureReference)
            {
                Merge(ret, type);
            }

            return(ret);
        }
Ejemplo n.º 56
0
        TypeReference InferType(IReferenceMap referenceMap, Type type)
        {
            type = type ?? throw new ArgumentNullException(nameof(type));

            var classAttribute = ReflectionUtils.GetClassAttribute(type);

            if (classAttribute != null)
            {
                return(new TypeReference(classAttribute.FullyQualifiedName));
            }

            var enumAttribute = type.GetCustomAttribute <JsiiEnumAttribute>();

            if (enumAttribute != null)
            {
                return(new TypeReference(enumAttribute.FullyQualifiedName));
            }

            var interfaceAttribute = type.GetCustomAttribute <JsiiInterfaceAttribute>();

            if (interfaceAttribute != null)
            {
                return(new TypeReference(interfaceAttribute.FullyQualifiedName));
            }

            var structAttribute = type.GetCustomAttribute <JsiiByValueAttribute>();

            if (structAttribute != null)
            {
                return(new TypeReference(structAttribute.FullyQualifiedName));
            }

            if (typeof(string).IsAssignableFrom(type))
            {
                return(new TypeReference(primitive: PrimitiveType.String));
            }

            if (typeof(bool).IsAssignableFrom(type))
            {
                return(new TypeReference(primitive: PrimitiveType.Boolean));
            }

            if (IsNumeric(type))
            {
                return(new TypeReference(primitive: PrimitiveType.Number));
            }

            if (typeof(DateTime).IsAssignableFrom(type))
            {
                return(new TypeReference(primitive: PrimitiveType.Date));
            }

            if (typeof(JObject).IsAssignableFrom(type) || typeof(JArray).IsAssignableFrom(type))
            {
                return(new TypeReference(primitive: PrimitiveType.Json));
            }

            if (type.IsArray)
            {
                return(new TypeReference
                       (
                           collection: new CollectionTypeReference
                           (
                               kind: CollectionKind.Array,
                               elementType: typeof(Object) == type.GetElementType()
                            ? new TypeReference(primitive: PrimitiveType.Any)
                            : InferType(referenceMap, type.GetElementType() !)
                           )
                       ));
            }

            Type dictionaryInterface = type.GetInterfaces()
                                       .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDictionary <,>));

            if (dictionaryInterface != null)
            {
                if (!typeof(string).IsAssignableFrom(dictionaryInterface.GetGenericArguments()[0]))
                {
                    throw new ArgumentException("All dictionaries must have string keys", nameof(type));
                }

                Type elementType = dictionaryInterface.GetGenericArguments()[1];
                return(new TypeReference
                       (
                           collection: new CollectionTypeReference
                           (
                               kind: CollectionKind.Map,
                               elementType: typeof(Object) == elementType
                            ? new TypeReference(primitive: PrimitiveType.Any)
                            : InferType(referenceMap, elementType)
                           )
                       ));
            }

            throw new ArgumentException($"Could not infer JSII type for .NET type '{type.Name}'", nameof(type));
        }
        public static bool HasIntrinsicAttribute(TypeInfo t)
        {
            var rdScalar = t.GetCustomAttribute <RdScalarAttribute>();

            return(rdScalar != null && rdScalar.Marshaller != null);
        }
Ejemplo n.º 58
0
        public object ToType(System.Type conversionType, IFormatProvider provider)
        {
            if (Proxies.ContainsKey(conversionType))
            {
                return(Proxies[conversionType]);
            }

            if (ToTypeCore(out var converted))
            {
                Proxies[conversionType] = converted;
                return(converted);
            }

            throw new InvalidCastException($"Unable to cast {this.GetType().FullName} into {conversionType.FullName}");

            bool ToTypeCore(out object result)
            {
                if (conversionType.IsInstanceOfType(this))
                {
                    result = this;
                    return(true);
                }

                if (!conversionType.IsInterface || Reference.Interfaces.Length == 0)
                {
                    // We can only convert to interfaces that are declared on the Reference.
                    result = null;
                    return(false);
                }

                var interfaceAttribute = conversionType.GetCustomAttribute <JsiiInterfaceAttribute>();

                if (interfaceAttribute == null)
                {
                    // We can only convert to interfaces decorated with the JsiiInterfaceAttribute
                    result = null;
                    return(false);
                }

                if (!Reference.Interfaces.Contains(interfaceAttribute.FullyQualifiedName))
                {
                    // We can only convert to interfaces declared by this Reference
                    result = null;
                    return(false);
                }

                var types           = ServiceContainer.ServiceProvider.GetRequiredService <ITypeCache>();
                var proxyType       = types.GetProxyType(interfaceAttribute.FullyQualifiedName);
                var constructorInfo = proxyType.GetConstructor(
                    BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
                    null,
                    new[] { typeof(ByRefValue) },
                    null
                    );

                if (constructorInfo == null)
                {
                    throw new JsiiException($"Could not find constructor to instantiate {proxyType.FullName}");
                }

                result = constructorInfo.Invoke(new object[] { Reference.ForProxy() });
                return(true);
            }
        }
Ejemplo n.º 59
0
        public static SerializerPair TryGetIntrinsicSerializer(TypeInfo typeInfo, Func <Type, SerializerPair> getInstanceSerializer)
        {
            if (ReflectionSerializerVerifier.HasIntrinsicNonProtocolMethods(typeInfo))
            {
                var genericArguments = typeInfo.GetGenericArguments();

                /*
                 * if (genericArguments.Length == 1)
                 * {
                 * var argument = genericArguments[0];
                 * var staticRead = SerializerReflectionUtil.GetReadStaticSerializer(typeInfo, argument);
                 * var staticWrite = SerializerReflectionUtil.GetWriteStaticDeserializer(typeInfo);
                 * return SerializerPair.CreateFromMethods(staticRead, staticWrite, getInstanceSerializer(argument));
                 * }
                 */
                if (genericArguments.Length == 0)
                {
                    var staticRead     = SerializerReflectionUtil.GetReadStaticNonProtocolSerializer(typeInfo);
                    var instanceWriter = SerializerReflectionUtil.GetWriteNonProtocolDeserializer(typeInfo);
                    return(SerializerPair.CreateFromNonProtocolMethods(staticRead, instanceWriter));
                }

                return(null);
            }

            if (ReflectionSerializerVerifier.HasIntrinsicProtocolMethods(typeInfo))
            {
                var genericArguments = typeInfo.GetGenericArguments();
                if (genericArguments.Length == 1)
                {
                    var argument    = genericArguments[0];
                    var staticRead  = SerializerReflectionUtil.GetReadStaticSerializer(typeInfo, argument);
                    var staticWrite = SerializerReflectionUtil.GetWriteStaticDeserializer(typeInfo);
                    return(SerializerPair.CreateFromMethods(staticRead, staticWrite, getInstanceSerializer(argument)));
                }

                if (genericArguments.Length == 0)
                {
                    var staticRead  = SerializerReflectionUtil.GetReadStaticSerializer(typeInfo);
                    var staticWrite = SerializerReflectionUtil.GetWriteStaticDeserializer(typeInfo);
                    return(SerializerPair.CreateFromMethods(staticRead, staticWrite));
                }

                return(null);
            }
            else if (ReflectionSerializerVerifier.HasIntrinsicFields(typeInfo))
            {
                var readField  = typeInfo.GetField("Read", BindingFlags.Public | BindingFlags.Static);
                var writeField = typeInfo.GetField("Write", BindingFlags.Public | BindingFlags.Static);
                if (readField == null)
                {
                    Assertion.Fail($"Invalid intrinsic serializer for type {typeInfo}. Static field 'Read' with type {typeof(CtxReadDelegate<>).ToString(true)} not found");
                }
                if (writeField == null)
                {
                    Assertion.Fail($"Invalid intrinsic serializer for type {typeInfo}. Static field 'Write' with type {typeof(CtxWriteDelegate<>).ToString(true)} not found");
                }
                var reader = readField.GetValue(null);
                var writer = writeField.GetValue(null);
                return(new SerializerPair(reader, writer));
            }
            else if (ReflectionSerializerVerifier.HasIntrinsicAttribute(typeInfo))
            {
                var marshallerType = typeInfo.GetCustomAttribute <RdScalarAttribute>().NotNull().Marshaller;
                var marshaller     = Activator.CreateInstance(marshallerType);
                return((SerializerPair)ReflectionUtil.InvokeStaticGeneric(typeof(SerializerPair), nameof(SerializerPair.FromMarshaller), typeInfo, marshaller));
            }

            return(null);
        }
Ejemplo n.º 60
0
        public void Merge(Object ast, System.Type type)
        {
            ast.IsAbstract = type.GetCustomAttribute <AbstractAttribute>() != null;
            ast.IsAlreadyGluonGenerated = typeof(GluonObject).IsAssignableFrom(type);

            var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).ToList();

            foreach (var m in type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
            {
                if (m.Name == "Create" && m.ReturnType == type)
                {
                    ast.Constructors.Add(ResolveAsConstructor(m));
                    methods.Remove(m);
                }
            }

            foreach (var p in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
            {
                ast.Properties.Add(Resolve(p));
                if (p.GetMethod != null)
                {
                    methods.Remove(p.GetMethod);
                }
                if (p.SetMethod != null)
                {
                    methods.Remove(p.SetMethod);
                }
            }

            foreach (var e in type.GetEvents(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
            {
                ast.Events.Add(Resolve(e));
                if (e.AddMethod != null)
                {
                    methods.Remove(e.AddMethod);
                }
                if (e.RemoveMethod != null)
                {
                    methods.Remove(e.RemoveMethod);
                }
            }

            Dictionary <string, int> overloads = new Dictionary <string, int>();

            foreach (var m in methods)
            {
                var methodNode = Resolve(m);

                int ordinal = 0;
                overloads.TryGetValue(m.Name, out ordinal);
                overloads[m.Name]          = ordinal + 1;
                methodNode.OverloadOrdinal = ordinal;
                ast.Methods.Add(methodNode);
            }


            var impl = type.GetInterfaces().Reverse().ToList();
            HashSet <System.Type> indirect = new HashSet <System.Type>();

            foreach (var iface in impl)
            {
                foreach (var indirectiface in iface.GetInterfaces())
                {
                    if (!indirect.Contains(indirectiface))
                    {
                        indirect.Add(indirectiface);
                    }
                }
            }

            foreach (var sub in indirect)
            {
                impl.Remove(sub);
            }

            if (impl != null && impl.Count != 0)
            {
                ast.BaseType = (Object)Resolve(impl[0]);

                if (ast.BaseType != null && ast.BaseType.IsPureReference)
                {
                    ast.BaseType = null;
                }

                if (ast.BaseType != null)
                {
                    for (int i = 1; i < impl.Count; i++)
                    {
                        ast.Interfaces.Add((Object)Resolve(impl[i]));
                    }
                }
                else
                {
                    for (int i = 0; i < impl.Count; i++)
                    {
                        ast.Interfaces.Add((Object)Resolve(impl[i]));
                    }
                }

                // TODO Can this error ever happen this way?

                //for (int i = 0; i < ast.Interfaces.Count; i++)
                //{
                //    if (ast.Interfaces[i] == null)
                //        Errors.IncompatibleType(impl[i + (ast.BaseType == null ? 0 : 1)]);
                //}
            }
        }