예제 #1
0
        protected virtual TsInterface Rewrite(CsClass csClass)
        {
            var properties = csClass.Members
                             .Where(x => !x.IsStatic)
                             .OfType <CsProperty>()
                             .Select(Rewrite)
                             .ToArray();

            var fields = csClass.Members
                         .OfType <CsField>()
                         .Select(Rewrite)
                         .ToArray();

            var baseTypes = new List <Type>();

            if (csClass.CsType.OriginalType.BaseType != typeof(object))
            {
                baseTypes.Add(csClass.CsType.OriginalType.BaseType);
            }

            baseTypes.AddRange(GetInterfaces(csClass.CsType.OriginalType, false));

            return(new TsInterface
            {
                CsType = csClass.CsType,
                Name = csClass.Name,
                ExportKind = TsExportKind.Named,
                TypeParameters = csClass.TypeParameters,
                Base = baseTypes.Select(x => TsType.From(new CsType(x))).ToArray(),
                Properties = properties.Concat(fields).ToArray()
            });
        }
예제 #2
0
        private static string TypeFormatter(TsType tsType, ITsTypeFormatter f)
        {
            TsClass tsClass = (TsClass)tsType;

            //Prefix classname with I
            return("I" + tsClass.Name);
        }
예제 #3
0
        /// <summary>
        /// Creates a TsCollection from TsType
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private TsCollection CreateCollectionType(TsType type)
        {
            var resolved = new TsCollection(type.Type);

            resolved.ItemsType = this.ResolveType(resolved.ItemsType, false);
            return(resolved);
        }
예제 #4
0
        protected virtual TsInterface Rewrite(CsClass csClass)
        {
            var properties = csClass.Members
                             .Where(x => !x.IsStatic)
                             .OfType <CsProperty>()
                             .Select(Rewrite)
                             .ToArray();

            var fields = csClass.Members
                         .OfType <CsField>()
                         .Select(Rewrite)
                         .ToArray();

            return(new TsInterface
            {
                CsType = csClass.CsType,
                Name = csClass.Name,
                ExportKind = TsExportKind.Named,
                TypeParameters = csClass.TypeParameters,
                Base = csClass.CsType.OriginalType.BaseType == typeof(object)
                                  ? Array.Empty <TsType>()
                                  : new[]
                {
                    TsType.From(new CsType(csClass.CsType.OriginalType
                                           .BaseType))
                },
                Properties = properties.Concat(fields).ToArray()
            });
        }
예제 #5
0
        public virtual string WriteType(TsType netType)
        {
            var @class = netType as TsClass;

            if (@class != null)
            {
                return(WriteClass(@class));
            }

            var @enum = netType as TsEnum;

            if (@enum != null)
            {
                return(WriteEnum(@enum));
            }

            var @interface = netType as TsInterface;

            if (@interface != null)
            {
                return(WriteInterface(@interface));
            }

            throw new NotImplementedException();
        }
예제 #6
0
        /// <summary>
        /// Creates a TsCollection from TsType
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private TsCollection CreateCollectionType(TsType type, TsPropertyVisibilityFormatter propertyVisibilityFormatter)
        {
            var resolved = new TsCollection(type.Type, propertyVisibilityFormatter);

            resolved.ItemsType = this.ResolveType(resolved.ItemsType, propertyVisibilityFormatter, false);
            return(resolved);
        }
        /// <summary>
        /// Gets fully qualified name of the type
        /// </summary>
        /// <param name="type">The type to get name of</param>
        /// <returns>Fully qualified name of the type</returns>
        public string GetFullyQualifiedTypeName(TsType type)
        {
            var moduleName = string.Empty;

            var member = type as TsModuleMember;

            if (member != null && !Options.TypeConverters.IsConverterRegistered(member.Type))
            {
                var memberType = member;
                moduleName = memberType.Module != null?GetModuleName(memberType.Module) : string.Empty;
            }
            else if (type is TsCollection)
            {
                var collectionType = (TsCollection)type;
                moduleName = GetCollectionModuleName(collectionType, moduleName);
            }

            if (type.Type.IsGenericParameter)
            {
                return(GetTypeName(type));
            }

            if (string.IsNullOrEmpty(moduleName))
            {
                return(GetTypeName(type));
            }

            var name = moduleName + "." + GetTypeName(type);

            return(name);
        }
예제 #8
0
 /// <summary>
 /// Adds all classes annotated with the TsClassAttribute from an assembly to the model.
 /// </summary>
 /// <param name="assembly">The assembly with classes to add</param>
 public void Add(Assembly assembly)
 {
     try
     {
         foreach (var type in assembly.GetTypes().Where(t =>
                                                        (t.GetCustomAttribute <TsClassAttribute>(false) != null &&
                                                         TsType.GetTypeFamily(t) == TsTypeFamily.Class) ||
                                                        (t.GetCustomAttribute <TsEnumAttribute>(false) != null &&
                                                         TsType.GetTypeFamily(t) == TsTypeFamily.Enum) ||
                                                        (t.GetCustomAttribute <TsInterfaceAttribute>(false) != null &&
                                                         TsType.GetTypeFamily(t) == TsTypeFamily.Class)
                                                        ))
         {
             Add(type);
         }
     }
     catch (ReflectionTypeLoadException e)
     {
         var availableTypes = e.Types.Where(t =>
                                            t != null &&
                                            t.GetCustomAttribute <TsClassAttribute>(false) != null &&
                                            TsType.GetTypeFamily(t) == TsTypeFamily.Class ||
                                            t.GetCustomAttribute <TsEnumAttribute>(false) != null &&
                                            TsType.GetTypeFamily(t) == TsTypeFamily.Enum ||
                                            t.GetCustomAttribute <TsInterfaceAttribute>(false) != null &&
                                            TsType.GetTypeFamily(t) == TsTypeFamily.Class);
         foreach (var type in availableTypes)
         {
             Add(type);
         }
     }
 }
예제 #9
0
        protected virtual TsTypeMember?Rewrite(CsTypeMember csTypeMember)
        {
            switch (csTypeMember)
            {
            case CsProperty csProperty:
                var forceNullable = csProperty.Attributes.Any(a => a.Name.Contains("CanBeNull")) ||
                                    csProperty.IsNullable;
                return(new TsPropertySignature
                {
                    Name = csProperty.Name,
                    Type = TsType.From(csProperty.Type,
                                       forceNullable)
                });

            case CsField csField:
                if (csField.Value == null)
                {
                    return(null);
                }

                return(new TsPropertySignature
                {
                    Name = csField.Name,
                    Type = TsType.FromLiteral(csField.Value)
                });

            default:
                throw new ArgumentOutOfRangeException(nameof(csTypeMember),
                                                      csTypeMember.GetType().Name, null);
            }
        }
예제 #10
0
        /// <summary>
        /// Gets fully qualified name of the type
        /// </summary>
        /// <param name="type">The type to get name of</param>
        /// <returns>Fully qualified name of the type</returns>
        public string GetFullyQualifiedTypeName(TsType type)
        {
            var moduleName = string.Empty;

            if (type as TsModuleMember != null && !_typeConvertors.IsConvertorRegistered(type.Type))
            {
                var memberType = (TsModuleMember)type;
                moduleName = memberType.Module != null?GetModuleName(memberType.Module) : string.Empty;
            }
            else if (type as TsCollection != null)
            {
                var collectionType = (TsCollection)type;
                moduleName = GetCollectionModuleName(collectionType, moduleName);
            }

            if (type.Type.IsGenericParameter)
            {
                return(this.GetTypeName(type));
            }
            if (!string.IsNullOrEmpty(moduleName))
            {
                var name = moduleName + "." + this.GetTypeName(type);
                return(name);
            }

            return(this.GetTypeName(type));
        }
예제 #11
0
        public TsTypeAttribute(TsType type)
        {
            switch (type)
            {
            case TsType.Object:
                TypeName = "Object";
                break;

            case TsType.Boolean:
                TypeName = "boolean";
                break;

            case TsType.String:
                TypeName = "string";
                break;

            case TsType.Number:
                TypeName = "number";
                break;

            case TsType.Date:
                TypeName = "Date";
                break;

            case TsType.Any:
                TypeName = "any";
                break;
            }
        }
예제 #12
0
        private string GenerateTypeName(TsType type)
        {
            var tsClass = (TsClass)type;

            var name = ClientTypescriptGenerator.TypeRenames.ContainsKey(tsClass.Name)
                                ? ClientTypescriptGenerator.TypeRenames[tsClass.Name]
                                : tsClass.Name;

            if (type.Type == typeof(HistogramOrder))
            {
                return("HistogramOrder");
            }

            if (InterfaceRegex.IsMatch(name) && !CsharpTypeInfoProvider.ExposedInterfaces.Contains(type.Type))
            {
                name = name.Substring(1);
            }

            if (!tsClass.GenericArguments.Any())
            {
                return(name);
            }

            return(name + "<" + string.Join(", ", tsClass.GenericArguments.Select(WriteArrayIfCollection)) + ">");
        }
예제 #13
0
 public TsProperty(string name, string type, TsType tsType, object value, bool isStatic)
 {
     Name     = name;
     Type     = type;
     TsType   = tsType;
     Value    = value;
     IsStatic = isStatic;
 }
예제 #14
0
        public void WhenInitilized_ClrTypeIsSet()
        {
            var type = typeof(string);

            var target = new TsType(type);

            Assert.Equal(type, target.Type);
        }
예제 #15
0
 public static TsIndexSignature ByNumber(TsType valueType)
 {
     return(new TsIndexSignature
     {
         IndexType = TsPredefinedType.Number(),
         ValueType = valueType
     });
 }
예제 #16
0
 public static TsIndexSignature ByString(TsType valueType)
 {
     return(new TsIndexSignature
     {
         IndexType = TsPredefinedType.String(),
         ValueType = valueType
     });
 }
예제 #17
0
        /// <summary>
        /// Gets name of the type in the TypeScript
        /// </summary>
        /// <param name="type">The type to get name of</param>
        /// <returns>name of the type</returns>
        public string GetTypeName(TsType type)
        {
            if (_typeConvertors.IsConvertorRegistered(type.Type))
            {
                return(_typeConvertors.ConvertType(type.Type));
            }

            return(_typeFormatters.FormatType(type));
        }
 /// <summary>
 /// Converts the specific type to it's string representation using a formatter registered for the type
 /// </summary>
 /// <param name="type">The type to format.</param>
 /// <returns>The string representation of the type.</returns>
 public string FormatType(TsType type)
 {
     if (_formatters.ContainsKey(type.GetType()))
     {
         return _formatters[type.GetType()](type, this);
     }
     else
     {
         return "any";
     }
 }
예제 #19
0
        public virtual string WriteTypeName(TsType netType)
        {
            var arrString = netType.IsArray ? "[]" : "";

            if ((netType.GenericParameters?.Count ?? 0) == 0)
            {
                return(netType.Name + arrString);
            }

            //render generic parameters
            return($"{netType.Name}<{string.Join(",", netType.GenericParameters.Select(gp => gp.Name))}>" + arrString);
        }
예제 #20
0
 private static TsTypeMember[] GetProperties(CsClass csClass)
 {
     return(csClass.Members
            .OfType <CsProperty>()
            .Select(p => new TsPropertySignature
     {
         Name = p.Name,
         Type = TsType.From(p.Type),
         Optional = false
     })
            .ToArray());
 }
예제 #21
0
 private static TsFunction RewriteMethod(CsMethod method)
 {
     return(new TsFunction
     {
         Name = method.Name,
         ExportKind = TsExportKind.Named,
         ReturnType = TsType.From(method.ReturnType),
         Parameters = method.Parameters
                      .Select(x => new TsFunctionParameter
         {
             Name = x.Name, Type = TsType.From(x.Type)
         })
                      .ToArray(),
         Body = "// some body"
     });
 }
예제 #22
0
 string GetAssignmentExpression(TsType type, string sourceExpression)
 {
     if (type is TsMappedType)
     {
         return(string.Format(((TsMappedType)type).AssignmentTemplate, sourceExpression));
     }
     if (type is TsTypeWithProperties)
     {
         return(type.TsTypeReferenceName + ".fromJSON(" + sourceExpression + ")");
     }
     if (type is TsCollection)
     {
         return(sourceExpression + " === null ? null : " + sourceExpression + ".map(o => " + GetAssignmentExpression(((TsCollection)type).TsItemType, "o") + ")");
     }
     return(sourceExpression);
 }
예제 #23
0
        private string WriteArrayIfCollection(TsType a)
        {
            var fullyQualifiedTypeName = _scriptGenerator.GetFullyQualifiedTypeName(a);

            if (typeof(IIsADictionary).IsAssignableFrom(a.Type))
            {
                return(fullyQualifiedTypeName);
            }
            if (a is TsCollection)
            {
            }

            return(a is TsCollection && !fullyQualifiedTypeName.StartsWith("Dictionary<")
                                ? fullyQualifiedTypeName + "[]"
                                : fullyQualifiedTypeName);
        }
예제 #24
0
 protected virtual TsInterface Rewrite(CsInterface csInterface)
 {
     return(new TsInterface
     {
         CsType = csInterface.CsType,
         Name = csInterface.Name,
         ExportKind = TsExportKind.Named,
         TypeParameters = csInterface.TypeParameters,
         Base = GetInterfaces(csInterface.CsType.OriginalType, false)
                .Select(x => TsType.From(new CsType(x)))
                .ToArray(),
         Properties = csInterface.Members
                      .Where(x => !x.IsStatic)
                      .OfType <CsProperty>()
                      .Select(Rewrite)
                      .ToArray()
     });
 }
예제 #25
0
        /// <summary>
        /// Resolves TsType to the more specialized type.
        /// </summary>
        /// <param name="toResolve">The type to resolve.</param>
        /// <returns></returns>
        private TsType ResolveType(TsType toResolve, TsPropertyVisibilityFormatter propertyVisibilityFormatter, bool useOpenGenericDefinition = true)
        {
            if (!(toResolve is TsType))
            {
                return(toResolve);
            }

            if (_knownTypes.ContainsKey(toResolve.Type))
            {
                return(_knownTypes[toResolve.Type]);
            }
            else if (toResolve.Type.IsGenericType && useOpenGenericDefinition)
            {
                // We stored its open type definition instead
                TsType openType = null;
                if (_knownTypes.TryGetValue(toResolve.Type.GetGenericTypeDefinition(), out openType))
                {
                    return(openType);
                }
            }
            else if (toResolve.Type.IsGenericType)
            {
                var genericType = TsType.Create(toResolve.Type, propertyVisibilityFormatter);
                _knownTypes[toResolve.Type] = genericType;
                return(genericType);
            }

            var    typeFamily = TsType.GetTypeFamily(toResolve.Type);
            TsType type       = null;

            switch (typeFamily)
            {
            case TsTypeFamily.System: type = new TsSystemType(toResolve.Type); break;

            case TsTypeFamily.Collection: type = this.CreateCollectionType(toResolve, propertyVisibilityFormatter); break;

            case TsTypeFamily.Enum: type = new TsEnum(toResolve.Type); break;

            default: type = TsType.Any; break;
            }

            _knownTypes[toResolve.Type] = type;
            return(type);
        }
예제 #26
0
        /// <summary>
        /// Sbusta un file timestampato, estraendo l'eventuale file firmato (pkcs) o il payload nel caso non fosse firmato.
        /// </summary>
        /// <param name="fileContents">bytearray del file tsd o m7m</param>
        /// <returns></returns>
        public static byte[] sbustaFileTimstamped(byte[] fileContents)
        {
            TsType tipo = getFileType(fileContents);

            if (tipo == TsType.TSD)
            {
                PKCS_Utils.tsd tsd = new PKCS_Utils.tsd();
                tsd.explode(fileContents);
                fileContents = tsd.Data.Content;
            }

            if (tipo == TsType.M7M)
            {
                PKCS_Utils.m7m m7m = new PKCS_Utils.m7m();
                m7m.explode(fileContents);
                fileContents = m7m.Data.Content;
            }
            return(fileContents);
        }
예제 #27
0
        /// <summary>
        /// Sbusta un file timstamped e firmato, fino arrivare al file originale (payload)
        /// </summary>
        /// <param name="fileContents"></param>
        /// <returns>bytearray del file tsd, m7m, o p7m</returns>
        public static byte[] sbustaFileFirmato(byte[] fileContents)
        {
            //controlla se è base64
            String strfileContents = System.Text.ASCIIEncoding.ASCII.GetString(fileContents);

            if (IsBase64Encoded(strfileContents))
            {
                fileContents = Convert.FromBase64String(strfileContents);
            }

            TsType tipo = getFileType(fileContents);

            if (tipo == TsType.PKCS)
            {
                CmsSignedData cms = new CmsSignedData(fileContents);
                fileContents = (byte[])cms.SignedContent.GetContent();
            }

            if (tipo == TsType.TSD)
            {
                PKCS_Utils.tsd tsd = new PKCS_Utils.tsd();
                tsd.explode(fileContents);
                fileContents = tsd.Data.Content;
            }

            if (tipo == TsType.M7M)
            {
                PKCS_Utils.m7m m7m = new PKCS_Utils.m7m();
                m7m.explode(fileContents);
                fileContents = m7m.Data.Content;
            }

            //non conosco il tipo, esco
            if (tipo == TsType.UNKNOWN)
            {
                return(fileContents);
            }


            //ricorsione per arrivare al singolo documento
            return(sbustaFileFirmato(fileContents));
        }
예제 #28
0
        public static TsFile[] Convert(IEnumerable <Type> types,
                                       IEnumerable <ICoder> coders,
                                       ICoder defaultCoder = null,
                                       IEnumerable <ICustomTypeConverter> customTypeConverters =
                                       null)
        {
            if (customTypeConverters != null)
            {
                TsType.RegisterCustomTypeConverters(customTypeConverters);
            }

            var csDeclarations = CsDeclarationFactory.Create(types).ToArray();

            var writtenTsFiles = coders.SelectMany(coder => coder.Rewrite(csDeclarations))
                                 .Where(x => x.Declarations.Any())
                                 .ToArray();

            return(FixBuild(writtenTsFiles,
                            defaultCoder ?? new DefaultCoder(),
                            csDeclarations));
        }
예제 #29
0
            public override void WriteTypeContent(StringBuilder result, TsType type)
            {
                if (type.Name.EndsWith("Request") || type.Name.EndsWith("Command"))
                {
                    var controllerStart = type.TsModule.Name.Replace("Scripts.Data.", "").Replace(".", "_");
                    var controllerEnd   = type.Name;
                    if (controllerEnd.EndsWith("Request"))
                    {
                        controllerEnd = controllerEnd.Substring(0, controllerEnd.Length - "Request".Length);
                    }
                    if (controllerEnd.EndsWith("Command"))
                    {
                        controllerEnd = controllerEnd.Substring(0, controllerEnd.Length - "Command".Length);
                    }

                    if (type.Type != "interface")
                    {
                        result.Append(string.Format("        path='{0}_{1}';\r\n", controllerStart, controllerEnd));
                    }
                }
                base.WriteTypeContent(result, type);
            }
예제 #30
0
        private static IEnumerable <TsType> Unwrap(TsType tsType)
        {
            switch (tsType)
            {
            case TsUnionType tsUnionType:
                return(tsUnionType.Types.SelectMany(Unwrap));

            case TsArrayType tsArrayType:
                return(Unwrap(tsArrayType.ElementType));

            case TsObjectType tsObjectType:
                return(tsObjectType.Members
                       .Select(UnwrapTsTypeMember)
                       .SelectMany(Unwrap));

            case TsTypeReference tsTypeReference:
                return(tsTypeReference.TypeArguments
                       .SelectMany(Unwrap)
                       .Append(tsTypeReference));

            case TsEnumLiteralType tsEnumLiteralType:
                return(new[] { tsEnumLiteralType.EnumType });

            case TsNull _:
            case TsPredefinedType _:
            case TsStringLiteralType _:
            case TsBoolLiteralType _:
            case TsIntLiteralType _:
                return(new[]
                {
                    tsType
                });

            default:
                throw new ArgumentOutOfRangeException(nameof(tsType),
                                                      tsType.GetType().Name,
                                                      null);
            }
        }