internal static JsonProperty FromJsonSchema(string name, JsonSchema4 type)
 {
     var data = JsonConvert.SerializeObject(type);
     var property = JsonConvert.DeserializeObject<JsonProperty>(data);
     property.Name = name;
     return property;
 }
        /// <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)
        {
            if (schema.ActualSchema == _exceptionSchema)
                return "Exception";

            return base.Resolve(schema, isRequired, typeNameHint);
        }
        /// <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)
        {
            if (schema.ActualSchema == ExceptionSchema)
                return "System.Exception";

            return base.Resolve(schema, isNullable, typeNameHint);
        }
 /// <summary>Creates a default <see cref="JsonObjectModel"/> from the given schema. </summary>
 /// <param name="schema">The <see cref="JsonSchema4"/>. </param>
 /// <returns>The <see cref="JsonObjectModel"/>. </returns>
 public static JsonObjectModel FromSchema(JsonSchema4 schema)
 {
     var obj = new JsonObjectModel();
     foreach (var property in schema.Properties)
     {
         if (property.Value.Type.HasFlag(JsonObjectType.Object))
         {
             if (property.Value.IsRequired)
                 obj[property.Key] = FromSchema(property.Value);
             else
                 obj[property.Key] = null;
         }
         else if (property.Value.Type.HasFlag(JsonObjectType.Array))
         {
             if (property.Value.IsRequired)
                 obj[property.Key] = new ObservableCollection<JsonTokenModel>();
             else
                 obj[property.Key] = null;
         }
         else
             obj[property.Key] = GetDefaultValue(property);
     }
     obj.Schema = schema;
     return obj;
 }
Example #5
0
 /// <summary>Appends the schema to the root object.</summary>
 /// <param name="schema">The schema to append.</param>
 /// <param name="typeNameHint">The type name hint.</param>
 public override void AppendSchema(JsonSchema4 schema, string typeNameHint)
 {
     if (!_document.Definitions.Values.Contains(schema))
     {
         var typeName = _typeNameGenerator.Generate(schema, typeNameHint, _document.Definitions.Keys);
         _document.Definitions[typeName] = schema;
     }
 }
 /// <summary>Creates a <see cref="JsonValueModel"/> from a <see cref="JValue"/> and a given schema. </summary>
 /// <param name="value">The value. </param>
 /// <param name="schema">The schema. </param>
 /// <returns>The <see cref="JsonValueModel"/>. </returns>
 public static JsonValueModel FromJson(JValue value, JsonSchema4 schema)
 {
     return new JsonValueModel
     {
         Schema = schema,
         Value = value.Value
     };
 }
Example #7
0
        /// <summary>Initializes a new instance of the <see cref="ResponseModel" /> class.</summary>
        /// <param name="response">The response.</param>
        /// <param name="exceptionSchema">The exception schema.</param>
        /// <param name="clientGeneratorBase">The client generator base.</param>
        public ResponseModel(KeyValuePair<string, SwaggerResponse> response, JsonSchema4 exceptionSchema, ClientGeneratorBase clientGeneratorBase)
        {
            _response = response.Value;
            _exceptionSchema = exceptionSchema;
            _clientGeneratorBase = clientGeneratorBase;

            StatusCode = response.Key;
        }
        internal override string GetType(JsonSchema4 schema, string typeNameHint)
        {
            if (schema == null)
                return "string";

            if (schema.ActualSchema.IsAnyType)
                return "object";

            return Resolver.Resolve(schema.ActualSchema, true, typeNameHint);
        }
Example #9
0
        /// <summary>Initializes a new instance of the <see cref="ClientTemplateModel" /> class.</summary>
        /// <param name="controllerName">Name of the controller.</param>
        /// <param name="controllerClassName">The class name of the controller.</param>
        /// <param name="operations">The operations.</param>
        /// <param name="document">The Swagger document.</param>
        /// <param name="exceptionSchema">The exception schema.</param>
        /// <param name="settings">The settings.</param>
        public ClientTemplateModel(string controllerName, string controllerClassName, IList<OperationModel> operations,
            SwaggerDocument document, JsonSchema4 exceptionSchema, SwaggerToCSharpClientGeneratorSettings settings)
        {
            _document = document;
            _exceptionSchema = exceptionSchema;
            _settings = settings;

            Class = controllerClassName;
            ExceptionClass = _settings.ExceptionClass.Replace("{controller}", controllerName);
            Operations = operations;
        }
        private ChildSchemaValidationError TryCreateChildSchemaError(JsonSchemaValidator validator, JsonSchema4 schema, JToken token, ValidationErrorKind errorKind, string property, string path)
        {
            var errors = validator.Validate(token, null, null);
            if (errors.Count == 0)
                return null;

            var errorDictionary = new Dictionary<JsonSchema4, ICollection<ValidationError>>();
            errorDictionary.Add(schema, errors);

            return new ChildSchemaValidationError(errorKind, property, path, errorDictionary);
        }
Example #11
0
        /// <summary>Adds a schema to type mapping.</summary>
        /// <param name="type">The type.</param>
        /// <param name="isIntegerEnumeration">Specifies whether the type is an integer enum.</param>
        /// <param name="schema">The schema.</param>
        /// <exception cref="InvalidOperationException">Added schema is not a JsonSchema4 instance.</exception>
        public void AddSchema(Type type, bool isIntegerEnumeration, JsonSchema4 schema)
        {
            if (schema.GetType() != typeof(JsonSchema4))
                throw new InvalidOperationException("Added schema is not a JsonSchema4 instance.");

            //#if DEBUG
            //            // TODO: (low-prio) Check code so that type names are unique
            //            if (Schemes.Any(s => s.TypeName == schema.TypeName))
            //                throw new InvalidOperationException("The type name '"+ schema.TypeName + "' is already registered in the schema resolver.");
            //#endif

            _mappings.Add(GetKey(type, isIntegerEnumeration), schema);
        }
        internal override string GetType(JsonSchema4 schema, string typeNameHint)
        {
            if (schema == null)
                return "void";

            if (schema.ActualSchema.Type == JsonObjectType.File)
                return "byte[]";

            if (schema.ActualSchema.IsAnyType)
                return "object";

            return Resolver.Resolve(schema.ActualSchema, true, typeNameHint);
        }
 private string GenJsonArrayProp(JsonSchema4 schema)
 {
     if (schema.Type== JsonObjectType.String)
     {
         return "\"string\"";
     }
     else if(schema.Type== JsonObjectType.None)
     {
         return ToSampleJson(schema.ActualSchema);
     }
     else
     {
         return "";
     }
 }
        public string ToSampleJson(JsonSchema4 jsonschemas)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("{");
            IList<string> json = new List<string>();
            foreach (var item in jsonschemas.Properties)
            {
                if (!item.Value.IsReadOnly)//readonly is not needed
                {
                    json.Add(GenJsonProperties(item.Value));
                }
                
            }
            builder.Append(string.Join("," , json));
            builder.Append("}");

            return builder.ToString();
        }
        /// <summary>Creates a <see cref="JsonObjectModel"/> from the given <see cref="JObject"/> and <see cref="JsonSchema4"/>. </summary>
        /// <param name="obj">The <see cref="JObject"/>. </param>
        /// <param name="schema">The <see cref="JsonSchema4"/>. </param>
        /// <returns>The <see cref="JsonObjectModel"/>. </returns>
        public static JsonObjectModel FromJson(JObject obj, JsonSchema4 schema)
        {
            var result = new JsonObjectModel();
            foreach (var property in schema.Properties)
            {
                if (property.Value.Type.HasFlag(JsonObjectType.Array))
                {
                    var propertySchema = property.Value.Item;
                    var objects = obj[property.Key].Select(o => o is JObject ?
                        (JsonTokenModel)FromJson((JObject)o, propertySchema) : JsonValueModel.FromJson((JValue)o, propertySchema));

                    var list = new ObservableCollection<JsonTokenModel>(objects);
                    foreach (var item in list)
                        item.ParentList = list;

                    result[property.Key] = list;
                }
                else if (property.Value.Type.HasFlag(JsonObjectType.Object))
                {
                    var token = obj[property.Key];
                    if (token is JObject)
                        result[property.Key] = FromJson((JObject)token, property.Value);
                    else
                        result[property.Key] = null;
                }
                else
                {
                    JToken value;
                    if (obj.TryGetValue(property.Key, out value))
                        result[property.Key] = ((JValue)value).Value;
                    else
                        result[property.Key] = GetDefaultValue(property);
                }
            }
            result.Schema = schema;
            return result;
        }
Example #16
0
        private ChildSchemaValidationError TryCreateChildSchemaError(JsonSchema4 schema, JToken token, ValidationErrorKind errorKind, string property, string path)
        {
            var validator = new JsonSchemaValidator(schema);

            return(TryCreateChildSchemaError(validator, schema, token, errorKind, property, path));
        }
Example #17
0
 /// <summary>Determines whether the given schema is the parent schema of this schema (i.e. super/base class).</summary>
 /// <param name="schema">The possible subtype schema.</param>
 /// <returns>true or false</returns>
 public bool Inherits(JsonSchema4 schema)
 {
     schema = schema.ActualSchema;
     return(InheritedSchemas.Any(s => s.ActualSchema == schema || s.Inherits(schema)));
 }
Example #18
0
        private ChildSchemaValidationError TryCreateChildSchemaError(JsonSchemaValidator validator, JsonSchema4 schema, JToken token, ValidationErrorKind errorKind, string property, string path)
        {
            var errors = validator.Validate(token, null, null);

            if (errors.Count == 0)
            {
                return(null);
            }

            var errorDictionary = new Dictionary <JsonSchema4, ICollection <ValidationError> >();

            errorDictionary.Add(schema, errors);

            return(new ChildSchemaValidationError(errorKind, property, path, errorDictionary));
        }
 private ChildSchemaValidationError TryCreateChildSchemaError(JsonSchema4 schema, JToken token, ValidationErrorKind errorKind, string property, string path)
 {
     var validator = new JsonSchemaValidator(schema);
     return TryCreateChildSchemaError(validator, schema, token, errorKind, property, path);
 }
 /// <summary>Sets the root object.</summary>
 /// <param name="rootObject">The root object.</param>
 public virtual void SetRootObject(object rootObject)
 {
     _rootSchema = (JsonSchema4)rootObject;
 }
Example #21
0
 /// <summary>Adds a schema to type mapping.</summary>
 /// <param name="type">The type.</param>
 /// <param name="schema">The schema.</param>
 public void AddSchema(Type type, JsonSchema4 schema)
 {
     _mappings.Add(type, schema);
 }
Example #22
0
 internal abstract string GetType(JsonSchema4 schema, bool isNullable, string typeNameHint);
 /// <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 SwaggerToCSharpTypeResolver(CSharpGeneratorSettings settings, JsonSchema4 exceptionSchema)
     : base(settings)
 {
     ExceptionSchema = exceptionSchema;
 }
        private string GetType(JsonSchema4 type, string typeNameHint)
        {
            if (type == null)
                return "any";

            return _resolver.Resolve(type.ActualSchema, true, typeNameHint);
        }
 /// <summary>Creates a <see cref="JsonObjectModel"/> from the given JSON data and <see cref="JsonSchema4"/>. </summary>
 /// <param name="jsonData">The JSON data. </param>
 /// <param name="schema">The <see cref="JsonSchema4"/>. </param>
 /// <returns>The <see cref="JsonObjectModel"/>. </returns>
 public static JsonObjectModel FromJson(string jsonData, JsonSchema4 schema)
 {
     var json = JsonConvert.DeserializeObject(jsonData);
     return FromJson((JObject)json, schema);
 }
Example #26
0
 /// <summary>Adds a document reference.</summary>
 /// <param name="documentPath">The document path.</param>
 /// <param name="schema">The referenced schema.</param>
 public void AddDocumentReference(string documentPath, JsonSchema4 schema)
 {
     _resolvedSchemas[documentPath] = schema;
 }
 /// <summary>Resolves a file reference.</summary>
 /// <param name="filePath">The file path.</param>
 /// <returns>The resolved JSON Schema.</returns>
 /// <exception cref="NotSupportedException">The System.IO.File API is not available on this platform.</exception>
 public virtual async Task <IJsonReference> ResolveFileReferenceAsync(string filePath)
 {
     return(await JsonSchema4.FromFileAsync(filePath, schema => this).ConfigureAwait(false));
 }
 /// <summary>Resolves an URL reference.</summary>
 /// <param name="url">The URL.</param>
 /// <exception cref="NotSupportedException">The HttpClient.GetAsync API is not available on this platform.</exception>
 public virtual async Task <IJsonReference> ResolveUrlReferenceAsync(string url)
 {
     return(await JsonSchema4.FromUrlAsync(url, schema => this).ConfigureAwait(false));
 }
Example #29
0
        ///// <summary>Serializes the <see cref="JsonSchema4" /> to a JSON string and removes externally loaded schemas.</summary>
        ///// <returns>The JSON string.</returns>
        //[Obsolete("Not ready yet as it has side-effects on the schema.")]
        //public string ToJsonWithExternalReferences()
        //{
        //    // TODO: Copy "this" schema first (high-prio)
        //    var oldSchema = SchemaVersion;
        //    SchemaVersion = "http://json-schema.org/draft-04/schema#";
        //    JsonSchemaReferenceUtilities.UpdateSchemaReferencePaths(this, true);
        //    var json = JsonSchemaReferenceUtilities.ConvertPropertyReferences(JsonConvert.SerializeObject(this, Formatting.Indented));
        //    SchemaVersion = oldSchema;
        //    return json;
        //}

        /// <summary>Gets a value indicating whether this schema inherits from the given parent schema.</summary>
        /// <param name="parentSchema">The parent schema.</param>
        /// <returns>true or false.</returns>
        public bool InheritsSchema(JsonSchema4 parentSchema)
        {
            return parentSchema != null && ActualSchema
                .AllInheritedSchemas.Concat(new List<JsonSchema4> { this })
                .Any(s => s.ActualSchema == parentSchema.ActualSchema) == true;
        }
Example #30
0
 /// <summary>Initializes a new instance of the <see cref="JsonSchemaValidator"/> class. </summary>
 /// <param name="schema">The schema. </param>
 public JsonSchemaValidator(JsonSchema4 schema)
 {
     _schema = schema;
 }
Example #31
0
 /// <summary>Applies the type and format to the given schema.</summary>
 /// <param name="schema">The JSON schema.</param>
 public void ApplyType(JsonSchema4 schema)
 {
     schema.Type   = Type;
     schema.Format = Format;
 }
Example #32
0
        /// <summary>Generates and appends a schema from a given type.</summary>
        /// <param name="type">The type.</param>
        /// <param name="mayBeNull">if set to <c>true</c> [may be null].</param>
        /// <param name="parentAttributes">The parent attributes.</param>
        /// <returns></returns>
        public JsonSchema4 GenerateAndAppendSchemaFromType(Type type, bool mayBeNull, IEnumerable<Attribute> parentAttributes)
        {
            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);

                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
                    {
                        // TODO: Fix this bad design
                        // IsNullable must be 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.GetEnumerableItemType();
                return new JsonSchema4
                {
                    // TODO: Fix this bad design
                    // IsNullable must be directly set on SwaggerParameter or SwaggerResponse
                    Type = _settings.NullHandling == NullHandling.JsonSchema ? JsonObjectType.Array | JsonObjectType.Null : JsonObjectType.Array,
                    Item = GenerateAndAppendSchemaFromType(itemType, false, null)
                };
            }

            return _schemaGenerator.Generate(type, _schemaResolver);
        }
        internal override string GetType(JsonSchema4 schema, bool isNullable, string typeNameHint)
        {
            if (schema == null)
                return "void";

            if (schema.ActualSchema.Type == JsonObjectType.File)
                return "any";

            if (schema.ActualSchema.IsAnyType || schema.ActualSchema.Type == JsonObjectType.File)
                return "any";

            return _resolver.Resolve(schema.ActualSchema, isNullable, typeNameHint);
        }
Example #34
0
        /// <summary>Resolves the type of the parameter.</summary>
        /// <param name="parameter">The parameter.</param>
        /// <returns>The parameter type name.</returns>
        protected virtual string ResolveParameterType(SwaggerParameter parameter)
        {
            var schema = parameter.ActualSchema;

            if (parameter.CollectionFormat == SwaggerParameterCollectionFormat.Multi && !schema.Type.HasFlag(JsonObjectType.Array))
                schema = new JsonSchema4 { Type = JsonObjectType.Array, Item = schema };

            var typeNameHint = ConversionUtilities.ConvertToUpperCamelCase(parameter.Name, true);
            return Resolver.Resolve(schema, parameter.IsRequired == false || parameter.IsNullable(BaseSettings.CodeGeneratorSettings.NullHandling), typeNameHint);
        }
Example #35
0
 /// <summary>Gets a value indicating whether the response schema is an exception.</summary>
 public bool InheritsExceptionSchema(JsonSchema4 exceptionSchema)
 {
     return exceptionSchema != null && ActualResponseSchema?
         .AllInheritedSchemas.Concat(new List<JsonSchema4> { ActualResponseSchema })
         .Any(s => s.ActualSchema == exceptionSchema.ActualSchema) == true;
 }
 /// <summary>Initializes a new instance of the <see cref="JsonSchemaValidator"/> class. </summary>
 /// <param name="schema">The schema. </param>
 public JsonSchemaValidator(JsonSchema4 schema)
 {
     _schema = schema;
 }
Example #37
0
 /// <summary>Adds a schema to type mapping.</summary>
 /// <param name="type">The type.</param>
 /// <param name="isIntegerEnumeration">Specifies whether the type is an integer enum.</param>
 /// <param name="schema">The schema.</param>
 public void AddSchema(Type type, bool isIntegerEnumeration, JsonSchema4 schema)
 {
     _mappings.Add(GetKey(type, isIntegerEnumeration), schema);
 }
 /// <summary>Initializes a new instance of the <see cref="CSharpTypeResolver" /> class.</summary>
 /// <param name="definition">The definition.</param>
 public SwaggerToCSharpTypeResolver(IDictionary<string, JsonSchema4> definition)
     : base(definition.Where(p => p.Key != "Exception").Select(p => p.Value).ToArray())
 {
     _exceptionSchema = definition.ContainsKey("Exception") ? definition["Exception"] : null;
 }
        private string GetType(JsonSchema4 schema, string typeNameHint)
        {
            if (schema == null)
                return "string";

            return _resolver.Resolve(schema.ActualSchema, true, typeNameHint);
        }
Example #40
0
 /// <summary>Determines whether the given schema is the parent schema of this schema (i.e. super/base class).</summary>
 /// <param name="schema">The possible subtype schema.</param>
 /// <returns>true or false</returns>
 public bool Inherits(JsonSchema4 schema)
 {
     schema = schema.ActualSchema;
     return(InheritedSchema?.ActualSchema == schema || InheritedSchema?.Inherits(schema) == true);
 }
 /// <summary>Generates the type name.</summary>
 /// <param name="schema">The property.</param>
 /// <param name="typeNameHint">The type name hint (the property name or definition key).</param>
 /// <returns>The new name.</returns>
 public virtual string Generate(JsonSchema4 schema, string typeNameHint)
 {
     return(ConversionUtilities.ConvertToUpperCamelCase(schema.TypeNameRaw?.Split('.').Last(), true));
 }
Example #42
0
 protected CldrJsonParser(string schema)
 {
     this.schema = JsonSchema4.FromJson(schema);
 }
 /// <summary>Adds a schema to type mapping.</summary>
 /// <param name="type">The type.</param>
 /// <param name="schema">The schema.</param>
 public void AddSchema(Type type, JsonSchema4 schema)
 {
     _mappings.Add(type, schema);
 }