Beispiel #1
0
        private void GenerateProperties(TsClass classModel, ScriptBuilder sb, TsGeneratorOutput generatorOutput)
        {
            var members = new List <TsProperty>();

            if ((generatorOutput & TsGeneratorOutput.Properties) == TsGeneratorOutput.Properties)
            {
                members.AddRange(classModel.Properties);
            }
            if ((generatorOutput & TsGeneratorOutput.Fields) == TsGeneratorOutput.Fields)
            {
                members.AddRange(classModel.Fields);
            }

            using (sb.IncreaseIndentation())
            {
                foreach (var property in members)
                {
                    if (property.IsIgnored ||
                        PropertyTypesToIgnore(property.PropertyType.Type) ||
                        (_typesPropertiesToIgnore.ContainsKey(classModel.Type) && _typesPropertiesToIgnore[classModel.Type].Contains(property.Name)))
                    {
                        continue;
                    }

                    AddDocCommentForCustomJsonConverter(sb, property);
                    _docAppender.AppendPropertyDoc(sb, property, this.GetPropertyName(property), this.GetPropertyType(property));
                    sb.AppendLineIndented($"{this.GetPropertyName(property)}: {this.GetPropertyType(property)};");
                }

                if (classModel.Type == typeof(PropertyBase))
                {
                    sb.AppendLineIndented($"type: string;");
                }
            }
        }
        public override string GenerateHubs(Assembly assembly, bool generateAsModules)
        {
            var hubs = assembly.GetTypes()
                       .Where(t => t.BaseType != null && t.BaseType.FullName != null && t.BaseType.FullName.Contains(HUB_TYPE))
                       .OrderBy(t => t.FullName)
                       .ToList();

            if (!hubs.Any())
            {
                Console.WriteLine("No SignalR hubs found");
                return("");
            }
            Console.WriteLine(hubs.Count + " SignalR hubs found");
            var requiredImports = new HashSet <string>();

            foreach (var hub in hubs)
            {
                requiredImports.Add(hub.Namespace.Split('.')[0]);
            }

            var scriptBuilder = new ScriptBuilder("    ");

            scriptBuilder.AppendLine();

            hubs.ForEach(h => GenerateHubInterfaces(h, scriptBuilder, generateAsModules, requiredImports));

            // Generate client connection interfaces
            if (generateAsModules)
            {
                scriptBuilder.Append("export ");
            }
            scriptBuilder.AppendLineIndented("interface SignalR {");
            using (scriptBuilder.IncreaseIndentation())
            {
                hubs.ForEach(h => scriptBuilder.AppendLineIndented(h.Name.ToCamelCase() + ": I" + h.Name + "Proxy;"));
            }
            scriptBuilder.AppendLineIndented("}");
            scriptBuilder.AppendLine();

            var output = scriptBuilder.ToString();

            // Output imports if required
            // TODO: this isn't going to work if SignalR hubs are in more than one assembly.
            if (generateAsModules)
            {
                var imports = "import Classes = require(\"./classes\");\r\n";
                foreach (var ns in requiredImports)
                {
                    imports += string.Format("import {0} = Classes.{0};\r\n", ns);
                }
                imports += "\r\n";
                output   = imports + output;
            }

            return(output);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="classModel"></param>
        /// <param name="sb"></param>
        /// <param name="generatorOutput"></param>
        protected override void AppendClassDefinition(TsClass classModel, ScriptBuilder sb, TsGeneratorOutput generatorOutput)
        {
            string typeName   = this.GetTypeName(classModel);
            string visibility = this.GetTypeVisibility(classModel, typeName) ? "export " : "";

            sb.AppendFormatIndented("{0}interface {1}", visibility, typeName);
            if (classModel.BaseType != null)
            {
                sb.AppendFormat(" extends {0}", this.GetFullyQualifiedTypeName(classModel.BaseType));
            }
            sb.AppendLine(" {");
            var members = new List <TsProperty>();

            if ((generatorOutput & TsGeneratorOutput.Properties) == TsGeneratorOutput.Properties)
            {
                members.AddRange(classModel.Properties);
            }
            if ((generatorOutput & TsGeneratorOutput.Fields) == TsGeneratorOutput.Fields)
            {
                members.AddRange(classModel.Fields);
            }
            using (sb.IncreaseIndentation())
            {
                foreach (var property in members)
                {
                    if (property.IsIgnored)
                    {
                        continue;
                    }
                    var propTypeName = this.GetPropertyType(property);
                    if (property.PropertyType.IsCollection())
                    {
                        //Note: new member functon checking if property is collection or not
                        //Also remove the array brackets from the name
                        if (propTypeName.Length > 2 && propTypeName.Substring(propTypeName.Length - 2) == "[]")
                        {
                            propTypeName = propTypeName.Substring(0, propTypeName.Length - 2);
                        }
                        propTypeName = "KnockoutViewModelArray<" + propTypeName + ">";
                    }
                    else if (property.PropertyType.Type.IsClass && property.PropertyType.Type != typeof(string))
                    {
                        // KnockoutViewModel does not emit observable objects for classes, it leaves the class in-situ.
                        // It's just value types, collections and strings that are observable.
                    }
                    else
                    {
                        propTypeName = "KnockoutObservable<" + propTypeName + ">";
                    }
                    sb.AppendLineIndented(string.Format("{0}: {1};", this.GetPropertyName(property), propTypeName));
                }
            }
            sb.AppendLineIndented("}");
            _generatedClasses.Add(classModel);
        }
        private void GenerateHubInterfaces(Type hubType, ScriptBuilder scriptBuilder, bool generateAsModules, HashSet <string> requiredImports)
        {
            if (!hubType.BaseType.FullName.Contains(HUB_TYPE))
            {
                throw new ArgumentException("The supplied type does not appear to be a SignalR hub.", "hubType");
            }

            // Build the client interface
            if (generateAsModules)
            {
                scriptBuilder.AppendIndented("export ");
            }
            scriptBuilder.AppendLineIndented(string.Format("interface I{0}Client {{", hubType.Name));
            using (scriptBuilder.IncreaseIndentation())
            {
                if (!hubType.BaseType.IsGenericType)
                {
                    scriptBuilder.AppendLineIndented("/* Client interface not generated as hub doesn't derive from Hub<T> */");
                }
                else
                {
                    GenerateMethods(scriptBuilder, requiredImports, hubType.BaseType.GetGenericArguments().First());
                }
            }
            scriptBuilder.AppendLineIndented("}");
            scriptBuilder.AppendLine();

            // Build the interface containing the SERVER methods
            if (generateAsModules)
            {
                scriptBuilder.AppendIndented("export ");
            }
            scriptBuilder.AppendLineIndented(string.Format("interface I{0} {{", hubType.Name));
            using (scriptBuilder.IncreaseIndentation())
            {
                GenerateMethods(scriptBuilder, requiredImports, hubType);
            }
            scriptBuilder.AppendLineIndented("}");
            scriptBuilder.AppendLine();

            // Build the proxy class (represents the proxy generated by signalR).
            if (generateAsModules)
            {
                scriptBuilder.AppendIndented("export ");
            }
            scriptBuilder.AppendLineIndented(string.Format("interface I{0}Proxy {{", hubType.Name));
            using (scriptBuilder.IncreaseIndentation())
            {
                scriptBuilder.AppendLineIndented("server: I" + hubType.Name + ";");
                scriptBuilder.AppendLineIndented("client: I" + hubType.Name + "Client;");
            }
            scriptBuilder.AppendLineIndented("}");
            scriptBuilder.AppendLine();
        }
        /// <summary>
        /// Appends the appropriate class definition for the specified member
        /// </summary>
        /// <param name="classModel"></param>
        /// <param name="sb"></param>
        /// <param name="generatorOutput"></param>
        protected override void AppendClassDefinition(TsClass classModel, ScriptBuilder sb, TsGeneratorOutput generatorOutput)
        {
            Tags.TryGetValue(classModel, out string tag);

            sb.AppendLineIndented($"// {classModel.Name} ({tag})");
            switch (tag)
            {
            case KoClass:
                AppendClassDefinition(classModel, sb, generatorOutput, true);
                break;

            case KoInterface:
                AppendKoInterfaceDefinition(classModel, sb, generatorOutput);
                break;

            case Poco:
                AppendClassDefinition(classModel, sb, generatorOutput, false);
                break;

            default:
                base.AppendClassDefinition(classModel, sb, generatorOutput);
                break;
            }

            _generatedClasses.Add(classModel);
        }
Beispiel #6
0
        private void AddRequestRenameInformation(ScriptBuilder sb, TsClass classModel)
        {
            if (_restSpec.SkipRequestImplementation(classModel.Name))
            {
                return;
            }

            var i = classModel.Name;

            if (!ClientTypesExporter.InterfaceRegex.IsMatch(i))
            {
                i = $"I{i}";
            }

            if (_restSpec.SkipRequestImplementation(i))
            {
                return;
            }
            if (!_restSpec.Requests.TryGetValue(i, out var mapping))
            {
                throw new Exception($"Could not get {i} original rest spec file name");
            }

            var originalSpec = Path.GetFileNameWithoutExtension(mapping.Json.Name);

            sb.AppendLineIndented($"@rest_spec_name(\"{originalSpec}\")");
        }
Beispiel #7
0
        private void AppendInterfaceDef(TsClass classModel, ScriptBuilder sb, TsGeneratorOutput generatorOutput)
        {
            AddNamespaceHeaderEnum(classModel.Name, classModel.Type.Assembly.FullName, sb);

            var typeName   = this.GetTypeName(classModel);
            var visibility = this.GetTypeVisibility(classModel, typeName) ? "export " : "";

            _docAppender.AppendClassDoc(sb, classModel, typeName);

            sb.AppendFormatIndented("{0}interface {1}", visibility, typeName);
            if (classModel.BaseType != null)
            {
                sb.AppendFormat(" extends {0}", this.GetFullyQualifiedTypeName(classModel.BaseType));
            }

            var interfaces = classModel.Interfaces.Where(m => CsharpTypeInfoProvider.ExposedInterfaces.Contains(m.Type)).ToList();

            if (interfaces.Count > 0)
            {
                var implementations = interfaces.Select(GetFullyQualifiedTypeName).ToArray();
                var prefixFormat    = " implements {0}";

                sb.AppendFormat(prefixFormat, string.Join(" ,", implementations));
            }

            sb.AppendLine(" {");

            GenerateProperties(classModel, sb, generatorOutput);

            sb.AppendLineIndented("}");
            _generatedClasses.Add(classModel);
        }
        private void AppendKoInterfaceDefinition(TsClass classModel, ScriptBuilder sb, TsGeneratorOutput generatorOutput)
        {
            string typeName   = this.GetTypeName(classModel);
            string visibility = this.GetTypeVisibility(classModel, typeName) ? "export " : "";

            sb.AppendIndented($"{visibility}interface {typeName}");
            if (classModel.BaseType != null)
            {
                sb.Append($" extends {this.GetFullyQualifiedTypeName(classModel.BaseType)}");
            }
            sb.AppendLine(" {");
            var members = new List <TsProperty>();

            if ((generatorOutput & TsGeneratorOutput.Properties) == TsGeneratorOutput.Properties)
            {
                members.AddRange(classModel.Properties);
            }
            if ((generatorOutput & TsGeneratorOutput.Fields) == TsGeneratorOutput.Fields)
            {
                members.AddRange(classModel.Fields);
            }
            using (sb.IncreaseIndentation())
            {
                foreach (TsProperty property in members)
                {
                    if (property.IsIgnored)
                    {
                        continue;
                    }
                    string propTypeName = this.GetPropertyType(property);
                    if (IsCollection(property))
                    {
                        if (propTypeName.Length > 2 && propTypeName.Substring(propTypeName.Length - 2) == "[]")
                        {
                            propTypeName = propTypeName.Substring(0, propTypeName.Length - 2);
                        }
                        propTypeName = "ko.ObservableArray<" + propTypeName + ">";
                    }
                    else
                    {
                        propTypeName = "ko.Subscribable<" + propTypeName + ">";
                    }
                    sb.AppendLineIndented($"{this.GetPropertyName(property)}: {propTypeName};");
                }
            }
            sb.AppendLineIndented("}");
        }
Beispiel #9
0
        protected override void AppendClassDefinition(TsClass classModel, ScriptBuilder sb, TsGeneratorOutput generatorOutput)
        {
            string typeName   = this.GetTypeName(classModel);
            string visibility = this.GetTypeVisibility(classModel, typeName) ? "export " : "";

            sb.AppendFormatIndented(
                "{0}class {1} extends {2}",
                visibility,
                typeName,
                //all bottom-level classes must extend Backbone.Model.
                classModel.BaseType != null ? this.GetFullyQualifiedTypeName(classModel.BaseType) : "Backbone.Model");

            sb.AppendLine(" {");

            var members = new List <TsProperty>();

            if ((generatorOutput & TsGeneratorOutput.Properties) == TsGeneratorOutput.Properties)
            {
                members.AddRange(classModel.Properties);
            }
            if ((generatorOutput & TsGeneratorOutput.Fields) == TsGeneratorOutput.Fields)
            {
                members.AddRange(classModel.Fields);
            }
            using (sb.IncreaseIndentation())
            {
                foreach (var property in members)
                {
                    if (property.IsIgnored)
                    {
                        continue;
                    }

                    sb.AppendLineIndented(string.Format(
                                              "get {0}(): {1} {{ return this.get(\"{0}\"); }}",
                                              this.GetPropertyName(property), this.GetPropertyType(property)));

                    sb.AppendLineIndented(string.Format(
                                              "set {0}(v: {1}) {{ this.set(\"{0}\", v); }}",
                                              this.GetPropertyName(property), this.GetPropertyType(property)));
                }
            }

            sb.AppendLineIndented("}");

            _generatedClasses.Add(classModel);
        }
Beispiel #10
0
 private void GenerateMethods(ScriptBuilder scriptBuilder, Type type)
 {
     type.GetMethods()
     .Where(mi => mi.GetBaseDefinition().DeclaringType.Name == type.Name)
     .OrderBy(mi => mi.Name)
     .ToList()
     .ForEach(m => scriptBuilder.AppendLineIndented(GenerateMethodDeclaration(m)));
 }
Beispiel #11
0
        private void AddDocCommentForCustomJsonConverter(ScriptBuilder sb, TsProperty property)
        {
            var declaringType = property.MemberInfo.DeclaringType;
            var propertyName  = property.MemberInfo.Name;

            var iface         = declaringType.GetInterfaces().FirstOrDefault(ii => ii.Name == "I" + declaringType.Name);
            var ifaceProperty = iface?.GetProperty(propertyName);

            var attributes = new List <Attribute>();

            if (ifaceProperty != null)
            {
                attributes.AddRange(ifaceProperty.GetCustomAttributes());
            }
            attributes.AddRange(property.MemberInfo.GetCustomAttributes());

            var isRequest          = declaringType.Name.Contains("Request");
            var nonGenericTypeName = ClientTypesExporter.RemoveGeneric.Replace(declaringType.Name, "$1");

            if (ClientTypesExporter.InterfaceRegex.IsMatch(nonGenericTypeName))
            {
                nonGenericTypeName = nonGenericTypeName.Substring(1);
            }

            if (isRequest && this._typeInfoProvider.RequestParameters.ContainsKey(nonGenericTypeName))
            {
                var rp   = this._typeInfoProvider.RequestParameters[nonGenericTypeName];
                var prop = rp.GetProperty(propertyName);
                if (prop != null)
                {
                    sb.AppendLineIndented("@request_parameter()");
                }
            }

            var converter = attributes.FirstOrDefault(a => a.TypeId.ToString() == "Nest.Json.JsonConverterAttribute");

            if (converter != null)
            {
                if (GetConverter(converter, out var type))
                {
                    return;
                }
                sb.AppendLineIndented($"@prop_serializer(\"{type.Name}\")");
            }
        }
        protected override void AppendClassDefinition(TsClass classModel, ScriptBuilder sb, TsGeneratorOutput generatorOutput)
        {
            string typeName = this.GetTypeName(classModel);
            string visibility = this.GetTypeVisibility(classModel, typeName) ? "export " : "";
            sb.AppendFormatIndented(
                "{0}class {1} extends {2}",
                visibility,
                typeName,
                //all bottom-level classes must extend Backbone.Model.
                classModel.BaseType != null ? this.GetFullyQualifiedTypeName(classModel.BaseType) : "Backbone.Model");

            sb.AppendLine(" {");

            var members = new List<TsProperty>();
            if ((generatorOutput & TsGeneratorOutput.Properties) == TsGeneratorOutput.Properties)
            {
                members.AddRange(classModel.Properties);
            }
            if ((generatorOutput & TsGeneratorOutput.Fields) == TsGeneratorOutput.Fields)
            {
                members.AddRange(classModel.Fields);
            }
            using (sb.IncreaseIndentation())
            {
                foreach (var property in members)
                {
                    if (property.IsIgnored)
                    {
                        continue;
                    }

                    sb.AppendLineIndented(string.Format(
                        "get {0}(): {1} {{ return this.get(\"{0}\"); }}",
                        this.GetPropertyName(property), this.GetPropertyType(property)));

                    sb.AppendLineIndented(string.Format(
                        "set {0}(v: {1}) {{ this.set(\"{0}\", v); }}",
                        this.GetPropertyName(property), this.GetPropertyType(property)));
                }
            }

            sb.AppendLineIndented("}");

            _generatedClasses.Add(classModel);
        }
Beispiel #13
0
        private void GenerateMethods(ScriptBuilder scriptBuilder, SignalRHubDesc hub, TypeConverter converter, bool isClient, Func <MethodInfo, TypeConverter, string> generator)
        {
            var type = isClient ? hub.HubType.GetDnxCompatible().BaseType.GenericTypeArguments.First() : hub.HubType;

            type.GetDnxCompatible().GetMethods()
            .Where(mi => !mi.IsStatic && mi.GetBaseDefinition().DeclaringType == type)
            .OrderBy(mi => mi.Name)
            .ToList()
            .ForEach(m => scriptBuilder.AppendLineIndented(generator(m, converter)));
        }
Beispiel #14
0
        private void AddNamespaceHeader(string name, ScriptBuilder sb)
        {
            var n = "common";

            if (this._sourceDirectory.TypeNameToNamespaceMapping.TryGetValue(name, out var ns))
            {
                n = string.Join('.', ns.Split(".").Select(StringExtensions.SnakeCase));
            }

            sb.AppendLineIndented($"@namespace(\"{n}\")");
        }
Beispiel #15
0
        public void WriteHubs(SignalRHubDesc[] hubs, TypeConverter converter, CustomIndentedTextWriter writer)
        {
            var hubList       = hubs.ToList();
            var scriptBuilder = new ScriptBuilder("    ");

            // Output signalR style promise interface:
            scriptBuilder.AppendLine("interface ISignalRPromise<T> {");
            using (scriptBuilder.IncreaseIndentation())
            {
                scriptBuilder.AppendLineIndented("done(cb: (result: T) => any): ISignalRPromise<T>;");
                scriptBuilder.AppendLineIndented("error(cb: (error: any) => any): ISignalRPromise<T>;");
            }
            scriptBuilder.AppendLineIndented("}");
            scriptBuilder.AppendLine();
            hubList.ForEach(h => GenerateHubInterfaces(h, scriptBuilder, converter));
            // Generate client connection interfaces
            scriptBuilder.AppendLineIndented("interface SignalR {");
            using (scriptBuilder.IncreaseIndentation())
            {
                hubList.ForEach(h => scriptBuilder.AppendLineIndented(h.HubClassName.ToCamelCase() + ": I" + h.HubClassName + "Proxy;"));
            }
            scriptBuilder.AppendLineIndented("}");
            scriptBuilder.AppendLine();

            writer.WriteLine(scriptBuilder.ToString());
        }
Beispiel #16
0
        private string GenerateHubs(Assembly assembly, TypeConverter converter)
        {
            var hubs = assembly.GetTypes()
                       .Where(t => t.GetDnxCompatible().BaseType != null && t.GetDnxCompatible().BaseType.FullName != null && t.GetDnxCompatible().BaseType.FullName.Contains(HUB_TYPE))
                       .OrderBy(t => t.FullName)
                       .ToList();

            if (!hubs.Any())
            {
                return("");
            }

            var scriptBuilder = new ScriptBuilder("    ");

            // Output signalR style promise interface:
            scriptBuilder.AppendLine("interface ISignalRPromise<T> {");
            using (scriptBuilder.IncreaseIndentation())
            {
                scriptBuilder.AppendLineIndented("done(cb: (result: T) => any): ISignalRPromise<T>;");
                scriptBuilder.AppendLineIndented("error(cb: (error: any) => any): ISignalRPromise<T>;");
            }
            scriptBuilder.AppendLineIndented("}");
            scriptBuilder.AppendLine();
            hubs.ForEach(h => GenerateHubInterfaces(new SignalRHubDesc(h), scriptBuilder, converter));
            // Generate client connection interfaces
            scriptBuilder.AppendLineIndented("interface SignalR {");
            using (scriptBuilder.IncreaseIndentation())
            {
                hubs.ForEach(h => scriptBuilder.AppendLineIndented(h.Name.ToCamelCase() + ": I" + h.Name + "Proxy;"));
            }
            scriptBuilder.AppendLineIndented("}");
            scriptBuilder.AppendLine();
            return(scriptBuilder.ToString());
        }
Beispiel #17
0
        protected override void AppendEnumDefinition(TsEnum enumModel, ScriptBuilder sb, TsGeneratorOutput output)
        {
            string typeName   = this.GetTypeName(enumModel);
            string visibility = ((output & TsGeneratorOutput.Enums) == TsGeneratorOutput.Enums || (output & TsGeneratorOutput.Constants) == TsGeneratorOutput.Constants) ? "export " : "";

            this._docAppender.AppendEnumDoc(sb, enumModel, typeName);
            string constSpecifier = this.GenerateConstEnums ? "const " : string.Empty;

            sb.AppendLineIndented(string.Format("{0}{2}enum {1} {{", visibility, typeName, constSpecifier));
            using (sb.IncreaseIndentation())
            {
                int i = 1;
                foreach (TsEnumValue v in enumModel.Values)
                {
                    this._docAppender.AppendEnumValueDoc(sb, v);
                    sb.AppendLineIndented(string.Format((i < enumModel.Values.Count) ? "{0} = {1}," : "{0} = {1}", ToCamelCase(v.Name), v.Value));
                    i++;
                }
            }
            sb.AppendLineIndented("}");
            this._generatedEnums.Add(enumModel);
        }
Beispiel #18
0
        protected override void AppendEnumDefinition(TsEnum enumModel, ScriptBuilder sb, TsGeneratorOutput output)
        {
            if (!AddNamespaceHeaderEnum(enumModel.Name, enumModel.Type.Assembly.FullName, sb))
            {
                return;
            }
            if (_typesToIgnore.Contains(enumModel.Type))
            {
                return;
            }

            var typeName   = this.GetTypeName(enumModel);
            var visibility = string.Empty;

            _docAppender.AppendEnumDoc(sb, enumModel, typeName);

            var constSpecifier = this.GenerateConstEnums ? "const " : string.Empty;

            sb.AppendLineIndented(string.Format("{0}{2}enum {1} {{", visibility, typeName, constSpecifier));

            using (sb.IncreaseIndentation())
            {
                var i = 1;
                foreach (var v in enumModel.Values)
                {
                    _docAppender.AppendEnumValueDoc(sb, v);
                    var enumMemberAttribute = v.Field.GetCustomAttribute <EnumMemberAttribute>();
                    var name = (!string.IsNullOrEmpty(enumMemberAttribute?.Value) ? enumMemberAttribute.Value : v.Name).QuoteMaybe();

                    sb.AppendLineIndented(string.Format(i < enumModel.Values.Count ? "{0} = {1}," : "{0} = {1}", name, v.Value));
                    i++;
                }
            }

            sb.AppendLineIndented("}");

            _generatedEnums.Add(enumModel);
        }
Beispiel #19
0
        private bool AddNamespaceHeaderEnum(string name, string ns, ScriptBuilder sb)
        {
            if (!ns.StartsWith("Nest") && !ns.StartsWith("Elasticsearch.Net"))
            {
                return(false);
            }

            var n = "common";

            if (this._sourceDirectory.TypeNameToNamespaceMapping.TryGetValue(name, out var fullNs))
            {
                n = string.Join('.', fullNs.Split(".").Select(StringExtensions.SnakeCase));
            }

            sb.AppendLineIndented($"/** namespace:{n} **/");
            return(true);
        }
Beispiel #20
0
        private static void AddDocCommentForCustomJsonConverter(ScriptBuilder sb, TsClass classModel)
        {
            var iface = classModel.Type.GetInterfaces().FirstOrDefault(i => i.Name == "I" + classModel.Type.Name);

            var attributes = new List <Attribute>();

            if (iface != null)
            {
                attributes.AddRange(iface.GetCustomAttributes());
            }
            attributes.AddRange(classModel.Type.GetCustomAttributes());

            var converter = attributes.FirstOrDefault(a => a.TypeId.ToString() == "Nest.Json.JsonConverterAttribute");

            if (converter != null)
            {
                if (GetConverter(converter, out var type))
                {
                    return;
                }
                sb.AppendLineIndented($"@class_serializer(\"{type.Name}\")");
            }
        }
        private void AppendClassDefinition(TsClass classModel, ScriptBuilder sb, TsGeneratorOutput generatorOutput, bool ko)
        {
            string typeName = this.GetTypeName(classModel);

            string visibility = this.GetTypeVisibility(classModel, typeName) ? "export " : "";

            sb.AppendIndented($"{visibility}class {typeName}");
            if (classModel.BaseType != null)
            {
                string baseTypeName = this.GetFullyQualifiedTypeName(classModel.BaseType);
                if (baseTypeName.StartsWith(classModel.Module.Name + ".", StringComparison.Ordinal))
                {
                    baseTypeName = baseTypeName.Substring(classModel.Module.Name.Length + 1);
                }

                sb.Append($" extends {baseTypeName}");
                sb.AppendLine(" {");
                using (sb.IncreaseIndentation())
                {
                    sb.AppendLineIndented("constructor() {");
                    using (sb.IncreaseIndentation())
                    {
                        sb.AppendLineIndented("super();");
                    }
                    sb.AppendLineIndented("}");
                }
            }
            else
            {
                sb.AppendLine(" {");
            }
            var members = new List <TsProperty>();

            if ((generatorOutput & TsGeneratorOutput.Properties) == TsGeneratorOutput.Properties)
            {
                members.AddRange(classModel.Properties);
            }
            if ((generatorOutput & TsGeneratorOutput.Fields) == TsGeneratorOutput.Fields)
            {
                members.AddRange(classModel.Fields);
            }
            using (sb.IncreaseIndentation())
            {
                foreach (TsProperty property in members.Where(m => !m.IsIgnored))
                {
                    string propTypeName = this.GetPropertyType(property);
                    if (IsCollection(property))
                    {
                        if (propTypeName.EndsWith("[]", StringComparison.Ordinal))
                        {
                            propTypeName = propTypeName.Substring(0, propTypeName.Length - "[]".Length);
                        }
                        if (ko)
                        {
                            sb.AppendLineIndented($"{this.GetPropertyName(property)}: ko.ObservableArray<{propTypeName}> = ko.observableArray([]);");
                        }
                        else
                        {
                            sb.AppendLineIndented($"{this.GetPropertyName(property)}: {propTypeName}[];");
                        }
                    }
                    else
                    {
                        if (ko)
                        {
                            sb.AppendLineIndented($"{this.GetPropertyName(property)}: ko.Subscribable<{propTypeName}> = ko.observable(null);");
                        }
                        else
                        {
                            sb.AppendLineIndented($"{this.GetPropertyName(property)}: {propTypeName};");
                        }
                    }
                }
            }

            sb.AppendLineIndented("}");
            _generatedClasses.Add(classModel);
        }
Beispiel #22
0
        private void GenerateHubInterfaces(SignalRHubDesc hub, ScriptBuilder scriptBuilder, TypeConverter converter)
        {
            if (!hub.HubType.GetDnxCompatible().BaseType.FullName.Contains(HUB_TYPE))
            {
                throw new ArgumentException("The supplied type does not appear to be a SignalR hub.", "hubType");
            }
            // Build the client interface
            scriptBuilder.AppendLineIndented(string.Format("export interface I{0}Client {{", hub.HubClassName));
            using (scriptBuilder.IncreaseIndentation())
            {
                if (!hub.HubType.GetDnxCompatible().BaseType.GetDnxCompatible().IsGenericType)
                {
                    scriptBuilder.AppendLineIndented("/* Client interface not generated as hub doesn't derive from Hub<T> */");
                }
                else
                {
                    GenerateMethods(scriptBuilder, hub, converter, true, (mi, tc) => GenerateMethodDeclaration(mi, tc, hub, true));
                }
            }
            scriptBuilder.AppendLineIndented("}");
            scriptBuilder.AppendLine();

            // Build the function for creating a hub proxy
            if (string.IsNullOrEmpty(hub.HubSignalRName))
            {
                scriptBuilder.AppendLineIndented($"/* function {hub.HubClassName}Client_CreateHubProxy not generated as hub type {hub.HubType.FullName} does not have a HubNameAttribute or the hub name is an empty string. */");
            }
            else
            {
                scriptBuilder.AppendLineIndented($"export function {hub.HubClassName}Client_CreateHubProxy(connection: SignalR.Hub.Connection): SignalR.Hub.Proxy {{");
                using (scriptBuilder.IncreaseIndentation())
                    scriptBuilder.AppendLineIndented($"return connection.createHubProxy('{hub.HubSignalRName}');");
                scriptBuilder.AppendLineIndented("}");
            }
            scriptBuilder.AppendLine();

            // Build the function for wiring up a proxy to a client interface
            if (!hub.HubType.GetDnxCompatible().BaseType.GetDnxCompatible().IsGenericType)
            {
                scriptBuilder.AppendLineIndented($"/* function {hub.HubClassName}Client_BindProxy not generated as hub doesn't derive from Hub<T> */");
            }
            else
            {
                scriptBuilder.AppendLineIndented($"export function {hub.HubClassName}Client_BindProxy(proxy: SignalR.Hub.Proxy, client: I{hub.HubClassName}Client): void {{");
                using (scriptBuilder.IncreaseIndentation())
                {
                    GenerateMethods(scriptBuilder, hub, converter, true, (mi, tc) => GenerateMethodProxyBinding(mi, tc, hub));
                }
                scriptBuilder.AppendLineIndented("}");
            }
            scriptBuilder.AppendLine();

            // Build the interface containing the SERVER methods
            scriptBuilder.AppendLineIndented($"interface I{hub.HubClassName} {{");
            using (scriptBuilder.IncreaseIndentation())
            {
                GenerateMethods(scriptBuilder, hub, converter, false, (mi, tc) => GenerateMethodDeclaration(mi, tc, hub, false));
            }
            scriptBuilder.AppendLineIndented("}");
            scriptBuilder.AppendLine();
            // Build the proxy class (represents the proxy generated by signalR).
            scriptBuilder.AppendLineIndented(string.Format("interface I{0}Proxy {{", hub.HubClassName));
            using (scriptBuilder.IncreaseIndentation())
            {
                scriptBuilder.AppendLineIndented("server: I" + hub.HubClassName + ";");
                scriptBuilder.AppendLineIndented("client: I" + hub.HubClassName + "Client;");
            }
            scriptBuilder.AppendLineIndented("}");
            scriptBuilder.AppendLine();
        }
Beispiel #23
0
        private void AppendClassDef(TsClass classModel, ScriptBuilder sb, TsGeneratorOutput generatorOutput)
        {
            AddNamespaceHeader(classModel.Name, sb);

            var typeName   = this.GetTypeName(classModel);
            var visibility = this.GetTypeVisibility(classModel, typeName) ? "export " : "";

            AddRequestRenameInformation(sb, classModel);
            AddDocCommentForCustomJsonConverter(sb, classModel);
            _docAppender.AppendClassDoc(sb, classModel, typeName);

            sb.AppendFormatIndented("{0}class {1}", visibility, typeName);
            if (CsharpTypeInfoProvider.StringAbstractions.Contains(classModel.Type))
            {
                sb.AppendLineIndented(" extends String {}");
                return;
            }

            void EnforceBaseClass <TInterface, TBase>()
            {
                if (classModel.BaseType != null)
                {
                    return;
                }
                if (classModel.Type == typeof(TBase))
                {
                    return;
                }
                if (typeof(TInterface).IsAssignableFrom(classModel.Type))
                {
                    classModel.BaseType = new TsClass(typeof(TBase));
                }
            }

            EnforceBaseClass <IAnalyzer, AnalyzerBase>();
            EnforceBaseClass <ITokenizer, TokenizerBase>();
            EnforceBaseClass <ITokenFilter, TokenFilterBase>();
            EnforceBaseClass <ICharFilter, CharFilterBase>();
            EnforceBaseClass <IProperty, PropertyBase>();
            EnforceBaseClass <IResponse, ResponseBase>();

            if (classModel.BaseType != null)
            {
                sb.AppendFormat(" extends {0}", this.GetFullyQualifiedTypeName(classModel.BaseType));
            }

            var interfaces = classModel.Interfaces.Where(m => CsharpTypeInfoProvider.ExposedInterfaces.Contains(m.Type)).ToList();

            if (interfaces.Count > 0)
            {
                var implementations = interfaces.Select(GetFullyQualifiedTypeName).ToArray();
                var prefixFormat    = " implements {0}";

                sb.AppendFormat(prefixFormat, string.Join(" ,", implementations));
            }

            sb.AppendLine(" {");

            GenerateProperties(classModel, sb, generatorOutput);

            sb.AppendLineIndented("}");
            _generatedClasses.Add(classModel);

            //generate a closed cat response type (NEST uses catresponse<TRecord> for all)
            if (typeof(ICatRecord).IsAssignableFrom(classModel.Type))
            {
                var catResponseName = classModel.Type.Name.Replace("Record", "Response");
                AddNamespaceHeader(classModel.Name, sb);
                sb.AppendLineIndented($"class {catResponseName} extends ResponseBase {{");
                using (sb.IncreaseIndentation())
                    sb.AppendLineIndented($"records: {typeName}[];");
                sb.AppendLineIndented("}");
            }
        }