Example #1
0
        /// <summary>
        /// Determines whether the specified model type is structurally equal to this object.
        /// </summary>
        /// <param name="other">The object to compare with this object.</param>
        /// <returns>true if the specified object is functionally equal to this object; otherwise, false.</returns>
        public override bool StructurallyEquals(IModelType other)
        {
            if (ReferenceEquals(other as SequenceType, null))
            {
                return false;
            }

            return base.StructurallyEquals(other) && 
                ElementType.StructurallyEquals((other as SequenceType).ElementType);
        }
Example #2
0
        /// <summary>
        /// Determines whether the specified model type is structurally equal to this object.
        /// </summary>
        /// <param name="other">The object to compare with this object.</param>
        /// <returns>true if the specified object is functionally equal to this object; otherwise, false.</returns>
        public override bool StructurallyEquals(IModelType other)
        {
            if (ReferenceEquals(other as DictionaryType, null))
            {
                return false;
            }

            return base.StructurallyEquals(other) && 
                   ValueType.StructurallyEquals((other as DictionaryType).ValueType) &&
                   SupportsAdditionalProperties == (other as DictionaryType).SupportsAdditionalProperties;
        }
Example #3
0
        public override string EscapeDefaultValue(string defaultValue, IModelType type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            var primaryType = type as PrimaryType;
            if (defaultValue != null)
            {
                if (type is CompositeType)
                {
                    return "new " + type.Name + "()";
                }
                if (primaryType != null)
                {
                    if (primaryType.KnownPrimaryType == KnownPrimaryType.String)
                    {
                        return Instance.QuoteValue(defaultValue);
                    }
                    if (primaryType.KnownPrimaryType == KnownPrimaryType.Boolean)
                    {
                        return defaultValue.ToLowerInvariant();
                    }
                    if ((primaryType.KnownPrimaryType == KnownPrimaryType.Date) ||
                        (primaryType.KnownPrimaryType == KnownPrimaryType.DateTime) ||
                        (primaryType.KnownPrimaryType == KnownPrimaryType.DateTimeRfc1123) ||
                        (primaryType.KnownPrimaryType == KnownPrimaryType.TimeSpan) ||
                        (primaryType.KnownPrimaryType == KnownPrimaryType.ByteArray) ||
                        (primaryType.KnownPrimaryType == KnownPrimaryType.Base64Url) ||
                        (primaryType.KnownPrimaryType == KnownPrimaryType.UnixTime))
                    {
                        return
                            $"Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<{primaryType.Name}>"+
                            $"({Instance.QuoteValue($"\"{defaultValue}\"")}, this.Client.SerializationSettings)";
                    }
                }
            }
            return defaultValue;
        }
Example #4
0
 /// <summary>
 ///     Returns language specific type reference name.
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 public virtual IModelType NormalizeTypeReference(IModelType type)
 {
     return type;
 }
        private bool TryBuildResponse(string methodName, HttpStatusCode responseStatusCode,
            OperationResponse response, Method method, List<Stack<IModelType>> types, IModelType headerType)
        {
            bool handled = false;
            IModelType serviceType;
            if (SwaggerOperationProducesJson())
            {
                if (TryBuildResponseBody(methodName, response,
                    s => GenerateResponseObjectName(s, responseStatusCode), out serviceType))
                {
                    method.Responses[responseStatusCode] = new Response(serviceType, headerType);
                    BuildMethodReturnTypeStack(serviceType, types);
                    handled = true;
                }
            }

            return handled;
        }
 /// <summary>
 /// Returns the ModelType name expressed as a nullable type (for classes, nothing different, for value types, append a '?'
 /// </summary>
 /// <param name="modelType">The ModelType to return as nullable</param>
 /// <returns>The ModelType name expressed as a nullable type</returns>
 public static string AsNullableType(this IModelType modelType) => modelType.IsValueType() ? $"{modelType.Name}?" : modelType.DeclarationName;
Example #7
0
 /// <summary>
 /// Returns true if the type is a PrimaryType with KnownPrimaryType matching typeToMatch.
 /// </summary>
 /// <param name="type"></param>
 /// <param name="typeToMatch"></param>
 /// <returns></returns>
 public static bool IsPrimaryType(this IModelType type, KnownPrimaryType typeToMatch) => typeToMatch == (type as PrimaryType)?.KnownPrimaryType;
Example #8
0
 /// <summary>
 /// Initializes a new instance of Response.
 /// </summary>
 /// <param name="body">Body type.</param>
 /// <param name="headers">Headers type.</param>
 public Response(IModelType body, IModelType headers) 
 {
     Body = body;
     Headers = headers;
 }
        /// <summary>
        /// Internal method for generating Yard-compatible representation of given type.
        /// </summary>
        /// <param name="type">The type doc needs to be generated for.</param>
        /// <returns>Doc in form of string.</returns>
        private static string PrepareTypeForDocRecursively(IModelType type)
        {
            var sequenceType = type as SequenceType;
            var compositeType = type as CompositeType;
            var enumType = type as EnumType;
            var dictionaryType = type as DictionaryType;
            var primaryType = type as PrimaryType;

            if (primaryType != null)
            {
                if (primaryType.KnownPrimaryType == KnownPrimaryType.String)
                {
                    return "String";
                }

                if (primaryType.KnownPrimaryType == KnownPrimaryType.Int || primaryType.KnownPrimaryType == KnownPrimaryType.Long)
                {
                    return "Integer";
                }

                if (primaryType.KnownPrimaryType == KnownPrimaryType.Boolean)
                {
                    return "Boolean";
                }

                if (primaryType.KnownPrimaryType == KnownPrimaryType.Double)
                {
                    return "Float";
                }

                if (primaryType.KnownPrimaryType == KnownPrimaryType.Date)
                {
                    return "Date";
                }

                if (primaryType.KnownPrimaryType == KnownPrimaryType.DateTime)
                {
                    return "DateTime";
                }

                if (primaryType.KnownPrimaryType == KnownPrimaryType.DateTimeRfc1123)
                {
                    return "DateTime";
                }

                if (primaryType.KnownPrimaryType == KnownPrimaryType.ByteArray)
                {
                    return "Array<Integer>";
                }

                if (primaryType.KnownPrimaryType == KnownPrimaryType.TimeSpan)
                {
                    return "Duration"; //TODO: Is this a real Ruby type...?
                }
            }

            if (compositeType != null)
            {
                return compositeType.Name;
            }

            if (enumType != null)
            {
                return ((EnumTypeRb)enumType).ModuleName;
            }

            if (sequenceType != null)
            {
                string internalString = PrepareTypeForDocRecursively(sequenceType.ElementType);

                if (!string.IsNullOrEmpty(internalString))
                {
                    return $"Array<{internalString}>";
                }

                return string.Empty;
            }

            if (dictionaryType != null)
            {
                string internalString = PrepareTypeForDocRecursively(dictionaryType.ValueType);

                if (!string.IsNullOrEmpty(internalString))
                {
                    return $"Hash{{String => {internalString}}}";
                }

                return string.Empty;
            }

            return string.Empty;
        }
Example #10
0
 public static bool ShouldBeSyntheticType(this IModelType type)
 {
     return(type is PrimaryType || type is SequenceType || type is DictionaryType || type is EnumType);
 }
Example #11
0
        public string DeserializeResponse(IModelType type, string valueReference = "result", string responseVariable = "parsedResponse")
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            var builder = new IndentedStringBuilder("  ");
            builder.AppendLine("var {0} = null;", responseVariable)
                   .AppendLine("try {")
                   .Indent()
                     .AppendLine("{0} = JSON.parse(responseBody);", responseVariable)
                     .AppendLine("{0} = JSON.parse(responseBody);", valueReference);
            var deserializeBody = GetDeserializationString(type, valueReference, responseVariable);
            if (!string.IsNullOrWhiteSpace(deserializeBody))
            {
                builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", responseVariable)
                         .Indent()
                         .AppendLine(deserializeBody)
                       .Outdent()
                       .AppendLine("}");
            }
            builder.Outdent()
                   .AppendLine("} catch (error) {")
                     .Indent()
                     .AppendLine(DeserializationError)
                   .Outdent()
                   .AppendLine("}");

            return builder.ToString();
        }
Example #12
0
 public string GetDeserializationString(IModelType type, string valueReference = "result", string responseVariable = "parsedResponse")
 {
     var builder = new IndentedStringBuilder("  ");
     if (type is CompositeType)
     {
         builder.AppendLine("var resultMapper = new client.models['{0}']().mapper();", type.Name);
     }
     else
     {
         builder.AppendLine("var resultMapper = {{{0}}};", type.ConstructMapper(responseVariable, null, false, false));
     }
     builder.AppendLine("{1} = client.deserialize(resultMapper, {0}, '{1}');", responseVariable, valueReference);
     return builder.ToString();
 }
Example #13
0
        /// <summary>
        /// Determines whether the specified model type is structurally equal to this object.
        /// </summary>
        /// <param name="other">The object to compare with this object.</param>
        /// <returns>true if the specified object is functionally equal to this object; otherwise, false.</returns>
        public virtual bool StructurallyEquals(IModelType other)
        {
            if (ReferenceEquals(other, null))
            {
                return false;
            }

            return GetType() == other.GetType() && Name.Equals(other.Name);
        }
Example #14
0
 /// <summary>
 /// Returns deserialization settings reference.
 /// </summary>
 /// <param name="deserializationType"></param>
 /// <returns></returns>
 public string GetDeserializationSettingsReference(IModelType deserializationType)
 {
     if (deserializationType.IsOrContainsPrimaryType(KnownPrimaryType.Date))
     {
         return "new Microsoft.Rest.Serialization.DateJsonConverter()";
     }
     else if (deserializationType.IsOrContainsPrimaryType(KnownPrimaryType.Base64Url))
     {
         return "new Microsoft.Rest.Serialization.Base64UrlJsonConverter()";
     }
     else if (deserializationType.IsOrContainsPrimaryType(KnownPrimaryType.UnixTime))
     {
         return "new Microsoft.Rest.Serialization.UnixTimeJsonConverter()";
     }
     return ClientReference + ".DeserializationSettings";
 }
Example #15
0
 /// <summary>
 ///     Returns language specific type declaration name.
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 public virtual IModelType NormalizeTypeDeclaration(IModelType type)
 {
     return type;
 }
Example #16
0
 /// <summary>
 /// Returns true if the specified type is user-defined.
 /// </summary>
 public static bool IsUserDefinedType(this IModelType type)
 {
     return((type is CompositeTypeGo) || (type is EnumTypeGo etg && etg.IsNamed));
 }
Example #17
0
        public virtual string GetExceptionNameIfExist(IModelType type, bool needsQuote)
        {
            CompositeType compType = type as CompositeType;
            if (compType != null)
            {
                if (ErrorTypes.Contains(compType))
                {
                    if (needsQuote)
                    {
                        return ", '" + compType.GetExceptionDefineType() + "'";
                    }
                    return ", " + compType.GetExceptionDefineType();
                }
            }

            return string.Empty;
        }
Example #18
0
        /// <summary>
        /// Determines whether the specified model type is structurally equal to this object.
        /// </summary>
        /// <param name="other">The object to compare with this object.</param>
        /// <returns>true if the specified object is functionally equal to this object; otherwise, false.</returns>
        public override bool StructurallyEquals(IModelType other)
        {
            if (ReferenceEquals(other as PrimaryType, null))
            {
                return false;
            }

            return base.StructurallyEquals(other) && 
                KnownPrimaryType == (other as PrimaryType).KnownPrimaryType &&
                Format == (other as PrimaryType).Format;
        }
Example #19
0
 public string GetDocumentationType(IModelType type)
 {
     return (type as IExtendedModelTypePy)?.TypeDocumentation ?? PythonConstants.None;
 }
Example #20
0
        public override string EscapeDefaultValue(string defaultValue, IModelType type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            PrimaryType primaryType = type as PrimaryType;
            if (defaultValue != null && primaryType != null)
            {
                if (primaryType.KnownPrimaryType == KnownPrimaryType.String)
                {
                    return QuoteValue(defaultValue, quoteChar: "'");
                }
                else if (primaryType.KnownPrimaryType == KnownPrimaryType.Boolean)
                {
                    return defaultValue.ToLowerInvariant();
                }
                else
                {
                    if (primaryType.KnownPrimaryType == KnownPrimaryType.Date ||
                        primaryType.KnownPrimaryType == KnownPrimaryType.DateTime ||
                        primaryType.KnownPrimaryType == KnownPrimaryType.DateTimeRfc1123 ||
                        primaryType.KnownPrimaryType == KnownPrimaryType.TimeSpan)
                    {
                        return "Date.parse('" + defaultValue + "')";
                    }

                    if (primaryType.KnownPrimaryType == KnownPrimaryType.ByteArray)
                    {
                        return "'" + defaultValue + "'.bytes.pack('C*')";
                    }
                }
            }

            EnumType enumType = type as EnumType;
            if (defaultValue != null && enumType != null)
            {
                return QuoteValue(defaultValue, quoteChar: "'");
            }
            return defaultValue;
        }
Example #21
0
        private static void AppendConstraintValidations(string valueReference, Dictionary <Constraint, string> constraints, IndentedStringBuilder sb, IModelType type)
        {
            foreach (var constraint in constraints.Keys)
            {
                string constraintCheck;
                var    knownFormat     = (type as PrimaryType)?.KnownFormat;
                string constraintValue =
                    knownFormat == KnownFormat.@char ? $"'{constraints[constraint]}'" :
                    knownFormat == KnownFormat.@decimal ? $"{constraints[constraint]}m" :
                    constraints[constraint];
                switch (constraint)
                {
                case Constraint.ExclusiveMaximum:
                    constraintCheck = $"{valueReference} >= {constraintValue}";
                    break;

                case Constraint.ExclusiveMinimum:
                    constraintCheck = $"{valueReference} <= {constraintValue}";
                    break;

                case Constraint.InclusiveMaximum:
                    constraintCheck = $"{valueReference} > {constraintValue}";
                    break;

                case Constraint.InclusiveMinimum:
                    constraintCheck = $"{valueReference} < {constraintValue}";
                    break;

                case Constraint.MaxItems:
                    constraintCheck = $"{valueReference}.Count > {constraintValue}";
                    break;

                case Constraint.MaxLength:
                    constraintCheck = $"{valueReference}.Length > {constraintValue}";
                    break;

                case Constraint.MinItems:
                    constraintCheck = $"{valueReference}.Count < {constraintValue}";
                    break;

                case Constraint.MinLength:
                    constraintCheck = $"{valueReference}.Length < {constraintValue}";
                    break;

                case Constraint.MultipleOf:
                    constraintCheck = $"{valueReference} % {constraintValue} != 0";
                    break;

                case Constraint.Pattern:
                    constraintValue = ToLiteral(constraintValue);
                    if (type is DictionaryType)
                    {
                        constraintCheck = $"!System.Linq.Enumerable.All({valueReference}.Values, value => System.Text.RegularExpressions.Regex.IsMatch(value, {constraintValue}))";
                    }
                    else
                    {
                        constraintCheck = $"!System.Text.RegularExpressions.Regex.IsMatch({valueReference}, {constraintValue})";
                    }
                    break;

                case Constraint.UniqueItems:
                    if ("true".EqualsIgnoreCase(constraints[constraint]))
                    {
                        constraintCheck = $"{valueReference}.Count != {valueReference}.Distinct().Count()";
                    }
                    else
                    {
                        constraintCheck = null;
                    }
                    break;

                default:
                    throw new NotSupportedException("Constraint '" + constraint + "' is not supported.");
                }
                if (constraintCheck != null)
                {
                    if (constraint != Constraint.UniqueItems)
                    {
                        sb.AppendLine("if ({0})", constraintCheck)
                        .AppendLine("{").Indent()
                        .AppendLine("throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.{0}, \"{1}\", {2});",
                                    constraint, valueReference.Replace("this.", ""), constraintValue).Outdent()
                        .AppendLine("}");
                    }
                    else
                    {
                        sb.AppendLine("if ({0})", constraintCheck)
                        .AppendLine("{").Indent()
                        .AppendLine("throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.{0}, \"{1}\");",
                                    constraint, valueReference.Replace("this.", "")).Outdent()
                        .AppendLine("}");
                    }
                }
            }
        }
Example #22
0
        /// <summary>
        /// Determines whether the specified model type is structurally equal to this object.
        /// </summary>
        /// <param name="other">The object to compare with this object.</param>
        /// <returns>true if the specified object is functionally equal to this object; otherwise, false.</returns>
        public override bool StructurallyEquals(IModelType other)
        {
            if (ReferenceEquals(other as EnumType, null))
            {
                return false;
            }

            return base.StructurallyEquals(other) && 
                Values.OrderBy(t => t).SequenceEqual(Values.OrderBy(t => t)) &&
                ModelAsString == (other as EnumType).ModelAsString;
        }
Example #23
0
        public static IndentedStringBuilder AppendConstraintValidations(this IModelType type, string valueReference, Dictionary <Constraint, string> constraints,
                                                                        IndentedStringBuilder builder)
        {
            if (valueReference == null)
            {
                throw new ArgumentNullException(nameof(valueReference));
            }

            if (constraints == null)
            {
                throw new ArgumentNullException(nameof(constraints));
            }

            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            foreach (var constraint in constraints.Keys)
            {
                string constraintCheck;
                string constraintValue = constraints[constraint];
                switch (constraint)
                {
                case Constraint.ExclusiveMaximum:
                    constraintCheck = $"{valueReference} >= {constraints[constraint]}";
                    break;

                case Constraint.ExclusiveMinimum:
                    constraintCheck = $"{valueReference} <= {constraints[constraint]}";
                    break;

                case Constraint.InclusiveMaximum:
                    constraintCheck = $"{valueReference} > {constraints[constraint]}";
                    break;

                case Constraint.InclusiveMinimum:
                    constraintCheck = $"{valueReference} < {constraints[constraint]}";
                    break;

                case Constraint.MaxItems:
                    constraintCheck = $"{valueReference}.length > {constraints[constraint]}";
                    break;

                case Constraint.MaxLength:
                    constraintCheck = $"{valueReference}.length > {constraints[constraint]}";
                    break;

                case Constraint.MinItems:
                    constraintCheck = $"{valueReference}.length < {constraints[constraint]}";
                    break;

                case Constraint.MinLength:
                    constraintCheck = $"{valueReference}.length < {constraints[constraint]}";
                    break;

                case Constraint.MultipleOf:
                    constraintCheck = $"{valueReference} % {constraints[constraint]} !== 0";
                    break;

                case Constraint.Pattern:

                    constraintValue = "/" + constraintValue.Replace("/", "\\/") + "/";
                    constraintCheck = $"{valueReference}.match({constraintValue}) === null";
                    break;

                case Constraint.UniqueItems:
                    if ("true".EqualsIgnoreCase(constraints[constraint]))
                    {
                        constraintCheck = string.Format(
                            "{0}.length !== {0}.filter(function(item, i, ar) {{ return ar.indexOf(item) === i; }}).length", valueReference);
                    }
                    else
                    {
                        constraintCheck = null;
                    }
                    break;

                default:
                    throw new NotSupportedException("Constraint '" + constraint + "' is not supported.");
                }
                if (constraintCheck != null)
                {
                    var escapedValueReference = valueReference.EscapeSingleQuotes();
                    if (constraint != Constraint.UniqueItems)
                    {
                        builder.AppendLine("if ({0})", constraintCheck)
                        .AppendLine("{").Indent()
                        .AppendLine("throw new Error('\"{0}\" should satisfy the constraint - \"{1}\": {2}');",
                                    escapedValueReference, constraint, constraintValue).Outdent()
                        .AppendLine("}");
                    }
                    else
                    {
                        builder.AppendLine("if ({0})", constraintCheck)
                        .AppendLine("{").Indent()
                        .AppendLine("throw new Error('\"{0}\" should satisfy the constraint - \"{1}\"');",
                                    escapedValueReference, constraint).Outdent()
                        .AppendLine("}");
                    }
                }
            }
            return(builder);
        }
        private static JsonSchema ParseType(Property property, IModelType type, IDictionary<string, JsonSchema> definitions, IEnumerable<CompositeType> modelTypes)
        {
            JsonSchema result = null;

            if (property == null || !property.IsReadOnly)
            {
                // A schema that matches a JSON object with specific properties, such as
                // { "name": { "type": "string" }, "age": { "type": "number" } }
                CompositeType compositeType = type as CompositeType;
                if (compositeType != null)
                {
                    result = ParseCompositeType(property, compositeType, definitions, modelTypes);
                }
                else
                {
                    // A schema that matches a "dictionary" JSON object, such as
                    // { "additionalProperties": { "type": "string" } }
                    DictionaryType dictionaryType = type as DictionaryType;
                    if (dictionaryType != null)
                    {
                        result = ParseDictionaryType(property, dictionaryType, definitions, modelTypes);
                    }
                    else
                    {
                        // A schema that matches a single value from a given set of values, such as
                        // { "enum": [ "a", "b" ] }
                        EnumType enumType = type as EnumType;
                        if (enumType != null)
                        {
                            result = ParseEnumType(property, enumType);
                        }
                        else
                        {
                            // A schema that matches simple values, such as { "type": "number" }
                            PrimaryType primaryType = type as PrimaryType;
                            if (primaryType != null)
                            {
                                result = ParsePrimaryType(property, primaryType);
                            }
                            else
                            {
                                // A schema that matches an array of values, such as
                                // { "items": { "type": "number" } }
                                SequenceType sequenceType = type as SequenceType;
                                if (sequenceType != null)
                                {
                                    result = ParseSequenceType(property, sequenceType, definitions, modelTypes);
                                }
                                else
                                {
                                    Debug.Fail("Unrecognized property type: " + type.GetType());
                                }
                            }
                        }
                    }
                }
            }

            return result;
        }
Example #25
0
 /// <summary>
 /// Determines if the given IModelType is a value type in C#
 /// </summary>
 /// <param name="modelType">The type to check</param>
 /// <returns>True if the type maps to a C# value type, otherwise false</returns>
 public static bool IsValueType(this IModelType modelType) => true == (modelType as IExtendedModelType)?.IsValueType;
Example #26
0
        public string GetPropertyDocumentationType(IModelType type)
        {
            // todo: fix the glitch where some model types don't have their parent reference set correctly
            if (type.Parent == null && (type is CompositeTypePy))
            {
                ((CompositeTypePy)type).CodeModel = CodeModel;
            }
            if (type.Parent == null && (type is EnumTypePy))
            {
                ((EnumTypePy)type).CodeModel = CodeModel;
            }

            return (type as IExtendedModelTypePy)?.TypeDocumentation ?? PythonConstants.None;
        }
        private Response BuildMethodReturnType(List<Stack<IModelType>> types, IModelType headerType)
        {
            IModelType baseType = New<PrimaryType>(KnownPrimaryType.Object);
            // Return null if no response is specified
            if (types.Count == 0)
            {
                return new Response(null, headerType);
            }
            // Return first if only one return type
            if (types.Count == 1)
            {
                return new Response(types.First().Pop(), headerType);
            }

            // BuildParameter up type inheritance tree
            types.ForEach(typeStack =>
            {
                IModelType type = typeStack.Peek();
                while (!Equals(type, baseType))
                {
                    if (type is CompositeType && _swaggerModeler.ExtendedTypes.ContainsKey(type.Name.RawValue))
                    {
                        type = _swaggerModeler.GeneratedTypes[_swaggerModeler.ExtendedTypes[type.Name.RawValue]];
                    }
                    else
                    {
                        type = baseType;
                    }
                    typeStack.Push(type);
                }
            });

            // Eliminate commonly shared base classes
            while (!types.First().IsNullOrEmpty())
            {
                IModelType currentType = types.First().Peek();
                foreach (var typeStack in types)
                {
                    IModelType t = typeStack.Pop();
                    if (!Equals(t, currentType))
                    {
                        return new Response(baseType, headerType);
                    }
                }
                baseType = currentType;
            }

            return new Response(baseType, headerType);
        }
 public static bool IsStream(this IModelType type)
 {
     return(type is PrimaryType primaryType && primaryType.KnownPrimaryType == KnownPrimaryType.Stream);
 }
 private void TryBuildDefaultResponse(string methodName, OperationResponse response, Method method, IModelType headerType)
 {
     IModelType errorModel = null;
     if (SwaggerOperationProducesJson())
     {
         if (TryBuildResponseBody(methodName, response, s => GenerateErrorModelName(s), out errorModel))
         {
             method.DefaultResponse = new Response(errorModel, headerType);
         }
     }
 }
        /// <summary>
        /// Return the TypeScript type (as a string) for specified type.
        /// </summary>
        /// <param name="type">IType to query</param>
        /// <param name="inModelsModule">Pass true if generating the code for the models module, thus model types don't need a "models." prefix</param>
        /// <returns>TypeScript type string for type</returns>
        public static string TSType(this IModelType type, bool inModelsModule)
        {
            CompositeTypeTS composite  = type as CompositeTypeTS;
            SequenceType    sequence   = type as SequenceType;
            DictionaryType  dictionary = type as DictionaryType;
            PrimaryType     primary    = type as PrimaryType;
            EnumType        enumType   = type as EnumType;

            string tsType;

            if (primary != null)
            {
                tsType = primary.PrimaryTSType();
            }
            else if (enumType != null)
            {
                string enumName = enumType.DeclarationName;
                if (inModelsModule || enumName.Contains('.') || enumName == "string")
                {
                    tsType = enumName;
                }
                else
                {
                    tsType = "Models." + enumName.ToPascalCase();
                }
            }
            else if (composite != null)
            {
                // ServiceClientCredentials starts with the "msRest." prefix, so strip msRest./msRestAzure. as we import those
                // types with no module prefix needed
                var compositeName = composite.UnionTypeName;
                if (compositeName.StartsWith("msRest.") || compositeName.StartsWith("msRestAzure."))
                {
                    tsType = compositeName.Substring(compositeName.IndexOf('.') + 1);
                }
                else if (inModelsModule || compositeName.Contains('.'))
                {
                    tsType = compositeName;
                }
                else
                {
                    tsType = "Models." + compositeName;
                }
            }
            else if (sequence != null)
            {
                if (sequence.IsSequenceContainingDateKind())
                {
                    tsType = sequence.ElementType.TSType(inModelsModule) + "[]" + " | string[]";
                }
                else
                {
                    tsType = sequence.ElementType.TSType(inModelsModule) + "[]";
                }
            }
            else if (dictionary != null)
            {
                if (dictionary.IsDictionaryContainingDateKind()) //then provide a union of Date and string
                {
                    tsType = "{ [propertyName: string]: " + dictionary.ValueType.TSType(inModelsModule) + " }" + " | { [propertyName: string]: string }";
                }
                else
                {
                    tsType = "{ [propertyName: string]: " + dictionary.ValueType.TSType(inModelsModule) + " }";
                }
            }
            else
            {
                throw new NotImplementedException($"Type '{type}' not implemented");
            }

            return(tsType);
        }
Example #31
0
 /// <summary>
 /// Casts the specified IModelType to the specified type paramater or throws an InvalidCastException.
 /// </summary>
 /// <typeparam name="T">The type to cast to.</typeparam>
 /// <param name="type">The type to cast from.</param>
 /// <returns>The type converted to T.</returns>
 public static T Cast <T>(this IModelType type)
 {
     return((T)type);
 }
 public static void ConstructMapper(TSBuilder builder, IModelType type, string serializedName, IVariable parameter, bool isPageable, bool expandComposite, bool isXML, bool isCaseSensitive = true, string xmlName = null)
 {
     builder.Value(value => ConstructMapper(value, type, serializedName, parameter, isPageable, expandComposite, isXML, isCaseSensitive, xmlName));
 }
Example #33
0
        //public bool IsComposed
        //{ get; private set; }

        #region .ctors and factories
        private ModelViewProperty(IModelType parent, IModelProperty modelProperty)
        {
            Parent        = parent;
            ModelProperty = modelProperty;
        }
 public static void ConstructMapper(TSValue value, IModelType type, string serializedName, IVariable parameter, bool isPageable, bool expandComposite, bool isXML, bool isCaseSensitive = true, string xmlName = null)
 {
     value.Object(mapper => ConstructMapper(mapper, type, serializedName, parameter, isPageable, expandComposite, isXML, isCaseSensitive, xmlName));
 }
Example #35
0
        /////////////////////////////////////////////////////////////////////////////////////////
        //
        // Type Extensions
        //
        /////////////////////////////////////////////////////////////////////////////////////////

        public static bool IsStreamType(this IModelType body)
        {
            var r = body as CompositeTypeGo;

            return(r != null && (r.BaseType.PrimaryType(KnownPrimaryType.Stream)));
        }
        public static void ConstructMapper(TSObject mapper, IModelType type, string serializedName, IVariable parameter, bool isPageable, bool expandComposite, bool isXML, bool isCaseSensitive = true, string xmlName = null)
        {
            string defaultValue = null;
            bool   isRequired   = false;
            bool   isConstant   = false;
            bool   isReadOnly   = false;
            Dictionary <Constraint, string> constraints = null;
            var property = parameter as Property;

            if (parameter != null)
            {
                defaultValue = parameter.DefaultValue;
                isRequired   = parameter.IsRequired;
                isConstant   = parameter.IsConstant;
                constraints  = parameter.Constraints;
            }

            string xmlPrefix = !isXML ? null : property?.XmlPrefix ?? type?.XmlPrefix;

            bool addXmlNameFromParameterValue = isXML && !string.IsNullOrEmpty(xmlName) && xmlName != serializedName;

            if (addXmlNameFromParameterValue)
            {
                if (!string.IsNullOrEmpty(xmlPrefix))
                {
                    xmlName = $"{xmlPrefix}:{xmlName}";
                }
                mapper.QuotedStringProperty("xmlName", xmlName);
            }

            if (isXML && !string.IsNullOrEmpty(serializedName) && !string.IsNullOrEmpty(xmlPrefix))
            {
                serializedName = $"{xmlPrefix}:{serializedName}";
            }

            if (property != null)
            {
                isReadOnly = property.IsReadOnly;

                if (isXML)
                {
                    if (property.XmlIsAttribute)
                    {
                        mapper.BooleanProperty("xmlIsAttribute", true);
                    }

                    if (property.XmlIsWrapped)
                    {
                        mapper.BooleanProperty("xmlIsWrapped", true);
                    }

                    string propertyXmlName = property.ModelType.XmlProperties?.Name ?? property.XmlName;
                    if (!addXmlNameFromParameterValue && !string.IsNullOrEmpty(propertyXmlName))
                    {
                        if (!string.IsNullOrEmpty(xmlPrefix))
                        {
                            propertyXmlName = $"{xmlPrefix}:{propertyXmlName}";
                        }

                        // For some reason we can't omit xmlName in this scenario if it is equal to
                        // serializedName. It might have to do with whether or not xmlElementName
                        // is present, but I'm not sure at this time.
                        mapper.QuotedStringProperty("xmlName", propertyXmlName);
                    }
                }
            }

            CompositeTypeTS composite = type as CompositeTypeTS;

            if (composite != null && composite.ContainsConstantProperties && (parameter != null && parameter.IsRequired))
            {
                defaultValue = "{}";
            }

            SequenceType sequence = type as SequenceType;

            if (sequence != null && isXML)
            {
                if (sequence.ElementXmlIsWrapped)
                {
                    mapper.BooleanProperty("xmlElementIsWrapped", true);
                }

                string xmlElementName = sequence.ElementType.XmlProperties?.Name ?? sequence.ElementXmlName;
                if (!string.IsNullOrEmpty(xmlElementName))
                {
                    mapper.QuotedStringProperty("xmlElementName", xmlElementName);
                }
            }

            if (isRequired)
            {
                mapper.BooleanProperty("required", true);
            }

            if (parameter?.IsXNullable != null)
            {
                if (parameter.IsXNullable.Value)
                {
                    mapper.BooleanProperty("nullable", true);
                }
                else
                {
                    mapper.BooleanProperty("nullable", false);
                }
            }

            if (isReadOnly)
            {
                mapper.BooleanProperty("readOnly", true);
            }

            if (isConstant)
            {
                mapper.BooleanProperty("isConstant", true);
            }

            if (serializedName != null)
            {
                if (!isCaseSensitive)
                {
                    serializedName = serializedName.ToLower();
                }
                mapper.QuotedStringProperty("serializedName", serializedName);
            }

            if (!string.IsNullOrEmpty(defaultValue))
            {
                mapper.TextProperty("defaultValue", defaultValue);
            }

            DictionaryType dictionary = type as DictionaryType;
            PrimaryType    primary    = type as PrimaryType;
            EnumType       enumType   = type as EnumType;

            void applyConstraints(TSObject obj)
            {
                bool useClientSideValidation = (bool)(Settings.Instance?.CustomSettings[CodeModelTS.ClientSideValidationSettingName] ?? false);

                if (useClientSideValidation && constraints != null && constraints.Any())
                {
                    obj.ObjectProperty("constraints", constraintsObject =>
                    {
                        foreach (KeyValuePair <Constraint, string> constraintEntry in constraints)
                        {
                            Constraint constraint  = constraintEntry.Key;
                            string constraintValue = constraintEntry.Value;
                            if (constraint == Constraint.Pattern)
                            {
                                constraintValue = CreateRegexPatternConstraintValue(constraintValue);
                            }
                            constraintsObject.TextProperty(constraint.ToString(), constraintValue);
                        }
                    });
                }
            }

            // Apply header collection constraints only to dictionary values, not the dictionary itself
            string prefix          = parameter?.Extensions?.GetValue <string>(SwaggerExtensions.HeaderCollectionPrefix);
            bool   skipConstraints = !string.IsNullOrEmpty(prefix) && dictionary != null;

            if (!skipConstraints)
            {
                applyConstraints(mapper);
            }

            if (primary != null)
            {
                switch (primary.KnownPrimaryType)
                {
                case KnownPrimaryType.Base64Url:
                case KnownPrimaryType.Boolean:
                case KnownPrimaryType.ByteArray:
                case KnownPrimaryType.Date:
                case KnownPrimaryType.DateTime:
                case KnownPrimaryType.DateTimeRfc1123:
                case KnownPrimaryType.Object:
                case KnownPrimaryType.Stream:
                case KnownPrimaryType.String:
                case KnownPrimaryType.TimeSpan:
                case KnownPrimaryType.UnixTime:
                case KnownPrimaryType.Uuid:
                    AddTypeProperty(mapper, primary.KnownPrimaryType.ToString());
                    break;

                case KnownPrimaryType.Int:
                case KnownPrimaryType.Long:
                case KnownPrimaryType.Decimal:
                case KnownPrimaryType.Double:
                    AddTypeProperty(mapper, "Number");
                    break;

                default:
                    throw new NotImplementedException($"{primary} is not a supported Type.");
                }
            }
            else if (enumType != null)
            {
                if (enumType.ModelAsString)
                {
                    AddTypeProperty(mapper, "String");
                }
                else
                {
                    AddTypeProperty(mapper, "Enum", typeObject =>
                    {
                        typeObject.ArrayProperty("allowedValues", allowedValues =>
                        {
                            foreach (EnumValue enumValue in enumType.Values)
                            {
                                allowedValues.QuotedString(enumValue.SerializedName);
                            }
                        });
                    });
                }
            }
            else if (sequence != null)
            {
                AddTypeProperty(mapper, "Sequence", typeObject =>
                {
                    typeObject.Property("element", element =>
                    {
                        ConstructMapper(element, sequence.ElementType, null, null, false, false, isXML, isCaseSensitive);
                    });
                });
            }
            else if (dictionary != null)
            {
                AddTypeProperty(mapper, "Dictionary", typeObject =>
                {
                    typeObject.ObjectProperty("value", dictionaryValue =>
                    {
                        ConstructMapper(dictionaryValue, dictionary.ValueType, null, null, false, false, isXML, isCaseSensitive);
                        applyConstraints(dictionaryValue);
                    });
                });

                if (!string.IsNullOrEmpty(prefix))
                {
                    mapper.QuotedStringProperty("headerCollectionPrefix", prefix);
                }
            }
            else if (composite != null)
            {
                AddTypeProperty(mapper, "Composite", typeObject =>
                {
                    if (expandComposite)
                    {
                        if (composite.IsPolymorphic)
                        {
                            // Note: If the polymorphicDiscriminator has a dot in it's name then do not escape that dot for
                            // it's serializedName, the way it is done for other properties. This makes it easy to find the
                            // discriminator property from the responseBody during deserialization. Please, do not get confused
                            // between the definition of the discriminator and the definition of the property that is
                            // marked as the discriminator.
                            typeObject.ObjectProperty("polymorphicDiscriminator", polymorphicDiscriminator =>
                            {
                                polymorphicDiscriminator.QuotedStringProperty("serializedName", composite.PolymorphicDiscriminator);
                                polymorphicDiscriminator.QuotedStringProperty("clientName", Singleton <CodeNamerTS> .Instance.GetPropertyName(composite.PolymorphicDiscriminator));
                            });
                            typeObject.QuotedStringProperty("uberParent", composite.Name);
                        }
                        else
                        {
                            CompositeType baseType = composite;
                            while (baseType.BaseModelType != null)
                            {
                                baseType = baseType.BaseModelType;
                            }
                            if (baseType.IsPolymorphic)
                            {
                                typeObject.TextProperty("polymorphicDiscriminator", baseType.Name + ".type.polymorphicDiscriminator");
                                typeObject.QuotedStringProperty("uberParent", baseType.Name);
                            }
                        }
                    }

                    typeObject.QuotedStringProperty("className", composite.Name);

                    if (expandComposite)
                    {
                        typeObject.ObjectProperty("modelProperties", modelProperties =>
                        {
                            if (composite.BaseModelType != null && composite.BaseModelType.ComposedProperties.Any())
                            {
                                modelProperties.Spread(composite.BaseModelType.Name + ".type.modelProperties");
                            }
                            foreach (Property prop in composite.Properties)
                            {
                                var serializedPropertyName = prop.SerializedName;
                                if (isPageable)
                                {
                                    PropertyInfo itemName     = composite.GetType().GetProperty("ItemName");
                                    PropertyInfo nextLinkName = composite.GetType().GetProperty("NextLinkName");
                                    string nextLinkNameValue  = (string)nextLinkName.GetValue(composite);
                                    if (itemName != null && ((string)itemName.GetValue(composite) == prop.Name))
                                    {
                                        serializedPropertyName = "";
                                    }

                                    if (prop.Name.Contains("nextLink") && nextLinkName != null && nextLinkNameValue == null)
                                    {
                                        continue;
                                    }
                                }

                                if (modelProperties.ContainsProperty(prop.Name))
                                {
                                    // throw new InvalidOperationException($"Mapper \"{serializedName}\" contains multiple modelProperties with the name \"{prop.Name}\".");
                                }
                                else
                                {
                                    modelProperties.Property(prop.Name, propertyValue => ConstructMapper(propertyValue, prop.ModelType, serializedPropertyName, prop, false, false, isXML, isCaseSensitive));
                                }
                            }
                        });
                    }

                    if (composite.AdditionalProperties != null)
                    {
                        typeObject.ObjectProperty("additionalProperties", additionalProperties =>
                        {
                            ConstructMapper(additionalProperties, composite.AdditionalProperties, serializedName: null, parameter: null, isPageable: false, expandComposite: false, isXML: isXML);
                        });
                    }
                    else
                    {
                        CompositeTypeTS baseType = composite;
                        while (true)
                        {
                            baseType = (CompositeTypeTS)baseType.BaseModelType;
                            if (baseType == null)
                            {
                                break;
                            }
                            else if (baseType.AdditionalProperties != null)
                            {
                                typeObject.TextProperty("additionalProperties", $"{baseType.Name}.type.additionalProperties");
                                break;
                            }
                        }
                    }
                });
            }
            else
            {
                throw new NotImplementedException($"{type} is not a supported Type.");
            }
        }
Example #37
0
        public ModelsModel Bind(CodeModelTs codeModel)
        {
            var models = new ModelsModel
            {
                Header = new HeaderModel
                {
                    ApiVersion = codeModel.ApiVersion
                },
                RequestModels  = new List <Model.Model>(),
                ResponseModels = new List <Model.Model>(),
                EnumModels     = new List <EnumModel>()
            };

            var modelTypesFromDefinition = codeModel.ModelTypes.ToList();

            var enumsInModels = new List <Tuple <string, IModelType> >();

            Func <IVariable, ModelProperty> getPropertyModel =
                variable =>
            {
                var    propertyType = variable.ModelType;
                string typeName     = null;

                //if (propertyType.IsEnumType())
                //{
                //    var enumType = (EnumTypeTs) propertyType;
                //    typeName = enumType.GetImplementationName(variable);
                //    enumsInModels.Add(new Tuple<string, IModelType>(typeName, propertyType));
                //}

                return(new ModelProperty
                {
                    Name = variable.Name.ToCamelCase(),
                    IsRequired = variable.IsRequired,
                    TypeName = typeName ?? GetTypeText(propertyType)
                });
            };

            foreach (var method in codeModel.Methods)
            {
                string     requestName  = null;
                string     responseName = null;
                IModelType modelType    = null;

                if (!TryGetResponseName(method, out modelType, out responseName, out requestName))
                {
                    continue;
                }

                var requestModelType = new Model.Model
                {
                    Name       = requestName,
                    Properties = new List <ModelProperty>()
                };

                foreach (Parameter parameter in method.Parameters)
                {
                    requestModelType.Properties.Add(getPropertyModel(parameter));
                }

                models.RequestModels.Add(requestModelType);

                if (modelType.IsPrimaryType() || modelType.IsSequenceType() || modelType.IsEnumType())
                {
                    continue;
                }

                var responseModelType = new Model.Model
                {
                    Name       = responseName,
                    Properties = new List <ModelProperty>()
                };

                var type = modelTypesFromDefinition.FirstOrDefault(m => m.ClassName == modelType.ClassName);

                if (type == null)
                {
                    continue;
                }

                modelTypesFromDefinition.Remove(type);

                foreach (var property in type.Properties)
                {
                    responseModelType.Properties.Add(getPropertyModel(property));
                }

                models.ResponseModels.Add(responseModelType);
            }

            foreach (var modelType in modelTypesFromDefinition)
            {
                if (modelType.IsPrimaryType() || modelType.IsSequenceType() && modelType.IsEnumType())
                {
                    continue;
                }

                var model = new Model.Model
                {
                    Name       = GetTypeText(modelType),
                    Properties = new List <ModelProperty>()
                };

                models.ResponseModels.Add(model);

                foreach (var property in modelType.Properties)
                {
                    model.Properties.Add(getPropertyModel(property));
                }
            }

            // disable enum generation for now #ranantawat.

            // foreach (var pair in enumsInModels)
            // {
            //    var enumType = (EnumTypeTs) pair.Item2;
            //    var enumModel = new EnumModel {Name = pair.Item1};

            //    if (enumType.ModelAsString)
            //    {
            //        for (var index = 0; index < enumType.EnumValues.Length; index++)
            //        {
            //            var value = enumType.Children.Cast<EnumValue>().ToArray()[index];
            //            enumModel.Values.Add(value.Name, index);
            //        }
            //    }

            //    models.EnumModels.Add(enumModel);
            // }

            models.EnumModels = models.EnumModels.Distinct().ToList();

            foreach (EnumType enumType in codeModel.EnumTypes.ToArray())
            {
                models.EnumModels.Add(new EnumModel
                {
                    Name   = enumType.DeclarationName,
                    Values = new Dictionary <string, object>()
                });
            }

            return(models);
        }
        public static string InitializePrimaryType(this IModelType paramType, string paramName, bool isBrowser = false)
        {
            var paramValue = "\"\"";

            if (paramType.IsPrimaryType(KnownPrimaryType.String))
            {
                if (paramName.EqualsIgnoreCase("location"))
                {
                    paramValue = "\"westus\"";
                }
                else
                {
                    paramValue = $"\"test{paramName.ToCamelCase()}\"";
                }
            }
            else if (paramType.IsPrimaryType(KnownPrimaryType.Date))
            {
                paramValue = "new Date().toISOString().substring(0, 10)";
            }
            else if (paramType.IsPrimaryType(KnownPrimaryType.DateTime))
            {
                paramValue = "new Date().toISOString()";
            }
            else if (paramType.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123))
            {
                paramValue = "new Date().toUTCString()";
            }
            else if (paramType.IsPrimaryType(KnownPrimaryType.UnixTime))
            {
                paramValue = "new Date()";
            }
            else if (paramType.IsPrimaryType(KnownPrimaryType.TimeSpan))
            {
                paramValue = "\"P1Y2M3DT4H5M6S\"";
            }
            else if (paramType.IsPrimaryType(KnownPrimaryType.Boolean))
            {
                paramValue = "true";
            }
            else if (paramType.IsPrimaryType(KnownPrimaryType.Int) || paramType.IsPrimaryType(KnownPrimaryType.Long))
            {
                paramValue = "1";
            }
            else if (paramType.IsPrimaryType(KnownPrimaryType.Decimal) || paramType.IsPrimaryType(KnownPrimaryType.Double))
            {
                paramValue = "1.01";
            }
            else if (paramType.IsPrimaryType(KnownPrimaryType.Object))
            {
                paramValue = "{}";
            }
            else if (paramType.IsPrimaryType(KnownPrimaryType.Uuid))
            {
                paramValue = "ec7b1657-199d-4d8a-bbb2-89a11a42e02a";
            }
            else if (paramType.IsPrimaryType(KnownPrimaryType.Stream))
            {
                paramValue = isBrowser ? "new ReadableStream()" : "new require(\"stream\").Readable()";
            }
            return(paramValue);
        }
Example #39
0
        private string GetPagingSetting(CodeModelPya codeModel, CompositeType body, Dictionary <string, object> extensions, IModelType valueType,
                                        IDictionary <int, string> typePageClasses, string methodName)
        {
            string valueTypeName = valueType.Name;
            var    ext           = extensions[AzureExtensions.PageableExtension] as JContainer;

            var ignoreNextLink = false;

            if ((ext["nextLinkName"] != null) && (ext["nextLinkName"].Type == JTokenType.Null))
            {
                ignoreNextLink = true;
            }
            var nextLinkName = (string)ext["nextLinkName"] ?? "nextLink";
            var itemName     = (string)ext["itemName"] ?? "value";

            // nextLinkName = nextLinkName.Replace(".", "\\\\.");
            // itemName = itemName.Replace(".", "\\\\.");
            var findNextLink = false;
            var findItem     = false;

            foreach (var property in body.ComposedProperties)
            {
                var propName = property.SerializedName;

                if (propName == nextLinkName)
                {
                    findNextLink = true;
                    nextLinkName = property.SerializedName = property.SerializedName.Replace(".", "\\\\.")?.Replace("\\\\\\\\", "\\\\");
                }
                else if (propName == itemName)
                {
                    findItem = true;
                    itemName = property.SerializedName = property.SerializedName.Replace(".", "\\\\.")?.Replace("\\\\\\\\", "\\\\");
                }

                if (propName == nextLinkName.Replace(".", "\\\\.")?.Replace("\\\\\\\\", "\\\\"))
                {
                    nextLinkName = nextLinkName.Replace(".", "\\\\.")?.Replace("\\\\\\\\", "\\\\");
                    findNextLink = true;
                }
                else if (propName == itemName.Replace(".", "\\\\.")?.Replace("\\\\\\\\", "\\\\"))
                {
                    itemName = itemName.Replace(".", "\\\\.")?.Replace("\\\\\\\\", "\\\\");
                    findItem = true;
                }
            }

            if (!findItem)
            {
                throw new KeyNotFoundException("Couldn't find the item property specified by extension");
            }

            string className;
            var    hash = (nextLinkName + "#" + itemName).GetHashCode();

            if (!typePageClasses.ContainsKey(hash))
            {
                className = (string)ext["className"];
                if (string.IsNullOrEmpty(className))
                {
                    if (typePageClasses.Count > 0)
                    {
                        className = valueTypeName +
                                    string.Format(CultureInfo.InvariantCulture, "Paged{0}", typePageClasses.Count);
                    }
                    else
                    {
                        className = valueTypeName + "Paged";
                    }
                }
                typePageClasses.Add(hash, className);
            }

            className        = typePageClasses[hash];
            ext["className"] = className;

            var pageModel = new PagePya(className, nextLinkName, itemName, valueType);

            if (!codeModel.PageModels.Contains(pageModel))
            {
                codeModel.PageModels.Add(pageModel);
            }

            return(className);
        }
 public static string GetObsoleteAttribute(this IModelType x)
 => GetObsoleteAttribute(x.DeprecationMessage);
Example #41
0
 private bool ContainsCompositeType(IModelType type)
 {
     bool result = false;
     //base condition
     if (type is CompositeType || 
         type is Core.Model.SequenceType && (type as Core.Model.SequenceType).ElementType is CompositeType || 
         type is Core.Model.DictionaryType && (type as Core.Model.DictionaryType).ValueType is CompositeType)
     {
         result = true;
     }
     else if (type is Core.Model.SequenceType)
     {
         result = ContainsCompositeType((type as Core.Model.SequenceType).ElementType);
     }
     else if (type is Core.Model.DictionaryType)
     {
         result = ContainsCompositeType((type as Core.Model.DictionaryType).ValueType);
     }
     return result;
 }
 /// <summary>
 /// Returns true if the IModelType is a kind of string (ie, string PrimaryType or an Enum that is modeled as a string)
 /// </summary>
 /// <param name="t">ModelType to check</param>
 /// <returns>true if the IModelType is a kind of string</returns>
 public static bool IsKindOfString(this IModelType t) =>
 t is PrimaryType pt &&
Example #43
0
 /// <summary>
 /// Conditionally returns the ModelType name expressed as a nullable type (for classes, nothing different, for value types, append a '?'
 /// </summary>
 /// <param name="modelType">The ModelType to return as nullable</param>
 /// <param name="predicate">An boolean indicating whether to make the type nullable</param>
 /// <returns>The ModelType name expressed as a nullable type</returns>
 public static string AsNullableType(this IModelType modelType, bool predicate) => predicate && modelType.IsValueType() ? $"{modelType.Name}?" : modelType.DeclarationName;
        public static bool IsResource(this IModelType type)
        {
            CompositeTypeJva compositeType = type as CompositeTypeJva;

            return(compositeType != null && compositeType.IsResource);
        }
Example #45
0
 private bool IsFolder(IModelType type)
 {
     return(type.GetType() == typeof(Folder));
 }
 public override IModelType NormalizeTypeReference(IModelType type)
 {
     throw new System.NotImplementedException();
 }
Example #47
0
        public static string ConstructMapper(this IModelType type, string serializedName, IVariable parameter, bool isPageable, bool expandComposite)
        {
            var    builder      = new IndentedStringBuilder("  ");
            string defaultValue = null;
            bool   isRequired   = false;
            bool   isConstant   = false;
            bool   isReadOnly   = false;
            Dictionary <Constraint, string> constraints = null;
            var property = parameter as Property;

            if (parameter != null)
            {
                defaultValue = parameter.DefaultValue;
                isRequired   = parameter.IsRequired;
                isConstant   = parameter.IsConstant;
                constraints  = parameter.Constraints;
            }
            if (property != null)
            {
                isReadOnly = property.IsReadOnly;
            }
            CompositeType composite = type as CompositeType;

            if (composite != null && composite.ContainsConstantProperties && (parameter != null && parameter.IsRequired))
            {
                defaultValue = "{}";
            }
            SequenceType   sequence   = type as SequenceType;
            DictionaryType dictionary = type as DictionaryType;
            PrimaryType    primary    = type as PrimaryType;
            EnumType       enumType   = type as EnumType;

            builder.AppendLine("").Indent();
            if (isRequired)
            {
                builder.AppendLine("required: true,");
            }
            else
            {
                builder.AppendLine("required: false,");
            }
            if (isReadOnly)
            {
                builder.AppendLine("readOnly: true,");
            }
            if (isConstant)
            {
                builder.AppendLine("isConstant: true,");
            }
            if (serializedName != null)
            {
                builder.AppendLine("serializedName: '{0}',", serializedName);
            }
            if (defaultValue != null)
            {
                builder.AppendLine("defaultValue: {0},", defaultValue);
            }
            if (constraints != null && constraints.Count > 0)
            {
                builder.AppendLine("constraints: {").Indent();
                var keys = constraints.Keys.ToList <Constraint>();
                for (int j = 0; j < keys.Count; j++)
                {
                    var constraintValue = constraints[keys[j]];
                    if (keys[j] == Constraint.Pattern)
                    {
                        constraintValue = $"'{constraintValue}'";
                    }
                    if (j != keys.Count - 1)
                    {
                        builder.AppendLine("{0}: {1},", keys[j], constraintValue);
                    }
                    else
                    {
                        builder.AppendLine("{0}: {1}", keys[j], constraintValue);
                    }
                }
                builder.Outdent().AppendLine("},");
            }
            // Add type information
            if (primary != null)
            {
                switch (primary.KnownPrimaryType)
                {
                case KnownPrimaryType.Boolean:
                    builder.AppendLine("type: {").Indent().AppendLine("name: 'Boolean'").Outdent().AppendLine("}");
                    break;

                case KnownPrimaryType.Int:
                case KnownPrimaryType.Long:
                case KnownPrimaryType.Decimal:
                case KnownPrimaryType.Double:
                    builder.AppendLine("type: {").Indent().AppendLine("name: 'Number'").Outdent().AppendLine("}");
                    break;

                case KnownPrimaryType.String:
                    builder.AppendLine("type: {").Indent().AppendLine("name: 'String'").Outdent().AppendLine("}");
                    break;

                case KnownPrimaryType.Uuid:
                    builder.AppendLine("type: {").Indent().AppendLine("name: 'String'").Outdent().AppendLine("}");
                    break;

                // case KnownPrimaryType.Uuid:
                //  builder.AppendLine("type: {").Indent().AppendLine("name: 'Uuid'").Outdent().AppendLine("}");
                //break;
                case KnownPrimaryType.ByteArray:
                    builder.AppendLine("type: {").Indent().AppendLine("name: 'ByteArray'").Outdent().AppendLine("}");
                    break;

                case KnownPrimaryType.Base64Url:
                    builder.AppendLine("type: {").Indent().AppendLine("name: 'Base64Url'").Outdent().AppendLine("}");
                    break;

                case KnownPrimaryType.Date:
                    builder.AppendLine("type: {").Indent().AppendLine("name: 'Date'").Outdent().AppendLine("}");
                    break;

                case KnownPrimaryType.DateTime:
                    builder.AppendLine("type: {").Indent().AppendLine("name: 'DateTime'").Outdent().AppendLine("}");
                    break;

                case KnownPrimaryType.DateTimeRfc1123:
                    builder.AppendLine("type: {").Indent().AppendLine("name: 'DateTimeRfc1123'").Outdent().AppendLine("}");
                    break;

                case KnownPrimaryType.TimeSpan:
                    builder.AppendLine("type: {").Indent().AppendLine("name: 'TimeSpan'").Outdent().AppendLine("}");
                    break;

                case KnownPrimaryType.UnixTime:
                    builder.AppendLine("type: {").Indent().AppendLine("name: 'UnixTime'").Outdent().AppendLine("}");
                    break;

                case KnownPrimaryType.Object:
                    builder.AppendLine("type: {").Indent().AppendLine("name: 'Object'").Outdent().AppendLine("}");
                    break;

                case KnownPrimaryType.Stream:
                    builder.AppendLine("type: {").Indent().AppendLine("name: 'Stream'").Outdent().AppendLine("}");
                    break;

                default:
                    throw new NotImplementedException(string.Format(Resources.InvalidType, primary));
                }
            }
            else if (enumType != null)
            {
                if (enumType.ModelAsString)
                {
                    builder.AppendLine("type: {").Indent().AppendLine("name: 'String'").Outdent().AppendLine("}");
                }
                else
                {
                    builder.AppendLine("type: {")
                    .Indent()
                    .AppendLine("name: 'Enum',")
                    .AppendLine("allowedValues: {0}", enumType.GetEnumValuesArray())
                    .Outdent()
                    .AppendLine("}");
                }
            }
            else if (sequence != null)
            {
                builder.AppendLine("type: {")
                .Indent()
                .AppendLine("name: 'Sequence',")
                .AppendLine("element: {")
                .Indent()
                .AppendLine("{0}", sequence.ElementType.ConstructMapper(sequence.ElementType.DeclarationName + "ElementType", null, false, false))
                .Outdent().AppendLine("}").Outdent().AppendLine("}");
            }
            else if (dictionary != null)
            {
                builder.AppendLine("type: {")
                .Indent()
                .AppendLine("name: 'Dictionary',")
                .AppendLine("value: {")
                .Indent()
                .AppendLine("{0}", dictionary.ValueType.ConstructMapper(dictionary.ValueType.DeclarationName + "ElementType", null, false, false))
                .Outdent().AppendLine("}").Outdent().AppendLine("}");
            }
            else if (composite != null)
            {
                builder.AppendLine("type: {")
                .Indent()
                .AppendLine("name: 'Composite',");
                if (composite.IsPolymorphic)
                {
                    builder = ConstructPolymorphicDiscriminator(composite, builder);
                }
                if (!expandComposite)
                {
                    builder.AppendLine("className: '{0}'", composite.Name).Outdent().AppendLine("}");
                }
                else
                {
                    builder.AppendLine("className: '{0}',", composite.Name)
                    .AppendLine("modelProperties: {").Indent();
                    var composedPropertyList = new List <Property>(composite.ComposedProperties);
                    for (var i = 0; i < composedPropertyList.Count; i++)
                    {
                        var          prop = composedPropertyList[i];
                        var          serializedPropertyName = prop.SerializedName;
                        PropertyInfo nextLinkName           = null;
                        string       nextLinkNameValue      = null;
                        if (isPageable)
                        {
                            var itemName = composite.GetType().GetProperty("ItemName");
                            nextLinkName      = composite.GetType().GetProperty("NextLinkName");
                            nextLinkNameValue = (string)nextLinkName.GetValue(composite);
                            if (itemName != null && ((string)itemName.GetValue(composite) == prop.Name))
                            {
                                serializedPropertyName = "";
                            }

                            if (prop.Name.Contains("nextLink") && nextLinkName != null && nextLinkNameValue == null)
                            {
                                continue;
                            }
                        }

                        if (i != composedPropertyList.Count - 1)
                        {
                            if (!isPageable)
                            {
                                builder.AppendLine("{0}: {{{1}}},", prop.Name, prop.ModelType.ConstructMapper(serializedPropertyName, prop, false, false));
                            }
                            else
                            {
                                // if pageable and nextlink is also present then we need a comma as nextLink would be the next one to be added
                                if (nextLinkNameValue != null)
                                {
                                    builder.AppendLine("{0}: {{{1}}},", prop.Name, prop.ModelType.ConstructMapper(serializedPropertyName, prop, false, false));
                                }
                                else
                                {
                                    builder.AppendLine("{0}: {{{1}}}", prop.Name, prop.ModelType.ConstructMapper(serializedPropertyName, prop, false, false));
                                }
                            }
                        }
                        else
                        {
                            builder.AppendLine("{0}: {{{1}}}", prop.Name, prop.ModelType.ConstructMapper(serializedPropertyName, prop, false, false));
                        }
                    }
                    // end of modelProperties and type
                    builder.Outdent().AppendLine("}").Outdent().AppendLine("}");
                }
            }
            else
            {
                throw new NotImplementedException(string.Format(Resources.InvalidType, type));
            }
            return(builder.ToString());
        }
 public override IModelType NormalizeTypeDeclaration(IModelType type)
 {
     throw new System.NotImplementedException();
 }
Example #49
0
 /// <summary>
 /// Returns true if the IModelType is a kind of string (ie, string PrimaryType or an Enum that is modeled as a string)
 /// </summary>
 /// <param name="t">ModelType to check</param>
 /// <returns>true if the IModelType is a kind of string</returns>
 public static bool IsKindOfString(this IModelType t) =>
 t is PrimaryType &&
 ((PrimaryType)t).KnownPrimaryType == KnownPrimaryType.String &&
 ((PrimaryType)t).KnownFormat != KnownFormat.@char ||
 t is EnumType &&
 ((EnumType)t).ModelAsString;
 public override string EscapeDefaultValue(string value, IModelType type)
 {
     throw new NotImplementedException();
 }
Example #51
0
        /// <summary>
        /// Generate code to perform required validation on a type
        /// </summary>
        /// <param name="type">The type to validate</param>
        /// <param name="scope">A scope provider for generating variable names as necessary</param>
        /// <param name="valueReference">A reference to the value being validated</param>
        /// <param name="constraints">Constraints</param>
        /// <returns>The code to validate the reference of the given type</returns>
        public static string ValidateType(this IModelType type, IChild scope, string valueReference,
                                          Dictionary <Constraint, string> constraints)
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            var model      = type as CompositeTypeCs;
            var sequence   = type as SequenceTypeCs;
            var dictionary = type as DictionaryTypeCs;

            var sb = new IndentedStringBuilder();

            if (model != null && model.ShouldValidateChain())
            {
                sb.AppendLine("{0}.Validate();", valueReference);
            }

            if (constraints != null && constraints.Any())
            {
                AppendConstraintValidations(valueReference, constraints, sb, (type as PrimaryType)?.KnownFormat ?? KnownFormat.none);
            }

            if (sequence != null && sequence.ShouldValidateChain())
            {
                var elementVar      = scope.GetUniqueName("element");
                var innerValidation = sequence.ElementType.ValidateType(scope, elementVar, null);
                if (!string.IsNullOrEmpty(innerValidation))
                {
                    sb.AppendLine("foreach (var {0} in {1})", elementVar, valueReference)
                    .AppendLine("{").Indent()
                    .AppendLine(innerValidation).Outdent()
                    .AppendLine("}");
                }
            }
            else if (dictionary != null && dictionary.ShouldValidateChain())
            {
                var valueVar        = scope.GetUniqueName("valueElement");
                var innerValidation = dictionary.ValueType.ValidateType(scope, valueVar, null);
                if (!string.IsNullOrEmpty(innerValidation))
                {
                    sb.AppendLine("foreach (var {0} in {1}.Values)", valueVar, valueReference)
                    .AppendLine("{").Indent()
                    .AppendLine(innerValidation).Outdent()
                    .AppendLine("}").Outdent();
                }
            }

            if (sb.ToString().Trim().Length > 0)
            {
                if (type.IsValueType())
                {
                    return(sb.ToString());
                }
                else
                {
                    return(CheckNull(valueReference, sb.ToString()));
                }
            }

            return(null);
        }
Example #52
0
 /// <summary>
 /// Initializes a new instance of Response.
 /// </summary>
 /// <param name="body">Body type.</param>
 /// <param name="headers">Headers type.</param>
 public Response(IModelType body, IModelType headers)
 {
     Body    = body;
     Headers = headers;
 }
 private static void BuildMethodReturnTypeStack(IModelType type, List<Stack<IModelType>> types)
 {
     var typeStack = new Stack<IModelType>();
     typeStack.Push(type);
     types.Add(typeStack);
 }
Example #54
0
        /////////////////////////////////////////////////////////////////////////////////////////
        //
        // Type Extensions
        //
        /////////////////////////////////////////////////////////////////////////////////////////

        public static bool IsStreamType(this IModelType body)
        {
            return(body is CompositeTypeGo r && (r.BaseType.PrimaryType(KnownPrimaryType.Stream)));
        }
        private bool TryBuildStreamResponse(HttpStatusCode responseStatusCode, OperationResponse response,
            Method method, List<Stack<IModelType>> types, IModelType headerType)
        {
            bool handled = false;
            if (SwaggerOperationProducesNotEmpty())
            {
                if (response.Schema != null)
                {
                    IModelType serviceType = response.Schema.GetBuilder(_swaggerModeler)
                        .BuildServiceType(response.Schema.Reference.StripDefinitionPath());

                    Debug.Assert(serviceType != null);

                    BuildMethodReturnTypeStack(serviceType, types);

                    var compositeType = serviceType as CompositeType;
                    if (compositeType != null)
                    {
                        VerifyFirstPropertyIsByteArray(compositeType);
                    }
                    method.Responses[responseStatusCode] = new Response(serviceType, headerType);
                    handled = true;
                }
            }
            return handled;
        }
Example #56
0
 public static bool ShouldBeSyntheticType(this IModelType type)
 {
     return(type is PrimaryType || type is SequenceType || type is DictionaryType || type is EnumType ||
            (type is CompositeType && (type as CompositeTypeGo).IsPolymorphicResponse()));
 }
        private bool TryBuildEmptyResponse(string methodName, HttpStatusCode responseStatusCode,
            OperationResponse response, Method method, List<Stack<IModelType>> types, IModelType headerType)
        {
            bool handled = false;

            if (response.Schema == null)
            {
                method.Responses[responseStatusCode] = new Response(null, headerType);
                handled = true;
            }
            else
            {
                if (_operation.Produces.IsNullOrEmpty())
                {
                    method.Responses[responseStatusCode] = new Response(New<PrimaryType>(KnownPrimaryType.Object), headerType);
                    BuildMethodReturnTypeStack(New<PrimaryType>(KnownPrimaryType.Object), types);
                    handled = true;
                }

                var unwrapedSchemaProperties =
                    _swaggerModeler.Resolver.Unwrap(response.Schema).Properties;
                if (unwrapedSchemaProperties != null && unwrapedSchemaProperties.Any())
                {
                    Logger.LogWarning(Resources.NoProduceOperationWithBody,
                        methodName);
                }
            }

            return handled;
        }
Example #58
0
 /// <summary>
 /// Gets if the type has an interface.
 /// </summary>
 public static bool HasInterface(this IModelType type)
 {
     return((type is CompositeTypeGo compositeType) &&
            (compositeType.IsRootType || compositeType.BaseIsPolymorphic && !compositeType.IsLeafType));
 }
        private bool TryBuildResponseBody(string methodName, OperationResponse response,
            Func<string, string> typeNamer, out IModelType responseType)
        {
            bool handled = false;
            responseType = null;
            if (SwaggerOperationProducesJson())
            {
                if (response.Schema != null)
                {
                    string referenceKey;
                    if (response.Schema.Reference != null)
                    {
                        referenceKey = response.Schema.Reference.StripDefinitionPath();
                        response.Schema.Reference = referenceKey;
                    }
                    else
                    {
                        referenceKey = typeNamer(methodName);
                    }

                    responseType = response.Schema.GetBuilder(_swaggerModeler).BuildServiceType(referenceKey);
                    handled = true;
                }
            }

            return handled;
        }
Example #60
0
 /// <summary>
 ///     Returns a quoted string for the given language if applicable.
 /// </summary>
 /// <param name="defaultValue">Value to quote.</param>
 /// <param name="type">Data type.</param>
 public virtual string EscapeDefaultValue(string defaultValue, IModelType type)
 {
     return defaultValue;
 }