public void Define()
        {
            if (!typeInfo.IsInterface || !typeInfo.IsPublic)
            {
                throw new ArgumentException($"{typeInfo.FullName} must be a public interface");
            }

            if (typeInfo.IsGenericType)
            {
                throw new NotSupportedException($"Generic interfaces are not supported: {typeInfo.FullName}");
            }

            var className   = typeInfo.FullName.Replace(".", string.Empty);
            var serviceName = typeInfo.GetCustomAttribute <FauxClientAttribute>().Name;
            var baseRoute   = typeInfo.GetCustomAttribute <RouteAttribute>().BaseRoute;

            var classBuilder = new StringBuilder();

            classBuilder.AppendLine($"namespace {RootNamespace}");
            classBuilder.AppendLine("{");
            classBuilder.AppendLine("    // Generated by DHaven.Faux");
            classBuilder.AppendLine($"    public class {className} : DHaven.Faux.Compiler.DiscoveryAwareBase, {typeInfo.FullName}");
            classBuilder.AppendLine("    {");
            classBuilder.AppendLine($"        public {className}()");
            classBuilder.AppendLine($"            : base(\"{serviceName}\", \"{baseRoute}\") {{ }}");

            foreach (var method in typeInfo.GetMethods())
            {
                BuildMethod(classBuilder, method);
            }

            classBuilder.AppendLine("    }");
            classBuilder.AppendLine("}");

            var sourceCode = classBuilder.ToString();

            if (OutputSourceFiles)
            {
                var fullPath = Path.Combine(SourceFilePath, className + ".cs");
                try
                {
                    File.WriteAllText(fullPath, sourceCode, Encoding.UTF8);
                }
                catch (Exception ex)
                {
                    DiscoverySupport.Logger.LogWarning(ex, "Could not write the source code for {0}", fullPath);
                }
            }

            syntaxTrees.Add(SyntaxFactory.ParseSyntaxTree(sourceCode));
        }
Example #2
0
        /// <summary>
        /// Registers a new type to be compiled.
        /// </summary>
        /// <param name="type">the type to register</param>
        public void RegisterInterface(TypeInfo type)
        {
            logger.LogDebug($"Registering the interface: {type.FullName}");

            var fullyQualifiedClassName = fauxDiscovery.GetImplementationNameFor(type);

            if (fullyQualifiedClassName != null)
            {
                // already registered
                return;
            }

            var binding        = type.GetCustomAttribute <HystrixFauxClientAttribute>() == null ? BindingType.Core : BindingType.Hystrix;
            var sourceCodeList = serviceClassGenerators[binding].GenerateSource(type, out fullyQualifiedClassName);

            fauxDiscovery.RegisterType(type, fullyQualifiedClassName);

            foreach (var sourceCode in sourceCodeList)
            {
#if NETSTANDARD
                syntaxTrees.Add(SyntaxFactory.ParseSyntaxTree(sourceCode));
#else
                codeSources.Add(sourceCode);
#endif
            }

            logger.LogDebug($"Finished compiling the syntax tree for {fullyQualifiedClassName} generated from {type.FullName}");
        }
        public static string GetComponentFullName(TypeInfo componentType)
        {
            if (componentType == null)
            {
                throw new ArgumentNullException(nameof(componentType));
            }

            var attribute = componentType.GetCustomAttribute<ViewComponentAttribute>();
            if (!string.IsNullOrEmpty(attribute?.Name))
            {
                return attribute.Name;
            }

            // If the view component didn't define a name explicitly then use the namespace + the
            // 'short name'.
            var shortName = GetShortNameByConvention(componentType);
            if (string.IsNullOrEmpty(componentType.Namespace))
            {
                return shortName;
            }
            else
            {
                return componentType.Namespace + "." + shortName;
            }
        }
 public static bool IsAnonymous(this System.Reflection.TypeInfo type)
 {
     return(type.GetCustomAttribute <CompilerGeneratedAttribute>() != null &&
            type.IsGenericType && type.Name.Contains("AnonymousType") &&
            (type.Name.StartsWith("<>") || type.Name.StartsWith("VB$")) &&
            (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic);
 }
Example #5
0
        public static bool HasJsonUseTypeHintAttribute(TP tp)
        {
#if WINDOWS_STORE
            return(tp.GetCustomAttribute <JsonUseTypeHintAttribute> (true) != null);
#else
            return(tp.GetCustomAttributes(typeof(JsonUseTypeHintAttribute), true).Length != 0);
#endif
        }
        private HarshContentTypeId Build(TypeInfo t)
        {
            if (t.AsType() == typeof(HarshEntity))
            {
                // don't recurse up to Object. we should never get 
                // here anyway, since entities are supposed to inherit from
                // something with an absolute ID specified,
                // not directly from the HarshEntity class. 
                return null;
            }

            var cta = t.GetCustomAttribute<ContentTypeAttribute>(inherit: false);

            if (cta == null)
            {
                if (t == _entityTypeInfo)
                {
                    throw Logger.Fatal.InvalidOperationFormat(
                        SR.ContentTypeIdBuilder_NoContentTypeAttribute,
                        t.FullName
                    );
                }
                else
                {
                    throw Logger.Fatal.InvalidOperationFormat(
                        SR.ContentTypeIdBuilder_NoContentTypeAttributeBaseClass,
                        t.FullName,
                        _entityTypeInfo.FullName
                    );
                }
            }

            var ctid = HarshContentTypeId.Parse(cta.ContentTypeId);

            if (ctid.IsAbsolute)
            {
                // an absolute ID. do not recurse further up the
                // class hierarchy, take it as it is
                return ctid;
            }
            else
            {
                // not an absolute ID, append the parent type ID first
                var result = Build(t.BaseType.GetTypeInfo());

                if (result == null)
                {
                    throw Logger.Fatal.InvalidOperationFormat(
                        SR.ContentTypeIdBuilder_NoAbsoluteIDInHierarchy,
                        _entityTypeInfo.FullName
                    );
                }

                return result.Append(ctid);
            }
        }
Example #7
0
        public void AllPublicConcreteTypesShouldBeAnnotatedWithDebuggerDisplay(TypeInfo type)
        {
            var attribute = type.GetCustomAttribute<DebuggerDisplayAttribute>(false);

            Assert.Equal("{DebuggerDisplay, nq}", attribute.Value);

            var debuggerDisplay = type.GetDeclaredProperty("DebuggerDisplay");

            Assert.False(debuggerDisplay.GetAccessors().Any(x => x.IsPublic));
        }
Example #8
0
        public TestClassInfo(TypeInfo info) {
 
            if (!info.IsPublic || !info.IsClass) return;
            var attr = info.GetCustomAttribute(typeof(TestAttribute)) as TestAttribute;
            if (attr != null) {
                this.IsValid = true;
                this.TestClassType = info;
                this.Description = attr.Description;
            }
            
        }
Example #9
0
 private static bool IsAnonymousType(Type t, TypeInfo ti)
 {
     // This is not a perfect way to detect anonymous classes since they are a compiler feature and not a CLR feature.
     // It is probably good enough though.
     // See also Jon Skeets exhaustive answer on anonymous classes: http://stackoverflow.com/a/315186/271746
     return
         t.Namespace == null &&
         ti.IsPublic == false &&
         t.IsNested == false &&
         ti.IsGenericType &&
         ti.IsSealed &&
         ti.GetCustomAttribute<CompilerGeneratedAttribute>() != null;
 }
 private static TestGroup CreateGroup(TypeInfo type)
 {
     TestGroup group = new TestGroup();
     group.Name = type.Name;
     group.Tags.Add(type.Name);
     group.Tags.Add(type.FullName);
     if (type.GetCustomAttribute<FunctionalTestAttribute>(true) != null)
     {
         group.Tags.Add("Functional");
     }
     foreach (TagAttribute attr in type.GetCustomAttributes<TagAttribute>(true))
     {
         group.Tags.Add(attr.Tag);
     }
     return group;
 }
Example #11
0
        public void ProcessType(IContainerConfiguration container, TypeInfo type)
        {
            var settingsAttribute = type.GetCustomAttribute<SettingsAttribute>();
            if (settingsAttribute != null)
            {
                var settingsType = type.AsType();
                var settingsScope = settingsAttribute.Scope;
                var activatorConfiguration = new SettingsActivatorConfiguration(settingsScope, settingsType);

                container.Register(activatorConfiguration);
            }

            foreach (var serviceType in type.ImplementedInterfaces)
            {
                ProcessServiceType(container, type, serviceType);
            }
        }
        /// <summary>
        /// Gets the widget full name for the given widget type.
        /// </summary>
        /// <param name="widgetType">The widget type.</param>
        /// <returns>The widget full name.</returns>
        public static string GetWidgetFullName(TypeInfo widgetType)
        {
            if (widgetType == null)
            {
                throw new ArgumentNullException(nameof(widgetType));
            }

            var attr = widgetType.GetCustomAttribute<WidgetAttribute>();
            if (attr != null && !string.IsNullOrEmpty(attr.Name))
            {
                return attr.Name;
            }

            var shortName = GetShortNameByConvention(widgetType);
            if (string.IsNullOrEmpty(widgetType.Namespace))
            {
                return shortName;
            }

            return $"{widgetType.Namespace}.{shortName}";
        }
        /// <summary>
        /// Gets the widget name for the given widget type.
        /// </summary>
        /// <param name="widgetType">The widget type.</param>
        /// <returns>The widget name.</returns>
        public static string GetWidgetName(TypeInfo widgetType)
        {
            if (widgetType == null)
            {
                throw new ArgumentNullException(nameof(widgetType));
            }

            var attr = widgetType.GetCustomAttribute<WidgetAttribute>();
            if (attr != null && !string.IsNullOrEmpty(attr.Name))
            {
                var idx = attr.Name.LastIndexOf('.');
                if (idx >= 0)
                {
                    return attr.Name.Substring(idx + 1);
                }

                return attr.Name;
            }

            return GetShortNameByConvention(widgetType);
        }
        public static string GetComponentName(TypeInfo componentType)
        {
            if (componentType == null)
            {
                throw new ArgumentNullException(nameof(componentType));
            }

            var attribute = componentType.GetCustomAttribute<ViewComponentAttribute>();
            if (attribute != null && !string.IsNullOrEmpty(attribute.Name))
            {
                var separatorIndex = attribute.Name.LastIndexOf('.');
                if (separatorIndex >= 0)
                {
                    return attribute.Name.Substring(separatorIndex + 1);
                }
                else
                {
                    return attribute.Name;
                }
            }

            return GetShortNameByConvention(componentType);
        }
 internal static String GetClassName(TypeInfo type)
 {
     var attribute = type.GetCustomAttribute<AVClassNameAttribute>();
       return attribute != null ? attribute.ClassName : null;
 }
        public static bool IsComponent(TypeInfo typeInfo)
        {
            if (typeInfo == null)
            {
                throw new ArgumentNullException(nameof(typeInfo));
            }

            if (!typeInfo.IsClass ||
                !typeInfo.IsPublic ||
                typeInfo.IsAbstract ||
                typeInfo.ContainsGenericParameters)
            {
                return false;
            }

            return
                typeInfo.Name.EndsWith(ViewComponentSuffix, StringComparison.OrdinalIgnoreCase) ||
                typeInfo.GetCustomAttribute<ViewComponentAttribute>() != null;
        }
        /// <summary>
        /// Determines if the given type represents a widget.
        /// </summary>
        /// <param name="typeInfo">The candidate type.</param>
        /// <returns>True if the candidate type represents a widget, otherwise false.</returns>
        public static bool IsWidget(TypeInfo typeInfo)
        {
            if (!typeInfo.IsClass
                || !typeInfo.IsPublic
                || typeInfo.IsAbstract
                || typeInfo.ContainsGenericParameters)
            {
                return false;
            }

            return typeInfo.Name.EndsWith(WidgetSuffix, StringComparison.OrdinalIgnoreCase)
                || typeInfo.GetCustomAttribute<WidgetAttribute>() != null;
        }
Example #18
0
 public static bool ExpandGroup(TypeInfo typeInfo)
 {
     ExpandGroupAttribute attr = typeInfo.GetCustomAttribute<ExpandGroupAttribute>();
     if(attr != null)
         return attr.Expand;
     else
         return true;
 }
Example #19
0
 private void EntitySystemOnComponentTypeAdded(object sender, TypeInfo type)
 {
     var rendererTypeAttribute = type.GetCustomAttribute<DefaultEntityComponentRendererAttribute>();
     if (rendererTypeAttribute == null)
     {
         return;
     }
     var renderType = AssemblyRegistry.GetType(rendererTypeAttribute.TypeName);
     if (renderType != null && typeof(IEntityComponentRenderer).GetTypeInfo().IsAssignableFrom(renderType.GetTypeInfo()) && renderType.GetTypeInfo().DeclaredConstructors.Any(x => !x.IsStatic && x.GetParameters().Length == 0))
     {
         var entityComponentRendererType = new EntityComponentRendererType(type, renderType, rendererTypeAttribute.Order);
         RendererTypes.Add(entityComponentRendererType);
     }
 }
            public TypeRepresentation(object o)
            {
                Count = 1;
                Type t = o.GetType();

                System.Reflection.TypeInfo ti = t.GetTypeInfo();
                Base.Attributes.ReporterDisplayNameAttribute rdma = (Base.Attributes.ReporterDisplayNameAttribute)ti.GetCustomAttribute(typeof(Base.Attributes.ReporterDisplayNameAttribute));
                if (rdma != null)
                {
                    Name = rdma.DisplayName;
                }
                else
                {
                    Name = o.GetType().Name;
                }
                _type    = t;
                Hash     = o.GetHashCode();
                Assembly = o.GetType().AssemblyQualifiedName;
            }
		public static bool HasJsonUseTypeHintAttribute ( TP tp ) {
#if WINDOWS_STORE
			return tp.GetCustomAttribute<JsonUseTypeHintAttribute> (true) != null;
#else
			return tp.GetCustomAttributes(typeof(JsonUseTypeHintAttribute),true).Length != 0;
#endif
		}
        public static string GenerateSource(TypeInfo typeInfo, out string fullClassName)
        {
            if (!typeInfo.IsInterface || !typeInfo.IsPublic)
            {
                throw new ArgumentException($"{typeInfo.FullName} must be a public interface");
            }

            if (typeInfo.IsGenericType)
            {
                throw new NotSupportedException($"Generic interfaces are not supported: {typeInfo.FullName}");
            }

            var className = typeInfo.FullName?.Replace(".", string.Empty);

            fullClassName = $"{RootNamespace}.{className}";

            using (Logger.BeginScope("Generator {0}:", className))
            {
                var serviceName  = typeInfo.GetCustomAttribute <FauxClientAttribute>().Name;
                var baseRoute    = typeInfo.GetCustomAttribute <RouteAttribute>()?.BaseRoute ?? string.Empty;
                var sealedString = GenerateSealedClasses ? "sealed" : string.Empty;

                Logger.LogTrace("Beginning to generate source");

                var classBuilder = new StringBuilder();
                classBuilder.AppendLine($"namespace {RootNamespace}");
                classBuilder.AppendLine("{");
                classBuilder.AppendLine("    // Generated by DHaven.Faux");
                classBuilder.AppendLine(
                    $"    public {sealedString} class {className} : DHaven.Faux.HttpSupport.DiscoveryAwareBase, {typeInfo.FullName}");
                classBuilder.AppendLine("    {");
                classBuilder.AppendLine($"        public {className}()");
                classBuilder.AppendLine($"            : base(\"{serviceName}\", \"{baseRoute}\") {{ }}");

                foreach (var method in typeInfo.GetMethods())
                {
                    BuildMethod(classBuilder, method);
                }

                classBuilder.AppendLine("    }");
                classBuilder.AppendLine("}");

                var sourceCode = classBuilder.ToString();

                Logger.LogTrace("Source generated");

                if (!OutputSourceFiles)
                {
                    return(sourceCode);
                }

                var fullPath = Path.Combine(SourceFilePath, $"{className}.cs");
                try
                {
                    Logger.LogTrace("Writing source file: {0}", fullPath);
                    File.WriteAllText(fullPath, sourceCode, Encoding.UTF8);
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(ex, "Could not write the source code for {0}", fullPath);
                }

                return(sourceCode);
            }
        }
 private static LoginType GetLoginType(TypeInfo typeInfo)
 {
     return typeInfo.GetCustomAttribute<AuthoAttribution>().LoginType;
 }
        public IEnumerable <string> GenerateSource(TypeInfo typeInfo, out string fullClassName)
        {
            if (!typeInfo.IsInterface || !typeInfo.IsPublic)
            {
                throw new ArgumentException($"{typeInfo.FullName} must be a public interface");
            }

            if (typeInfo.IsGenericType)
            {
                throw new NotSupportedException($"Generic interfaces are not supported: {typeInfo.FullName}");
            }

            var className = typeInfo.FullName?.Replace(".", string.Empty);

            fullClassName = $"{Config.RootNamespace}.{className}";

            using (logger.BeginScope("Generator {0}:", className))
            {
                var serviceName  = typeInfo.GetCustomAttribute <FauxClientAttribute>().Name;
                var baseRoute    = typeInfo.GetCustomAttribute <FauxClientAttribute>().Route ?? string.Empty;
                var sealedString = Config.GenerateSealedClasses ? "sealed" : string.Empty;

                logger.LogTrace("Beginning to generate source");

                using (var namespaceBuilder = new IndentBuilder())
                {
                    namespaceBuilder.AppendLine($"namespace {Config.RootNamespace}");
                    namespaceBuilder.AppendLine("{");
                    using (var classBuilder = namespaceBuilder.Indent())
                    {
                        classBuilder.AppendLine("// Generated by DHaven.Faux");
                        classBuilder.AppendLine(
                            $"public {sealedString} class {className} : DHaven.Faux.HttpSupport.DiscoveryAwareBase, {typeInfo.FullName}");
                        classBuilder.AppendLine("{");

                        using (var fieldBuilder = classBuilder.Indent())
                        {
                            fieldBuilder.AppendLine("private readonly Microsoft.Extensions.Logging.ILogger 仮logger;");
                        }

                        using (var constructorBuilder = classBuilder.Indent())
                        {
                            constructorBuilder.AppendLine($"public {className}(DHaven.Faux.HttpSupport.IHttpClient client,");
                            constructorBuilder.AppendLine("        Microsoft.Extensions.Logging.ILogger logger)");
                            constructorBuilder.AppendLine($"    : base(client, \"{serviceName}\", \"{baseRoute}\")");
                            constructorBuilder.AppendLine("{");
                            using (var insideCxrBuilder = constructorBuilder.Indent())
                            {
                                insideCxrBuilder.AppendLine("仮logger = logger;");
                            }

                            constructorBuilder.AppendLine("}");
                        }

                        foreach (var method in typeInfo.GetMethods())
                        {
                            using (var methodBuilder = classBuilder.Indent())
                            {
                                BuildMethod(methodBuilder, method);
                            }
                        }

                        classBuilder.AppendLine("}");
                    }

                    namespaceBuilder.AppendLine("}");

                    var sourceCode = namespaceBuilder.ToString();

                    logger.LogTrace("Source generated");

                    if (Config.OutputSourceFiles)
                    {
                        var fullPath = Path.Combine(Config.SourceFilePath, $"{className}.cs");
                        try
                        {
                            logger.LogTrace("Writing source file: {0}", fullPath);
                            File.WriteAllText(fullPath, sourceCode, Encoding.UTF8);
                        }
                        catch (Exception ex)
                        {
                            logger.LogWarning(ex, "Could not write the source code for {0}", fullPath);
                        }
                    }

                    return(new[] { sourceCode });
                }
            }
        }
 /// <summary>
 /// Checks whether the given enum is to be used as a bit field type.
 /// </summary>
 /// <param name="typeInfo"></param>
 /// <returns>True if the given enum is a bit field enum, false otherwise.</returns>
 private static bool IsBitFieldEnum(TypeInfo typeInfo)
 {
     return typeInfo.GetCustomAttribute(typeof(FlagsAttribute)) != null;
 }
 /// <summary>
 /// Determines whether the provided type info is an eligible part.
 /// </summary>
 /// <param name="typeInfo">The type information.</param>
 /// <returns>
 /// <c>true</c> if the type information is an eligible part, otherwise <c>false</c>.
 /// </returns>
 private bool IsEligiblePart(TypeInfo typeInfo)
 {
     return typeInfo.IsClass && !typeInfo.IsAbstract && typeInfo.GetCustomAttribute<ExcludeFromCompositionAttribute>() == null;
 }