public void When_format_date_time_correct_then_validation_succeeds()
        {
            //// Arrange
            var schema = new JsonSchema4();
            schema.Type = JsonObjectType.String;
            schema.Format = JsonFormatStrings.DateTime;

            var token = new JValue("2014-12-01 11:00:01");

            //// Act
            var errors = schema.Validate(token);

            //// Assert
            Assert.AreEqual(0, errors.Count());
        }
        public ClassTemplateModel(string typeName, CSharpGeneratorSettings settings, CSharpTypeResolver resolver, JsonSchema4 schema, IEnumerable<PropertyModel> properties)
        {
            _resolver = resolver;
            _schema = schema;
            _settings = settings;

            Class = typeName;
            Properties = properties;
        }
        public void When_adding_property_to_schema_then_parent_should_be_set()
        {
            //// Arrange
            var schema = new JsonSchema4();

            //// Act
            schema.Properties.Add("test", new JsonProperty());

            //// Assert
            Assert.IsTrue(schema.Properties.ContainsKey("test"));
            Assert.AreEqual(schema, schema.Properties["test"].ParentSchema);
        }
        public void When_integer_required_and_integer_provided_then_validation_succeeds()
        {
            //// Arrange
            var schema = new JsonSchema4();
            schema.Type = JsonObjectType.Integer;

            var token = new JValue(10);

            //// Act
            var errors = schema.Validate(token);

            //// Assert
            Assert.AreEqual(0, errors.Count());
        }
        public void When_boolean_required_but_string_provided_then_validation_fails()
        {
            //// Arrange
            var schema = new JsonSchema4();
            schema.Type = JsonObjectType.Boolean;

            var token = new JValue("foo");

            //// Act
            var errors = schema.Validate(token);

            //// Assert
            Assert.AreEqual(ValidationErrorKind.BooleanExpected, errors.First().Kind);
        }
Example #6
0
        public void When_format_ipv6_correct_then_validation_succeeds()
        {
            //// Arrange
            var schema = new JsonSchema4();
            schema.Type = JsonObjectType.String;
            schema.Format = JsonFormatStrings.IpV6;

            var token = new JValue("::1");

            //// Act
            var errors = schema.Validate(token);

            //// Assert
            Assert.AreEqual(0, errors.Count());
        }
        public void When_format_hostname_incorrect_then_validation_succeeds()
        {
            //// Arrange
            var schema = new JsonSchema4();
            schema.Type = JsonObjectType.String;
            schema.Format = JsonFormatStrings.Hostname;

            var token = new JValue("foo:bar");

            //// Act
            var errors = schema.Validate(token);

            //// Assert
            Assert.AreEqual(ValidationErrorKind.HostnameExpected, errors.First().Kind);
        }
        public void When_format_hostname_is_ip_then_validation_succeeds()
        {
            //// Arrange
            var schema = new JsonSchema4();
            schema.Type = JsonObjectType.String;
            schema.Format = JsonFormatStrings.Hostname;

            var token = new JValue("rsuter.com");

            //// Act
            var errors = schema.Validate(token);

            //// Assert
            Assert.AreEqual(0, errors.Count());
        }
Example #9
0
        public void When_format_ipv6_incorrect_then_validation_fails()
        {
            //// Arrange
            var schema = new JsonSchema4();
            schema.Type = JsonObjectType.String;
            schema.Format = JsonFormatStrings.IpV6;

            var token = new JValue("test");

            //// Act
            var errors = schema.Validate(token);

            //// Assert
            Assert.AreEqual(ValidationErrorKind.IpV6Expected, errors.First().Kind);
        }
        public void When_integer_minimum_does_not_match_then_it_should_fail()
        {
            //// Arrange
            var schema = new JsonSchema4();
            schema.Type = JsonObjectType.Integer;
            schema.Minimum = 2;

            var token = new JValue(1);

            //// Act
            var errors = schema.Validate(token);

            //// Assert
            Assert.AreEqual(ValidationErrorKind.NumberTooSmall, errors.First().Kind);
        }
Example #11
0
        public void When_format_guid_correct_then_validation_succeeds()
        {
            //// Arrange
            var schema = new JsonSchema4();
            schema.Type = JsonObjectType.String;
            schema.Format = JsonFormatStrings.Guid;

            var guid = Guid.NewGuid().ToString();
            var token = new JValue(guid);

            //// Act
            var errors = schema.Validate(token);

            //// Assert
            Assert.AreEqual(0, errors.Count());
        }
        public void Numeric_type_should_not_trigger_validation_if_has_byte_format()
        {
            //// Arrange
            var numericSchema = new JsonSchema4
                                {
                                    Type = JsonObjectType.Integer,
                                    Format = JsonFormatStrings.Byte
                                };

            var token = new JValue(1);

            //// Act
            var numericErrors = numericSchema.Validate(token);

            //// Assert
            Assert.AreEqual(0, numericErrors.Count);
        }
        public void When_optional_property_is_missing_then_it_should_succeed()
        {
            //// Arrange
            var schema = new JsonSchema4();
            schema.Type = JsonObjectType.Object;
            schema.Properties["Foo"] = new JsonProperty
            {
                IsRequired = false,
            };

            var token = new JObject();

            //// Act
            var errors = schema.Validate(token);

            //// Assert
            Assert.AreEqual(0, errors.Count());
        }
        public void Validation_should_fail_if_string_is_not_byte_formatted()
        {
            //// Arrange
            var schema = new JsonSchema4
                         {
                             Type = JsonObjectType.String,
                             Format = JsonFormatStrings.Byte
                         };

            var token = new JValue("invalid");

            //// Act
            var errors = schema.Validate(token);

            //// Assert
            Assert.AreEqual(1, errors.Count);
            Assert.AreEqual(ValidationErrorKind.Base64Expected, errors.Single().Kind);
        }
        public void Validation_should_succeed_if_string_is_base64_formatted_without_trailing_equals()
        {
            //// Arrange
            var schema = new JsonSchema4
                         {
                             Type = JsonObjectType.String,
                             Format = "base64"
                         };

            var value = Convert.ToBase64String(new byte[] { 1, 2, 3 });
            var token = new JValue(value);

            //// Act
            var errors = schema.Validate(token);

            //// Assert
            Assert.AreEqual(0, errors.Count);
        }
        private List<EnumerationEntry> GetEnumeration(JsonSchema4 schema)
        {
            var entries = new List<EnumerationEntry>();
            for (int i = 0; i < schema.Enumeration.Count; i++)
            {
                var value = schema.Enumeration.ElementAt(i);
                var name = schema.EnumerationNames.Count > i ?
                    schema.EnumerationNames.ElementAt(i) :
                    schema.Type == JsonObjectType.Integer ? "_" + value : value.ToString();

                entries.Add(new EnumerationEntry
                {
                    Value = schema.Type == JsonObjectType.Integer ? value.ToString() : "<any>\"" + value + "\"",
                    Name = ConversionUtilities.ConvertToUpperCamelCase(name, true)
                });
            }
            return entries;
        }
        public void When_array_item_are_valid_then_it_should_succeed()
        {
            //// Arrange
            var schema = new JsonSchema4();
            schema.Type = JsonObjectType.Array;
            schema.Item = new JsonSchema4();
            schema.Item.Type = JsonObjectType.String;

            var token = new JArray();
            token.Add(new JValue("Foo"));
            token.Add(new JValue("Bar"));

            //// Act
            var errors = schema.Validate(token);

            //// Assert
            Assert.AreEqual(0, errors.Count());
        }
        public void When_schema_has_extension_data_property_then_property_is_in_serialized_json()
        {
            //// Arrange
            var schema = new JsonSchema4();
            schema.ExtensionData = new Dictionary<string, object>
            {
                { "Test", 123 }
            };

            //// Act
            var json = schema.ToJson();

            //// Assert
            Assert.IsTrue(json.Contains(
            @"{
              ""$schema"": ""http://json-schema.org/draft-04/schema#"",
              ""Test"": 123
            }"));
        }
        public void When_min_items_does_not_match_then_it_should_fail()
        {
            //// Arrange
            var schema = new JsonSchema4();
            schema.Type = JsonObjectType.Array;
            schema.MinItems = 2;
            schema.Item = new JsonSchema4();
            schema.Item.Type = JsonObjectType.String;

            var token = new JArray();
            token.Add(new JValue("Foo"));

            //// Act
            var errors = schema.Validate(token);

            //// Assert
            Assert.AreEqual(1, errors.Count());
            Assert.AreEqual(ValidationErrorKind.TooFewItems, errors.First().Kind);
        }
        public void When_property_matches_one_of_the_types_then_it_should_succeed()
        {
            //// Arrange
            var schema = new JsonSchema4();
            schema.Type = JsonObjectType.Object;
            schema.Properties["Foo"] = new JsonProperty
            {
                Type = JsonObjectType.Number | JsonObjectType.Null
            };

            var token = new JObject();
            token["Foo"] = new JValue(5);

            //// Act
            var errors = schema.Validate(token);

            //// Assert
            Assert.AreEqual(0, errors.Count());
        }
        public void When_object_is_in_property_then_path_should_be_built_correctly()
        {
            //// Arrange
            var objectToSearch = new JsonSchema4();
            var obj = new
            {
                Property = new
                {
                    Property1 = new { },
                    Property2 = objectToSearch
                }
            };

            //// Act
            var path = JsonPathUtilities.GetJsonPath(obj, objectToSearch);

            //// Assert
            Assert.AreEqual("#/Property/Property2", path);
        }
        public void When_string_property_is_available_then_it_should_succeed()
        {
            //// Arrange
            var schema = new JsonSchema4();
            schema.Type = JsonObjectType.Object;
            schema.Properties["Foo"] = new JsonProperty
            {
                IsRequired = true,
                Type = JsonObjectType.String
            };

            var token = new JObject();
            token["Foo"] = new JValue("Bar");

            //// Act
            var errors = schema.Validate(token);

            //// Assert
            Assert.AreEqual(0, errors.Count());
        }
        public void When_is_not_all_of_then_it_should_fail()
        {
            //// Arrange
            var schema = new JsonSchema4();
            schema.AllOf.Add(new JsonSchema4
            {
                Type = JsonObjectType.String
            });
            schema.AllOf.Add(new JsonSchema4
            {
                Type = JsonObjectType.Integer
            });

            var token = new JValue(5);

            //// Act
            var errors = schema.Validate(token);

            //// Assert
            Assert.AreEqual(ValidationErrorKind.NotAllOf, errors.First().Kind);
        }
        public void When_required_property_is_missing_then_it_should_be_in_error_list()
        {
            //// Arrange
            var schema = new JsonSchema4();
            schema.Type = JsonObjectType.Object;
            schema.Properties["Foo"] = new JsonProperty
            {
                IsRequired = true,
            };

            var token = new JObject();

            //// Act
            var errors = schema.Validate(token);

            //// Assert
            Assert.AreEqual(1, errors.Count());
            Assert.AreEqual("Foo", errors.First().Property);
            Assert.AreEqual("Foo", errors.First().Path);
            Assert.AreEqual(ValidationErrorKind.PropertyRequired, errors.First().Kind);
        }
        public void When_is_any_of_then_it_should_succeed()
        {
            //// Arrange
            var schema = new JsonSchema4();
            schema.AnyOf.Add(new JsonSchema4
            {
                Type = JsonObjectType.String
            });
            schema.AnyOf.Add(new JsonSchema4
            {
                Type = JsonObjectType.Integer
            });

            var token = new JValue(10);

            //// Act
            var errors = schema.Validate(token);

            //// Assert
            Assert.AreEqual(0, errors.Count);
        }
        public void When_string_property_required_but_integer_provided_then_it_should_fail()
        {
            //// Arrange
            var schema = new JsonSchema4();
            schema.Type = JsonObjectType.Object;
            schema.Properties["Foo"] = new JsonProperty
            {
                IsRequired = true,
                Type = JsonObjectType.String
            };

            var token = new JObject();
            token["Foo"] = new JValue(10);

            //// Act
            var errors = schema.Validate(token);

            //// Assert
            Assert.AreEqual(ValidationErrorKind.StringExpected, errors.First().Kind);
            Assert.AreEqual("Foo", errors.First().Property);
            Assert.AreEqual("Foo", errors.First().Path);
        }
        public void When_object_is_in_list_then_path_should_be_built_correctly()
        {
            //// Arrange
            var objectToSearch = new JsonSchema4();
            var obj = new
            {
                Property = new
                {
                    List = new List<object>
                    {
                        new { },
                        new { },
                        objectToSearch
                    }
                }
            };

            //// Act
            var foundObject = JsonPathUtilities.GetObjectFromJsonPath(obj, "#/Property/List/2");

            //// Assert
            Assert.AreEqual(foundObject, objectToSearch);
        }
        public void When_object_is_in_dictionary_then_path_should_be_built_correctly()
        {
            //// Arrange
            var objectToSearch = new JsonSchema4();
            var obj = new
            {
                Property = new
                {
                    List = new Dictionary<string, object>
                    {
                        { "Test1", new { } },
                        { "Test2", new { } },
                        { "Test3", objectToSearch },
                    }
                }
            };

            //// Act
            var path = JsonPathUtilities.GetJsonPath(obj, objectToSearch);

            //// Assert
            Assert.AreEqual("#/Property/List/Test3", path);
        }
        public void When_second_item_validation_fails_then_path_should_be_correct()
        {
            //// Arrange
            var schema = new JsonSchema4();
            schema.Type = JsonObjectType.Array;
            schema.Item = new JsonSchema4();
            schema.Item.Type = JsonObjectType.String;

            var token = new JArray();
            token.Add(new JValue("Foo"));
            token.Add(new JValue(10));

            //// Act
            var errors = schema.Validate(token);

            //// Assert
            Assert.AreEqual(1, errors.Count());
            Assert.AreEqual(ValidationErrorKind.ArrayItemNotValid, errors.First().Kind);

            var firstItemError = ((ChildSchemaValidationError) errors.First()).Errors.First().Value.First();
            Assert.AreEqual(ValidationErrorKind.StringExpected, firstItemError.Kind);
            Assert.AreEqual("[1]", errors.First().Property);
            Assert.AreEqual("[1]", errors.First().Path);
        }
Example #30
0
 /// <summary>Initializes a new instance of the <see cref="CSharpTypeResolver"/> class.</summary>
 /// <param name="settings">The generator settings.</param>
 /// <param name="exceptionSchema">The exception type schema.</param>
 public CSharpTypeResolver(CSharpGeneratorSettings settings, JsonSchema4 exceptionSchema)
     : base(settings)
 {
     Settings        = settings;
     ExceptionSchema = exceptionSchema;
 }
Example #31
0
 /// <summary>Resolves and possibly generates the specified schema.</summary>
 /// <param name="schema">The schema.</param>
 /// <param name="isNullable">Specifies whether the given type usage is nullable.</param>
 /// <param name="typeNameHint">The type name hint to use when generating the type and the type name is missing.</param>
 /// <returns>The type name.</returns>
 public override string Resolve(JsonSchema4 schema, bool isNullable, string typeNameHint)
 {
     return(Resolve(schema, isNullable, typeNameHint, true));
 }
Example #32
0
 /// <summary>Initializes a new instance of the <see cref="CSharpResponseModel"/> class.</summary>
 /// <param name="operationModel">The operation model.</param>
 /// <param name="statusCode">The status code.</param>
 /// <param name="response">The response.</param>
 /// <param name="isPrimarySuccessResponse">Specifies whether this is the success response.</param>
 /// <param name="exceptionSchema">The exception schema.</param>
 /// <param name="generator">The client generator.</param>
 /// <param name="resolver">The resolver.</param>
 /// <param name="settings">The settings.</param>
 public CSharpResponseModel(IOperationModel operationModel, string statusCode, SwaggerResponse response,
                            bool isPrimarySuccessResponse, JsonSchema4 exceptionSchema, IClientGenerator generator, TypeResolverBase resolver, CodeGeneratorSettingsBase settings)
     : base(operationModel, statusCode, response, isPrimarySuccessResponse, exceptionSchema, resolver, settings, generator)
 {
 }
Example #33
0
 /// <summary>Initializes a new instance of the <see cref="EnumTemplateModel" /> class.</summary>
 /// <param name="typeName">Name of the type.</param>
 /// <param name="schema">The schema.</param>
 /// <param name="settings">The settings.</param>
 public EnumTemplateModel(string typeName, JsonSchema4 schema, TypeScriptGeneratorSettings settings)
 {
     _schema   = schema;
     _settings = settings;
     Name      = typeName;
 }
Example #34
0
 /// <summary>Gets a value indicating whether the schema supports constructor conversion.</summary>
 /// <param name="schema">The schema.</param>
 /// <returns>The result.</returns>
 public bool SupportsConstructorConversion(JsonSchema4 schema)
 {
     return(schema?.ActualSchema.BaseDiscriminator == null);
 }
Example #35
0
        private JsonSchema4 CreateAndAddSchema(Type type, bool mayBeNull, IEnumerable <Attribute> parentAttributes,
                                               ISchemaResolver schemaResolver, ISchemaDefinitionAppender schemaDefinitionAppender)
        {
            if (type.Name == "Task`1")
            {
                type = type.GenericTypeArguments[0];
            }

            if (type.Name == "JsonResult`1")
            {
                type = type.GenericTypeArguments[0];
            }

            if (IsFileResponse(type))
            {
                return new JsonSchema4 {
                           Type = JsonObjectType.File
                }
            }
            ;

            var typeDescription = JsonObjectTypeDescription.FromType(type, parentAttributes, Settings.DefaultEnumHandling);

            if (typeDescription.Type.HasFlag(JsonObjectType.Object) && !typeDescription.IsDictionary)
            {
                if (type == typeof(object))
                {
                    return(new JsonSchema4
                    {
                        // IsNullable is directly set on SwaggerParameter or SwaggerResponse
                        Type = Settings.NullHandling == NullHandling.JsonSchema ? JsonObjectType.Object | JsonObjectType.Null : JsonObjectType.Object,
                        AllowAdditionalProperties = false
                    });
                }

                if (!schemaResolver.HasSchema(type, false))
                {
                    _schemaGenerator.Generate(type, schemaResolver, schemaDefinitionAppender);
                }

                if (mayBeNull)
                {
                    if (Settings.NullHandling == NullHandling.JsonSchema)
                    {
                        var schema = new JsonSchema4();
                        schema.OneOf.Add(new JsonSchema4 {
                            Type = JsonObjectType.Null
                        });
                        schema.OneOf.Add(new JsonSchema4 {
                            SchemaReference = schemaResolver.GetSchema(type, false)
                        });
                        return(schema);
                    }
                    else
                    {
                        // IsNullable is directly set on SwaggerParameter or SwaggerResponse
                        return(new JsonSchema4 {
                            SchemaReference = schemaResolver.GetSchema(type, false)
                        });
                    }
                }
                else
                {
                    return new JsonSchema4 {
                               SchemaReference = schemaResolver.GetSchema(type, false)
                    }
                };
            }

            if (typeDescription.Type.HasFlag(JsonObjectType.Array))
            {
                var itemType = type.GenericTypeArguments.Length == 0 ? type.GetElementType() : type.GenericTypeArguments[0];
                return(new JsonSchema4
                {
                    // IsNullable is directly set on SwaggerParameter or SwaggerResponse
                    Type = Settings.NullHandling == NullHandling.JsonSchema ? JsonObjectType.Array | JsonObjectType.Null : JsonObjectType.Array,
                    Item = CreateAndAddSchema(itemType, false, null, schemaResolver, schemaDefinitionAppender)
                });
            }

            return(_schemaGenerator.Generate(type, schemaResolver, schemaDefinitionAppender));
        }
    }
}
Example #36
0
 /// <summary>Resolves and possibly generates the specified schema.</summary>
 /// <param name="schema">The schema.</param>
 /// <param name="isNullable">Specifies whether the given type usage is nullable.</param>
 /// <param name="typeNameHint">The type name hint to use when generating the type and the type name is missing.</param>
 /// <returns>The type name.</returns>
 public abstract string Resolve(JsonSchema4 schema, bool isNullable, string typeNameHint);
 /// <summary>Creates the response model.</summary>
 /// <param name="statusCode">The status code.</param>
 /// <param name="response">The response.</param>
 /// <param name="exceptionSchema">The exception schema.</param>
 /// <param name="generator">The generator.</param>
 /// <param name="settings">The settings.</param>
 /// <returns></returns>
 protected override TypeScriptResponseModel CreateResponseModel(string statusCode, SwaggerResponse response,
                                                                JsonSchema4 exceptionSchema, IClientGenerator generator, ClientGeneratorBaseSettings settings)
 {
     return(new TypeScriptResponseModel(this, statusCode, response, response == GetSuccessResponse(),
                                        exceptionSchema, generator, (SwaggerToTypeScriptClientGeneratorSettings)settings));
 }
Example #38
0
 /// <summary>Checks whether the given schema generates a new type (e.g. class, enum, class with dictionary inheritance, etc.)
 /// or is an inline type (e.g. string, number, etc.). Warning: Enum will also return true.</summary>
 /// <param name="schema"></param>
 /// <returns></returns>
 public bool GeneratesType(JsonSchema4 schema)
 {
     schema = GetResolvableSchema(schema);
     return(schema.HasReference || (schema.IsObject && !schema.IsDictionary && !schema.IsAnyType));
 }
Example #39
0
 /// <summary>Tries to resolve the schema and returns null if there was a problem.</summary>
 /// <param name="schema">The schema.</param>
 /// <param name="typeNameHint">The type name hint.</param>
 /// <returns>The type name.</returns>
 public string TryResolve(JsonSchema4 schema, string typeNameHint)
 {
     return(schema != null?Resolve(schema, false, typeNameHint) : null);
 }
Example #40
0
        /// <summary>Resolves and possibly generates the specified schema.</summary>
        /// <param name="schema">The schema.</param>
        /// <param name="isRequired">Specifies whether the given type usage is required.</param>
        /// <param name="typeNameHint">The type name hint to use when generating the type and the type name is missing.</param>
        /// <returns>The type name.</returns>
        public override string Resolve(JsonSchema4 schema, bool isRequired, string typeNameHint)
        {
            schema = schema.ActualSchema;

            var type = schema.Type;

            if (type.HasFlag(JsonObjectType.Array))
            {
                var property = schema;
                if (property.Item != null)
                {
                    return(string.Format(Settings.ArrayType + "<{0}>", Resolve(property.Item, true, null)));
                }

                throw new NotImplementedException("Array with multiple Items schemes are not supported.");
            }

            if (type.HasFlag(JsonObjectType.Number))
            {
                return(isRequired ? "decimal" : "decimal?");
            }

            if (type.HasFlag(JsonObjectType.Integer))
            {
                if (schema.IsEnumeration)
                {
                    return(AddGenerator(schema, typeNameHint));
                }

                if (schema.Format == JsonFormatStrings.Byte)
                {
                    return(isRequired ? "byte" : "byte?");
                }

                return(isRequired ? "long" : "long?");
            }

            if (type.HasFlag(JsonObjectType.Boolean))
            {
                return(isRequired ? "bool" : "bool?");
            }

            if (type.HasFlag(JsonObjectType.String))
            {
                if (schema.Format == JsonFormatStrings.DateTime)
                {
                    return(isRequired ? Settings.DateTimeType : Settings.DateTimeType + "?");
                }

                if (schema.Format == JsonFormatStrings.TimeSpan)
                {
                    return(isRequired ? "TimeSpan" : "TimeSpan?");
                }

                if (schema.Format == JsonFormatStrings.Guid)
                {
                    return(isRequired ? "Guid" : "Guid?");
                }

                if (schema.Format == JsonFormatStrings.Base64)
                {
                    return("byte[]");
                }

                if (schema.IsEnumeration)
                {
                    return(AddGenerator(schema, typeNameHint));
                }

                return("string");
            }

            if (type.HasFlag(JsonObjectType.Object))
            {
                if (schema.IsAnyType)
                {
                    return("object");
                }

                if (schema.IsDictionary)
                {
                    return(string.Format(Settings.DictionaryType + "<string, {0}>", Resolve(schema.AdditionalPropertiesSchema, true, null)));
                }

                return(AddGenerator(schema, typeNameHint));
            }

            throw new NotImplementedException("Type not supported");
        }
Example #41
0
 /// <summary>Creates a type generator.</summary>
 /// <param name="schema">The schema.</param>
 /// <returns>The generator.</returns>
 protected override CSharpGenerator CreateTypeGenerator(JsonSchema4 schema)
 {
     return(new CSharpGenerator(schema, Settings, this));
 }
Example #42
0
        public static void AddResponse(this SwaggerOperation operation, string statusCode, string description, JsonSchema4 schema = null)
        {
            var response = new SwaggerResponse {
                Description = description, Schema = schema
            };

            operation.Responses.Add(statusCode, response);
        }
Example #43
0
        /// <summary>Resolves and possibly generates the specified schema.</summary>
        /// <param name="schema">The schema.</param>
        /// <param name="isNullable">Specifies whether the given type usage is nullable.</param>
        /// <param name="typeNameHint">The type name hint to use when generating the type and the type name is missing.</param>
        /// <param name="checkForExistingSchema">Checks whether a named schema is already registered.</param>
        /// <returns>The type name.</returns>
        public string Resolve(JsonSchema4 schema, bool isNullable, string typeNameHint, bool checkForExistingSchema)
        {
            if (schema == null)
            {
                throw new ArgumentNullException(nameof(schema));
            }

            schema = GetResolvableSchema(schema);

            if (schema == ExceptionSchema)
            {
                return("System.Exception");
            }

            if (schema.ActualTypeSchema.IsAnyType)
            {
                return("object");
            }

            var type = schema.Type;

            if (type == JsonObjectType.None && schema.IsEnumeration)
            {
                type = schema.Enumeration.All(v => v is int) ?
                       JsonObjectType.Integer :
                       JsonObjectType.String;
            }

            if (type.HasFlag(JsonObjectType.Number))
            {
                return(ResolveNumber(schema, isNullable));
            }

            if (type.HasFlag(JsonObjectType.Integer))
            {
                return(ResolveInteger(schema, isNullable, typeNameHint));
            }

            if (type.HasFlag(JsonObjectType.Boolean))
            {
                return(ResolveBoolean(isNullable));
            }

            if (type.HasFlag(JsonObjectType.String))
            {
                return(ResolveString(schema, isNullable, typeNameHint));
            }

            if (Types.ContainsKey(schema) && checkForExistingSchema)
            {
                return(Types[schema]);
            }

            if (type.HasFlag(JsonObjectType.Array))
            {
                return(ResolveArrayOrTuple(schema));
            }

            if (type.HasFlag(JsonObjectType.File))
            {
                return("byte[]");
            }

            if (schema.IsDictionary)
            {
                return(ResolveDictionary(schema));
            }

            return(GetOrGenerateTypeName(schema, typeNameHint));
        }
Example #44
0
 /// <summary>Initializes a new instance of the <see cref="TypeScriptGenerator"/> class.</summary>
 /// <param name="schema">The schema.</param>
 public TypeScriptGenerator(JsonSchema4 schema)
     : this(schema, new TypeScriptGeneratorSettings())
 {
 }
Example #45
0
 /// <summary>Creates the response model.</summary>
 /// <param name="operation">The operation.</param>
 /// <param name="statusCode">The status code.</param>
 /// <param name="response">The response.</param>
 /// <param name="exceptionSchema">The exception schema.</param>
 /// <param name="generator">The generator.</param>
 /// <param name="resolver">The resolver.</param>
 /// <param name="settings">The settings.</param>
 /// <returns>The response model.</returns>
 protected abstract TResponseModel CreateResponseModel(SwaggerOperation operation, string statusCode, SwaggerResponse response, JsonSchema4 exceptionSchema, IClientGenerator generator,
                                                       TypeResolverBase resolver, ClientGeneratorBaseSettings settings);
Example #46
0
        private string Resolve(JsonSchema4 schema, string typeNameHint, bool addInterfacePrefix)
        {
            if (schema == null)
            {
                throw new ArgumentNullException(nameof(schema));
            }

            schema = schema.ActualSchema;

            if (schema.IsAnyType)
            {
                return("any");
            }

            var type = schema.Type;

            if (type == JsonObjectType.None && schema.IsEnumeration)
            {
                type = schema.Enumeration.All(v => v is int) ?
                       JsonObjectType.Integer :
                       JsonObjectType.String;
            }

            if (type.HasFlag(JsonObjectType.Array))
            {
                return(ResolveArrayOrTuple(schema, typeNameHint, addInterfacePrefix));
            }

            if (type.HasFlag(JsonObjectType.Number))
            {
                return("number");
            }

            if (type.HasFlag(JsonObjectType.Integer))
            {
                return(ResolveInteger(schema, typeNameHint));
            }

            if (type.HasFlag(JsonObjectType.Boolean))
            {
                return("boolean");
            }

            if (type.HasFlag(JsonObjectType.String))
            {
                return(ResolveString(schema, typeNameHint));
            }

            if (type.HasFlag(JsonObjectType.File))
            {
                return("any");
            }

            if (schema.IsDictionary)
            {
                var prefix = addInterfacePrefix &&
                             SupportsConstructorConversion(schema.AdditionalPropertiesSchema) &&
                             schema.AdditionalPropertiesSchema?.ActualSchema.Type.HasFlag(JsonObjectType.Object) == true ? "I" : "";
                var valueType = prefix + ResolveDictionaryValueType(schema, "any", Settings.SchemaType);
                return($"{{ [key: string] : {valueType}; }}");
            }

            return((addInterfacePrefix && SupportsConstructorConversion(schema) ? "I" : "") +
                   base.GetOrGenerateTypeName(schema, typeNameHint));
        }
Example #47
0
 /// <summary>Creates the response model.</summary>
 /// <param name="statusCode">The status code.</param>
 /// <param name="response">The response.</param>
 /// <param name="exceptionSchema">The exception schema.</param>
 /// <param name="generator">The generator.</param>
 /// <param name="settings">The settings.</param>
 /// <returns></returns>
 protected override CSharpResponseModel CreateResponseModel(string statusCode, SwaggerResponse response, JsonSchema4 exceptionSchema, IClientGenerator generator, ClientGeneratorBaseSettings settings)
 {
     return(new CSharpResponseModel(statusCode, response, response == GetSuccessResponse(), exceptionSchema, generator, settings.CodeGeneratorSettings));
 }
        /// <summary>Generates a <see cref="JsonSchema4" /> object for the given type and adds the mapping to the given resolver.</summary>
        /// <param name="type">The type.</param>
        /// <param name="parentAttributes">The parent property or parameter attributes.</param>
        /// <param name="schemaResolver"></param>
        /// <param name="schemaDefinitionAppender"></param>
        /// <returns>The schema.</returns>
        /// <exception cref="InvalidOperationException">Could not find value type of dictionary type.</exception>
        public virtual TSchemaType Generate <TSchemaType>(Type type, IEnumerable <Attribute> parentAttributes,
                                                          ISchemaResolver schemaResolver, ISchemaDefinitionAppender schemaDefinitionAppender)
            where TSchemaType : JsonSchema4, new()
        {
            var schema = HandleSpecialTypes <TSchemaType>(type, schemaResolver);

            if (schema != null)
            {
                return(schema);
            }

            schema = new TSchemaType();

            if (schemaDefinitionAppender.RootObject == null)
            {
                schemaDefinitionAppender.RootObject = schema;
            }

            ApplyExtensionDataAttributes(schema, type, parentAttributes);

            var typeDescription = JsonObjectTypeDescription.FromType(type, parentAttributes, Settings.DefaultEnumHandling);

            if (typeDescription.Type.HasFlag(JsonObjectType.Object))
            {
                if (typeDescription.IsDictionary)
                {
                    typeDescription.ApplyType(schema);
                    GenerateDictionary(type, schema, schemaResolver, schemaDefinitionAppender);
                }
                else
                {
                    if (schemaResolver.HasSchema(type, false))
                    {
                        schema.SchemaReference = schemaResolver.GetSchema(type, false);
                        return(schema);
                    }

                    if (schema.GetType() == typeof(JsonSchema4))
                    {
                        typeDescription.ApplyType(schema);

                        schema.TypeNameRaw = ReflectionExtensions.GetSafeTypeName(type);
                        schema.Description = GetDescription(type.GetTypeInfo(), type.GetTypeInfo().GetCustomAttributes());

                        GenerateObject(type, schema, schemaResolver, schemaDefinitionAppender);
                    }
                    else
                    {
                        schema.SchemaReference = Generate <JsonSchema4>(type, parentAttributes, schemaResolver, schemaDefinitionAppender);
                        return(schema);
                    }
                }
            }
            else if (type.GetTypeInfo().IsEnum)
            {
                var isIntegerEnumeration = typeDescription.Type == JsonObjectType.Integer;
                if (schemaResolver.HasSchema(type, isIntegerEnumeration))
                {
                    schema.SchemaReference = schemaResolver.GetSchema(type, isIntegerEnumeration);
                    return(schema);
                }

                if (schema.GetType() == typeof(JsonSchema4))
                {
                    LoadEnumerations(type, schema, typeDescription);

                    typeDescription.ApplyType(schema);

                    schema.TypeNameRaw = ReflectionExtensions.GetSafeTypeName(type);
                    schema.Description = type.GetXmlSummary();

                    schemaResolver.AddSchema(type, isIntegerEnumeration, schema);
                }
                else
                {
                    schema.SchemaReference = Generate <JsonSchema4>(type, parentAttributes, schemaResolver, schemaDefinitionAppender);
                    return(schema);
                }
            }
            else if (typeDescription.Type.HasFlag(JsonObjectType.Array))
            {
                typeDescription.ApplyType(schema);

                var itemType = type.GetEnumerableItemType();
                if (itemType == null)
                {
                    var jsonSchemaAttribute = type.GetTypeInfo().GetCustomAttribute <JsonSchemaAttribute>();
                    if (jsonSchemaAttribute?.ArrayItem != null)
                    {
                        schema.Item = Generate(jsonSchemaAttribute.ArrayItem, schemaResolver, schemaDefinitionAppender);
                    }
                    else
                    {
                        schema.Item = JsonSchema4.CreateAnySchema();
                    }
                }
                else
                {
                    schema.Item = Generate(itemType, schemaResolver, schemaDefinitionAppender);
                }
            }
            else
            {
                typeDescription.ApplyType(schema);
            }

            return(schema);
        }
Example #49
0
 /// <summary>Resolves and possibly generates the specified schema. Returns the type name with a 'I' prefix if the feature is supported for the given schema.</summary>
 /// <param name="schema">The schema.</param>
 /// <param name="isNullable">Specifies whether the given type usage is nullable.</param>
 /// <param name="typeNameHint">The type name hint to use when generating the type and the type name is missing.</param>
 /// <returns>The type name.</returns>
 /// <exception cref="ArgumentNullException"><paramref name="schema"/> is <see langword="null" />.</exception>
 public string ResolveConstructorInterfaceName(JsonSchema4 schema, bool isNullable, string typeNameHint)
 {
     return(Resolve(schema, typeNameHint, true));
 }
Example #50
0
        private ObservableList <AppModelParameter> GenerateXMLBody(ApplicationAPIModel aAM, JsonSchema4 operation)
        {
            string SampleBody = JsonSchemaTools.JsonSchemaFaker(operation, true);
            string XMlName    = operation.HasReference? XMlName = operation.Reference.Xml.Name: XMlName = operation.Xml.Name;



            SampleBody = "{\"" + XMlName + "\":" + SampleBody + "}";
            string s2       = SampleBody;
            string xmlbody  = JsonConvert.DeserializeXmlNode(SampleBody).OuterXml;
            string temppath = System.IO.Path.GetTempFileName();

            File.WriteAllText(temppath, xmlbody);
            XMLTemplateParser   XTp = new XMLTemplateParser();
            ApplicationAPIModel aam = XTp.ParseDocument(temppath).ElementAt(0);

            object[] BodyandModelParameters = JSONTemplateParser.GenerateBodyANdModelParameters(SampleBody);
            aAM.RequestBody     = aam.RequestBody;
            aAM.RequestBodyType = ApplicationAPIUtils.eRequestBodyType.FreeText;
            aam.ContentType     = ApplicationAPIUtils.eContentType.XML;
            return(aam.AppModelParameters);
        }
Example #51
0
        private JsonNode createJsonFromSchema(JsonSchema4 schema)
        {
            // TODO: more comprehensive schema stuff like default values

            JsonObjectType type      = schema.Type;
            int            typeFlags = (int)type;

            if (type.HasFlag(JsonObjectType.Boolean))
            {
                return(new JsonNode(false, NodeType.Boolean, new JValue(false), schema));
            }
            if (type.HasFlag(JsonObjectType.Integer))
            {
                return(new JsonNode(0, NodeType.Integer, new JValue(0L), schema));
            }
            if (type.HasFlag(JsonObjectType.Number))
            {
                return(new JsonNode(0, NodeType.Number, new JValue(0F), schema));
            }
            if (type.HasFlag(JsonObjectType.Null))
            {
                return(new JsonNode(null, NodeType.Null, new JValue(new object()), schema));
            }

            if (type.HasFlag(JsonObjectType.String))
            {
                return(new JsonNode("", NodeType.String, new JValue(""), schema));
            }

            if (type.HasFlag(JsonObjectType.Array))
            {
                // TODO: "contains" keyword
                // TODO: "minItems" "maxItems" keyword
                // TODO: "uniqueItems" keyword

                List <JsonNode> array = new List <JsonNode>();
                if (schema.Items.Count == 1)
                {
                    array.Add(createJsonFromSchema(schema.Item));
                }
                else
                {
                    array.AddRange(schema.Items.Select(createJsonFromSchema));
                }

                return(new JsonNode(array, NodeType.Array, new JArray(array), schema));
            }

            if (type.HasFlag(JsonObjectType.Object))
            {
                // TODO: "minProperties" keyword

                Dictionary <string, JsonNode> obj = new Dictionary <string, JsonNode>();

                foreach (KeyValuePair <string, JsonProperty> property in schema.Properties)
                {
                    obj[property.Key] = createJsonFromSchema(property.Value);
                }

                return(new JsonNode(obj, NodeType.Object, new JObject(obj), schema));
            }

            return(new JsonNode(null, NodeType.Null, new JValue(new object()), schema));
        }
Example #52
0
        private ObservableList <AppModelParameter> GenerateJsonBody(ApplicationAPIModel aAM, JsonSchema4 operation)
        {
            string SampleBody = JsonSchemaTools.JsonSchemaFaker(operation);

            object[] BodyandModelParameters = JSONTemplateParser.GenerateBodyANdModelParameters(SampleBody);
            aAM.RequestBody = (string)BodyandModelParameters[0];
            return((ObservableList <AppModelParameter>)BodyandModelParameters[1]);
        }
Example #53
0
 /// <summary>Removes a nullable oneOf reference if available.</summary>
 /// <param name="schema">The schema.</param>
 /// <returns>The actually resolvable schema</returns>
 public JsonSchema4 RemoveNullability(JsonSchema4 schema)
 {
     // TODO: Method on JsonSchema4?
     return(schema.OneOf.FirstOrDefault(o => !o.IsNullable(SchemaType.JsonSchema)) ?? schema);
 }
        private void LoadPropertyOrField(MemberInfo property, Type propertyType, Type parentType, JsonSchema4 parentSchema, ISchemaResolver schemaResolver, ISchemaDefinitionAppender schemaDefinitionAppender)
        {
            var attributes = property.GetCustomAttributes(inherit: true).OfType <Attribute>().ToArray();
            var propertyTypeDescription = JsonObjectTypeDescription.FromType(propertyType, attributes, Settings.DefaultEnumHandling);

            if (IsPropertyIgnored(parentType, attributes) == false)
            {
                JsonProperty jsonProperty;

                if (propertyType.Name == "Nullable`1")
#if !LEGACY
                { propertyType = propertyType.GenericTypeArguments[0]; }
#else
                { propertyType = propertyType.GetGenericArguments()[0]; }
#endif

                var requiresSchemaReference = RequiresSchemaReference(propertyType, attributes);
                if (requiresSchemaReference)
                {
                    var propertySchema = Generate <JsonSchema4>(propertyType, attributes, schemaResolver, schemaDefinitionAppender);

                    // The schema is automatically added to Definitions if it is missing in JsonPathUtilities.GetJsonPath()
                    if (Settings.NullHandling == NullHandling.JsonSchema)
                    {
                        jsonProperty = new JsonProperty();
                        jsonProperty.OneOf.Add(new JsonSchema4
                        {
                            SchemaReference = propertySchema.ActualSchema
                        });
                    }
                    else
                    {
                        jsonProperty = new JsonProperty
                        {
                            SchemaReference = propertySchema.ActualSchema
                        };
                    }
                }
                else
                {
                    jsonProperty = Generate <JsonProperty>(propertyType, attributes, schemaResolver, schemaDefinitionAppender);
                }

                var propertyName = JsonPathUtilities.GetPropertyName(property, Settings.DefaultPropertyNameHandling);
                if (parentSchema.Properties.ContainsKey(propertyName))
                {
                    throw new InvalidOperationException("The JSON property '" + propertyName + "' is defined multiple times on type '" + parentType.FullName + "'.");
                }

                parentSchema.Properties.Add(propertyName, jsonProperty);

                var requiredAttribute     = attributes.TryGetIfAssignableTo("System.ComponentModel.DataAnnotations.RequiredAttribute");
                var jsonPropertyAttribute = attributes.OfType <JsonPropertyAttribute>().SingleOrDefault();

                var hasJsonNetAttributeRequired = jsonPropertyAttribute != null && (
                    jsonPropertyAttribute.Required == Required.Always ||
                    jsonPropertyAttribute.Required == Required.AllowNull);

                var isDataContractMemberRequired = GetDataMemberAttribute(parentType, attributes)?.IsRequired == true;

                var hasRequiredAttribute = requiredAttribute != null;
                if (hasRequiredAttribute || isDataContractMemberRequired || hasJsonNetAttributeRequired)
                {
                    parentSchema.RequiredProperties.Add(propertyName);
                }

                var isJsonNetAttributeNullable = jsonPropertyAttribute != null && jsonPropertyAttribute.Required == Required.AllowNull;

                var isNullable = !hasRequiredAttribute && !isDataContractMemberRequired && (propertyTypeDescription.IsNullable || isJsonNetAttributeNullable);
                if (isNullable)
                {
                    if (Settings.NullHandling == NullHandling.JsonSchema)
                    {
                        if (requiresSchemaReference)
                        {
                            jsonProperty.OneOf.Add(new JsonSchema4 {
                                Type = JsonObjectType.Null
                            });
                        }
                        else if (jsonProperty.Type == JsonObjectType.None)
                        {
                            jsonProperty.OneOf.Add(new JsonSchema4 {
                                Type = JsonObjectType.None
                            });
                            jsonProperty.OneOf.Add(new JsonSchema4 {
                                Type = JsonObjectType.Null
                            });
                        }
                        else
                        {
                            jsonProperty.Type = jsonProperty.Type | JsonObjectType.Null;
                        }
                    }
                }
                else if (Settings.NullHandling == NullHandling.Swagger)
                {
                    if (!parentSchema.RequiredProperties.Contains(propertyName))
                    {
                        parentSchema.RequiredProperties.Add(propertyName);
                    }
                }

                dynamic readOnlyAttribute = attributes.TryGetIfAssignableTo("System.ComponentModel.ReadOnlyAttribute");
                if (readOnlyAttribute != null)
                {
                    jsonProperty.IsReadOnly = readOnlyAttribute.IsReadOnly;
                }

                jsonProperty.Description = GetDescription(property, attributes);

                ApplyPropertyAnnotations(jsonProperty, parentType, attributes, propertyTypeDescription);
            }
        }
Example #55
0
 /// <summary>Gets the actual schema (i.e. when not referencing a type schema or it is inlined)
 /// and removes a nullable oneOf reference if available.</summary>
 /// <param name="schema">The schema.</param>
 /// <returns>The actually resolvable schema</returns>
 public JsonSchema4 GetResolvableSchema(JsonSchema4 schema)
 {
     schema = RemoveNullability(schema);
     return(IsDefinitionTypeSchema(schema.ActualSchema) ? schema : schema.ActualSchema);
 }
 public string Generate(JsonSchema4 schema, string typeNameHint, ICollection <string> reservedTypeNames)
 {
     return("MyCustomType" + ConversionUtilities.ConvertToUpperCamelCase(typeNameHint, true));
 }
        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            var presenter = (FrameworkElement)container;

            if (item is JsonObjectModel)
            {
                return((DataTemplate)presenter.Resources["RootTemplate"]);
            }

            JsonSchema4 schema = null;

            if (item is JsonTokenModel)
            {
                schema = ((JsonTokenModel)item).Schema;
            }

            if (item is JsonPropertyModel)
            {
                schema = ((JsonPropertyModel)item).Schema;
            }

            var type = schema.Type;

            if (type.HasFlag(JsonObjectType.String) && schema.Format == JsonFormatStrings.DateTime) // TODO: What to do with date/time?
            {
                return((DataTemplate)presenter.Resources["DateTimeTemplate"]);
            }
            if (type.HasFlag(JsonObjectType.String) && schema.Format == "date")
            {
                return((DataTemplate)presenter.Resources["DateTemplate"]);
            }
            if (type.HasFlag(JsonObjectType.String) && schema.Format == "time")
            {
                return((DataTemplate)presenter.Resources["TimeTemplate"]);
            }
            if (type.HasFlag(JsonObjectType.String) && schema.Enumeration.Count > 0)
            {
                return((DataTemplate)presenter.Resources["EnumTemplate"]);
            }
            if (type.HasFlag(JsonObjectType.String))
            {
                return((DataTemplate)presenter.Resources["StringTemplate"]);
            }

            if (type.HasFlag(JsonObjectType.Integer) && schema.Enumeration.Count > 0)
            {
                return((DataTemplate)presenter.Resources["EnumTemplate"]);
            }
            if (type.HasFlag(JsonObjectType.Integer))
            {
                return((DataTemplate)presenter.Resources["IntegerTemplate"]);
            }

            if (type.HasFlag(JsonObjectType.Number))
            {
                return((DataTemplate)presenter.Resources["NumberTemplate"]);
            }
            if (type.HasFlag(JsonObjectType.Boolean))
            {
                return((DataTemplate)presenter.Resources["BooleanTemplate"]);
            }
            if (type.HasFlag(JsonObjectType.Object))
            {
                return((DataTemplate)presenter.Resources["ObjectTemplate"]);
            }
            if (type.HasFlag(JsonObjectType.Array))
            {
                return((DataTemplate)presenter.Resources["ArrayTemplate"]);
            }

            return(base.SelectTemplate(item, container));
        }
        /// <summary>Applies the property annotations to the JSON property.</summary>
        /// <param name="jsonProperty">The JSON property.</param>
        /// <param name="parentType">The type of the parent.</param>
        /// <param name="attributes">The attributes.</param>
        /// <param name="propertyTypeDescription">The property type description.</param>
        public void ApplyPropertyAnnotations(JsonSchema4 jsonProperty, Type parentType, IList <Attribute> attributes,
                                             JsonObjectTypeDescription propertyTypeDescription)
        {
            // TODO: Refactor out

            dynamic displayAttribute = attributes.TryGetIfAssignableTo("System.ComponentModel.DataAnnotations.DisplayAttribute");

            if (displayAttribute != null && displayAttribute.Name != null)
            {
                jsonProperty.Title = displayAttribute.Name;
            }

            dynamic defaultValueAttribute = attributes.TryGetIfAssignableTo("System.ComponentModel.DefaultValueAttribute");

            if (defaultValueAttribute != null && defaultValueAttribute.Value != null)
            {
                jsonProperty.Default = ConvertDefaultValue(parentType, attributes, defaultValueAttribute);
            }

            dynamic regexAttribute = attributes.TryGetIfAssignableTo("System.ComponentModel.DataAnnotations.RegularExpressionAttribute");

            if (regexAttribute != null)
            {
                jsonProperty.Pattern = regexAttribute.Pattern;
            }

            if (propertyTypeDescription.Type == JsonObjectType.Number ||
                propertyTypeDescription.Type == JsonObjectType.Integer)
            {
                dynamic rangeAttribute = attributes.TryGetIfAssignableTo("System.ComponentModel.DataAnnotations.RangeAttribute");
                if (rangeAttribute != null)
                {
                    if (rangeAttribute.Minimum != null && rangeAttribute.Minimum > double.MinValue)
                    {
                        jsonProperty.Minimum = (decimal?)(double)rangeAttribute.Minimum;
                    }
                    if (rangeAttribute.Maximum != null && rangeAttribute.Maximum < double.MaxValue)
                    {
                        jsonProperty.Maximum = (decimal?)(double)rangeAttribute.Maximum;
                    }
                }

                var multipleOfAttribute = attributes.OfType <MultipleOfAttribute>().SingleOrDefault();
                if (multipleOfAttribute != null)
                {
                    jsonProperty.MultipleOf = multipleOfAttribute.MultipleOf;
                }
            }

            dynamic minLengthAttribute = attributes.TryGetIfAssignableTo("System.ComponentModel.DataAnnotations.MinLengthAttribute");

            if (minLengthAttribute != null && minLengthAttribute.Length != null)
            {
                if (propertyTypeDescription.Type == JsonObjectType.String)
                {
                    jsonProperty.MinLength = minLengthAttribute.Length;
                }
                else if (propertyTypeDescription.Type == JsonObjectType.Array)
                {
                    jsonProperty.MinItems = minLengthAttribute.Length;
                }
            }

            dynamic maxLengthAttribute = attributes.TryGetIfAssignableTo("System.ComponentModel.DataAnnotations.MaxLengthAttribute");

            if (maxLengthAttribute != null && maxLengthAttribute.Length != null)
            {
                if (propertyTypeDescription.Type == JsonObjectType.String)
                {
                    jsonProperty.MaxLength = maxLengthAttribute.Length;
                }
                else if (propertyTypeDescription.Type == JsonObjectType.Array)
                {
                    jsonProperty.MaxItems = maxLengthAttribute.Length;
                }
            }

            dynamic stringLengthAttribute = attributes.TryGetIfAssignableTo("System.ComponentModel.DataAnnotations.StringLengthAttribute");

            if (stringLengthAttribute != null)
            {
                if (propertyTypeDescription.Type == JsonObjectType.String)
                {
                    jsonProperty.MinLength = stringLengthAttribute.MinimumLength;
                    jsonProperty.MaxLength = stringLengthAttribute.MaximumLength;
                }
            }

            dynamic dataTypeAttribute = attributes.TryGetIfAssignableTo("System.ComponentModel.DataAnnotations.DataTypeAttribute");

            if (dataTypeAttribute != null)
            {
                var dataType = dataTypeAttribute.DataType.ToString();
                if (DataTypeFormats.ContainsKey(dataType))
                {
                    jsonProperty.Format = DataTypeFormats[dataType];
                }
            }
        }
 /// <summary>Initializes a new instance of the <see cref="TypeScriptGenerator"/> class.</summary>
 /// <param name="schema">The schema.</param>
 /// <param name="resolver">The resolver.</param>
 public TypeScriptGenerator(JsonSchema4 schema, TypeScriptTypeResolver resolver)
 {
     _schema = schema;
     _resolver = resolver;
 }
Example #60
0
        public static void AddBodyParameter(this SwaggerOperation operation, string name, JsonSchema4 schema, string description)
        {
            var parameter = new SwaggerParameter {
                Schema = schema, Name = name, Kind = SwaggerParameterKind.Body
            };

            if (!string.IsNullOrWhiteSpace(description))
            {
                parameter.Description = description;
            }

            parameter.IsRequired    = true;
            parameter.IsNullableRaw = false;

            operation.Parameters.Add(parameter);
        }