コード例 #1
0
        /// <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);
        }
コード例 #2
0
        /// <summary>
        /// Generates class definition and appends it to the output.
        /// </summary>
        /// <param name="classModel">The class to generate definition for.</param>
        /// <param name="sb">The output.</param>
        /// <param name="generatorOutput"></param>
        protected virtual void AppendConstantModule(TsClass classModel, ScriptBuilder sb)
        {
            if (!classModel.Constants.Any())
            {
                return;
            }

            string typeName = this.GetTypeName(classModel);

            sb.AppendLineIndented(string.Format("export namespace {0} {{", typeName));

            using (sb.IncreaseIndentation()) {
                foreach (var property in classModel.Constants)
                {
                    if (property.IsIgnored)
                    {
                        continue;
                    }

                    _docAppender.AppendConstantModuleDoc(sb, property, this.GetPropertyName(property), this.GetPropertyType(property));
                    sb.AppendFormatIndented("export const {0}: {1} = {2};", this.GetPropertyName(property), this.GetPropertyType(property), this.GetPropertyConstantValue(property));
                    sb.AppendLine();
                }
            }
            sb.AppendLineIndented("}");

            _generatedClasses.Add(classModel);
        }
コード例 #3
0
        public void WhenInitializedWithInnerClass_ModuleIsSetToNamespaceAndOuterClass()
        {
            var target = new TsClass(typeof(TypeLite.Tests.TestModels.Outer.Inner));

            Assert.NotNull(target.Module);
            Assert.Equal(typeof(TypeLite.Tests.TestModels.Outer.Inner).Namespace + ".Outer", target.Module.Name);
        }
コード例 #4
0
        private static string TypeFormatter(TsType tsType, ITsTypeFormatter f)
        {
            TsClass tsClass = (TsClass)tsType;

            //Prefix classname with I
            return("I" + tsClass.Name);
        }
コード例 #5
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}\")");
        }
コード例 #6
0
        public void WhenInitialized_ModuleIsSetToNamespaceModule()
        {
            var target = new TsClass(typeof(Address));

            Assert.NotNull(target.Module);
            Assert.Equal(typeof(Address).Namespace, target.Module.Name);
        }
コード例 #7
0
        public void WhenInitializedWithClassThatHasBaseClass_BaseTypeIsSet()
        {
            var target = new TsClass(typeof(Employee));

            Assert.NotNull(target.BaseType);
            Assert.Equal(typeof(Person), target.BaseType.Type);
        }
コード例 #8
0
        public void WhenInitialized_PropertiesAreCreated()
        {
            var target = new TsClass(typeof(Address));

            Assert.Single(target.Properties.Where(o => o.MemberInfo == typeof(Address).GetProperty("Street")));
            Assert.Single(target.Properties.Where(o => o.MemberInfo == typeof(Address).GetProperty("Town")));
        }
コード例 #9
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;");
                }
            }
        }
コード例 #10
0
        protected virtual List <TsClass> SortByDependency(List <TsClass> tsClasses)
        {
            List <TsClass>  sorted = new List <TsClass>();
            Queue <TsClass> queue  = new Queue <TsClass>(tsClasses);

            while (queue.Count > 0)
            {
                TsClass processedClass = queue.Dequeue();
                if (processedClass.BaseType == null)
                {
                    if (!sorted.Contains(processedClass))
                    {
                        sorted.Add(processedClass);
                    }
                }
                else
                {
                    TsClass baseClass = tsClasses.Single(c => c.Type.FullName == processedClass.BaseType.Type.FullName);
                    if (sorted.Contains(baseClass))
                    {
                        if (!sorted.Contains(processedClass))
                        {
                            sorted.Add(processedClass);
                        }
                    }
                    else
                    {
                        queue.Enqueue(processedClass);
                    }
                }
            }

            return(sorted);
        }
コード例 #11
0
        public virtual string WriteClass(TsClass netClass)
        {
            var exportStr = netClass.IsPublic ? "export " : "";
            var extends   = netClass.BaseTypes.Any()
                ? " extends " + string.Join(", ", netClass.BaseTypes.Select(WriteTypeName))
                : "";
            var generics = netClass.GenericParameters.Any()
                ? $" <{string.Join(", ", netClass.GenericParameters.Select(WriteGenericParameter))}>"
                : "";

            var methods = GetMethodsString(netClass);
            var fields  = GetFieldsString(netClass);
            //var properties = GetPropertiesString(netClass);
            var events        = GetEventsString(netClass);
            var nestedClasses = GetNestedClassesString(netClass);

            var body = JoinBodyText(fields, events, methods);

            //TODO: config for brackets on same line as declaration
            return($"{exportStr}class {netClass.Name}{generics}{extends}" + _config.NewLine +
                   @"{" + _config.NewLine +
                   body +
                   @"}" +
                   nestedClasses);
        }
コード例 #12
0
        /// <summary>
        /// Generates class definition and appends it to the output.
        /// </summary>
        /// <param name="classModel">The class to generate definition for.</param>
        /// <param name="sb">The output.</param>
        protected virtual void AppendConstantModule(TsClass classModel, IndentedStringBuilder sb)
        {
            if (!classModel.Constants.Any())
            {
                return;
            }

            var typeName = GetTypeName(classModel);

            sb.AppendLine(string.Format("export module {0} {{", typeName));

            using (sb.Indent())
            {
                foreach (var property in classModel.Constants)
                {
                    if (property.IsIgnored)
                    {
                        continue;
                    }

                    DocAppender.AppendConstantModuleDoc(sb, property, GetPropertyName(property), GetPropertyType(property));
                    sb.Append(string.Format("export var {0}: {1} = {2};", GetPropertyName(property), GetPropertyType(property), GetPropertyConstantValue(property)));
                    sb.AppendLine();
                }
            }
            sb.AppendLine("}");

            GeneratedClasses.Add(classModel);
        }
コード例 #13
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);
        }
コード例 #14
0
        public void WhenCreateFromClass_NameIsSetToTypeNameReturnedByTypeResolver()
        {
            var classResolvedType = this.SetupTypeResolverFor <ClassWithoutAttribute>();

            var @class = TsClass.CreateFrom <ClassWithoutAttribute>(_typeResolverMock.Object, _configurationProviderMock.Object);

            Assert.Same(classResolvedType, @class.Name);
        }
コード例 #15
0
        public void WhenInitialized_ConstantsHaveCorrectValues()
        {
            var target = new TsClass(typeof(Person));

            var maxAddresses = target.Constants.Single(o => o.MemberInfo == typeof(Person).GetField("MaxAddresses"));

            Assert.Equal(Person.MaxAddresses, maxAddresses.ConstantValue);
        }
コード例 #16
0
        public void WhenCreateFromClassWitoutInterfaces_InterfacesCollectionIsEmpty()
        {
            var classResolvedType = this.SetupTypeResolverFor <BaseClass>();

            var @class = TsClass.CreateFrom <DerivedClass>(_typeResolverMock.Object, _configurationProviderMock.Object);

            Assert.Empty(@class.Interfaces);
        }
コード例 #17
0
        public void WhenCreateFromClassWithoutSpecificBaseClass_BaseTypeIsNull()
        {
            var baseClassResolvedType   = this.SetupTypeResolverFor <BaseClass>();
            var objectClassResolvedType = this.SetupTypeResolverFor <object>();

            var @class = TsClass.CreateFrom <BaseClass>(_typeResolverMock.Object, _configurationProviderMock.Object);

            Assert.Null(@class.BaseType);
        }
コード例 #18
0
        public void WhenModuleIsSet_ClassIsAddedToModule()
        {
            var module = new TsModule("Tests");
            var target = new TsClass(typeof(Address));

            target.Module = module;

            Assert.Contains(target, module.Classes);
        }
コード例 #19
0
        public void WhenCreateFromClassWithBaseClass_BaseTypeIsSetToTypeNameReturnedByTypeResolver()
        {
            var classResolvedType     = this.SetupTypeResolverFor <DerivedClass>();
            var baseClassResolvedType = this.SetupTypeResolverFor <BaseClass>();

            var @class = TsClass.CreateFrom <DerivedClass>(_typeResolverMock.Object, _configurationProviderMock.Object);

            Assert.Same(baseClassResolvedType, @class.BaseType);
        }
コード例 #20
0
        public void WhenInitializedWithClassThatHasBaseClass_OnlyPropertiesDefinedInDerivedClassAreCreated()
        {
            var target = new TsClass(typeof(Employee));

            Assert.Single(target.Properties.Where(o => o.MemberInfo == typeof(Employee).GetProperty("Salary")));

            Assert.Empty(target.Properties.Where(o => o.MemberInfo == typeof(Employee).GetProperty("Street")));
            Assert.Empty(target.Properties.Where(o => o.MemberInfo == typeof(Employee).GetProperty("Street")));
        }
コード例 #21
0
        public void WhenCreateFromClassWithInterfaces_InterfacesCollectionDoesNotContainsInterfacesNotResolvedByTypeResolver()
        {
            var classResolvedType      = this.SetupTypeResolverFor <ClassWithIntefaces>();
            var interface1ResolvedType = this.SetupTypeResolverFor <IInterfaceForClassWithInterfaces>();

            var @class = TsClass.CreateFrom <ClassWithIntefaces>(_typeResolverMock.Object, _configurationProviderMock.Object);

            Assert.Equal(1, @class.Interfaces.Count);
            Assert.Contains(interface1ResolvedType, @class.Interfaces);
        }
コード例 #22
0
        private string GetNestedClassesString(TsClass netClass)
        {
            var nestedClasses = string.Join(_config.NewLines(2), netClass.NestedClasses.Select(WriteType));

            if (!string.IsNullOrWhiteSpace(nestedClasses))
            {
                nestedClasses = _config.NewLines(2) + nestedClasses;
            }
            return(nestedClasses);
        }
コード例 #23
0
ファイル: TsTypeGenerator.cs プロジェクト: Jake91/TypeSharp
        private void PopulateProperties(TsClass type, IReadOnlyDictionary <Type, TsTypeDefinitionBase> typeDict)
        {
            var properties = this._propertyProvider.GetProperties(type.CSharpType);

            foreach (var propertyInfo in properties)
            {
                var propertyType = GetTsType(propertyInfo.PropertyType, typeDict);
                type.Properties.Add(this._propertyProvider.CreateClassProperty(propertyInfo, propertyType));
            }
        }
コード例 #24
0
        public void WhenInitialized_PropertiesCollectionIsEmpty()
        {
            var typeName = new TsBasicType()
            {
                Context = typeof(ClassWithoutAttribute), TypeName = "ClassWithoutAttribute"
            };
            var sut = new TsClass(typeName);

            Assert.Empty(sut.Properties);
        }
コード例 #25
0
        public void WhenInitializedWithClassWithEnum_PropertiesCreated()
        {
            var target = new TsClass(typeof(Item));

            Assert.Single(target.Properties.Where(o => o.MemberInfo == typeof(Item).GetProperty("Type")));
            Assert.Single(target.Properties.Where(o => o.MemberInfo == typeof(Item).GetProperty("Id")));
            Assert.Single(target.Properties.Where(o => o.MemberInfo == typeof(Item).GetProperty("Name")));

            Assert.Null(target.BaseType);
        }
コード例 #26
0
        public void WhenInitialized_NameIsSet()
        {
            var typeName = new TsBasicType()
            {
                Context = typeof(ClassWithoutAttribute), TypeName = "ClassWithoutAttribute"
            };
            var sut = new TsClass(typeName);

            Assert.Same(typeName, sut.Name);
        }
コード例 #27
0
        /// <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);
        }
コード例 #28
0
        public void WhenCreateFromClassWithProperties_PropertiesCollectionContainsProperty()
        {
            this.SetupTypeResolverFor <ClassWithProperty>();
            this.SetupTypeResolverFor <int>();
            var propertyConfiguration = this.SetupConfigurationForMember <ClassWithProperty>("Property");

            var @class = TsClass.CreateFrom <ClassWithProperty>(_typeResolverMock.Object, _configurationProviderMock.Object);

            Assert.Equal(1, @class.Properties.Count);
            Assert.Equal(propertyConfiguration.Name, @class.Properties[0].Name);
        }
コード例 #29
0
        public void WhenModuleIsSetToOtherModule_ClassIsRemovedFromOriginalModule()
        {
            var originalModule = new TsModule("Tests.Original");
            var module         = new TsModule("Tests");
            var target         = new TsClass(typeof(Address));

            target.Module = originalModule;
            target.Module = module;

            Assert.DoesNotContain(target, originalModule.Classes);
        }
コード例 #30
0
 protected override void AppendClassDefinition(TsClass classModel, ScriptBuilder sb, TsGeneratorOutput generatorOutput)
 {
     if (classModel.Type.IsInterface && CsharpTypeInfoProvider.ExposedInterfaces.Contains(classModel.Type))
     {
         AppendInterfaceDef(classModel, sb, generatorOutput);
     }
     else
     {
         AppendClassDef(classModel, sb, generatorOutput);
     }
 }