internal string FromAssemblyType(string[] classNames, string settingsData)
            {
                var settings = JsonConvert.DeserializeObject<AssemblyTypeToSwaggerGeneratorSettings>(settingsData);

                var generator = new JsonSchemaGenerator(settings);
                var resolver = new SchemaResolver();
                var service = new SwaggerService();

                var assembly = Assembly.LoadFrom(settings.AssemblyPath);
                foreach (var className in classNames)
                {
                    var type = assembly.GetType(className);
                    var schema = generator.Generate<JsonSchema4>(type, resolver);
                    service.Definitions[type.Name] = schema;
                }

                return service.ToJson();
            }
Beispiel #2
0
        private static SwaggerDocument CreateService()
        {
            var document = new SwaggerDocument();
            var settings = new JsonSchemaGeneratorSettings();
            var generator = new JsonSchemaGenerator(settings);

            document.Paths["/Person"] = new SwaggerOperations();
            document.Paths["/Person"][SwaggerOperationMethod.Get] = new SwaggerOperation
            {
                Responses = new Dictionary<string, SwaggerResponse>
                {
                    {
                        "200", new SwaggerResponse
                        {
                            Schema = new JsonSchema4
                            {
                                SchemaReference = generator.Generate(typeof(Person), new SwaggerSchemaResolver(document, settings))
                            }
                        }
                    }
                }
            };
            return document;
        }
Beispiel #3
0
        public void GenerateSchemaForDirectoryInfo()
        {
            JsonSchemaGenerator generator = new JsonSchemaGenerator();

            generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
            generator.ContractResolver          = new CustomDirectoryInfoMapper
            {
#if !(NETFX_CORE || PORTABLE || ASPNETCORE50)
                IgnoreSerializableAttribute = true
#endif
            };

            JsonSchema schema = generator.Generate(typeof(DirectoryInfo), true);

            string json = schema.ToString();

            StringAssert.AreEqual(@"{
  ""id"": ""System.IO.DirectoryInfo"",
  ""required"": true,
  ""type"": [
    ""object"",
    ""null""
  ],
  ""additionalProperties"": false,
  ""properties"": {
    ""Name"": {
      ""required"": true,
      ""type"": [
        ""string"",
        ""null""
      ]
    },
    ""Parent"": {
      ""$ref"": ""System.IO.DirectoryInfo""
    },
    ""Exists"": {
      ""required"": true,
      ""type"": ""boolean""
    },
    ""FullName"": {
      ""required"": true,
      ""type"": [
        ""string"",
        ""null""
      ]
    },
    ""Extension"": {
      ""required"": true,
      ""type"": [
        ""string"",
        ""null""
      ]
    },
    ""CreationTime"": {
      ""required"": true,
      ""type"": ""string""
    },
    ""CreationTimeUtc"": {
      ""required"": true,
      ""type"": ""string""
    },
    ""LastAccessTime"": {
      ""required"": true,
      ""type"": ""string""
    },
    ""LastAccessTimeUtc"": {
      ""required"": true,
      ""type"": ""string""
    },
    ""LastWriteTime"": {
      ""required"": true,
      ""type"": ""string""
    },
    ""LastWriteTimeUtc"": {
      ""required"": true,
      ""type"": ""string""
    },
    ""Attributes"": {
      ""required"": true,
      ""type"": ""integer""
    }
  }
}", json);

            DirectoryInfo temp = new DirectoryInfo(@"c:\temp");

            JTokenWriter   jsonWriter = new JTokenWriter();
            JsonSerializer serializer = new JsonSerializer();
            serializer.Converters.Add(new IsoDateTimeConverter());
            serializer.ContractResolver = new CustomDirectoryInfoMapper
            {
#if !(NETFX_CORE || PORTABLE || ASPNETCORE50)
                IgnoreSerializableInterface = true
#endif
            };
            serializer.Serialize(jsonWriter, temp);

            List <string> errors = new List <string>();
            jsonWriter.Token.Validate(schema, (sender, args) => errors.Add(args.Message));

            Assert.AreEqual(0, errors.Count);
        }
            internal string FromAssemblyType(string[] classNames, string settingsData)
            {
                var document = new SwaggerDocument();
                var settings = JsonConvert.DeserializeObject<AssemblyTypeToSwaggerGeneratorSettings>(settingsData);

                RegisterReferencePaths(GetAllReferencePaths(settings));

                var generator = new JsonSchemaGenerator(settings);
                var schemaResolver = new SwaggerSchemaResolver(document, settings);

#if FullNet
                var assembly = Assembly.LoadFrom(settings.AssemblyPath);
#else
                var assembly = Context.LoadFromAssemblyPath(settings.AssemblyPath);
#endif
                foreach (var className in classNames)
                {
                    var type = assembly.GetType(className);
                    var schema = generator.Generate(type, schemaResolver);
                    document.Definitions[type.Name] = schema;
                }

                return document.ToJson();
            }
Beispiel #5
0
        public void JsonPropertyWithHandlingValues()
        {
            JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();

            jsonSchemaGenerator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
            JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(JsonPropertyWithHandlingValues));
            string     json       = jsonSchema.ToString();

            Assert.AreEqual(@"{
  ""id"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues"",
  ""required"": true,
  ""type"": [
    ""object"",
    ""null""
  ],
  ""properties"": {
    ""DefaultValueHandlingIgnoreProperty"": {
      ""type"": [
        ""string"",
        ""null""
      ],
      ""default"": ""Default!""
    },
    ""DefaultValueHandlingIncludeProperty"": {
      ""required"": true,
      ""type"": [
        ""string"",
        ""null""
      ],
      ""default"": ""Default!""
    },
    ""DefaultValueHandlingPopulateProperty"": {
      ""required"": true,
      ""type"": [
        ""string"",
        ""null""
      ],
      ""default"": ""Default!""
    },
    ""DefaultValueHandlingIgnoreAndPopulateProperty"": {
      ""type"": [
        ""string"",
        ""null""
      ],
      ""default"": ""Default!""
    },
    ""NullValueHandlingIgnoreProperty"": {
      ""type"": [
        ""string"",
        ""null""
      ]
    },
    ""NullValueHandlingIncludeProperty"": {
      ""required"": true,
      ""type"": [
        ""string"",
        ""null""
      ]
    },
    ""ReferenceLoopHandlingErrorProperty"": {
      ""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues""
    },
    ""ReferenceLoopHandlingIgnoreProperty"": {
      ""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues""
    },
    ""ReferenceLoopHandlingSerializeProperty"": {
      ""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues""
    }
  }
}", json);
        }
Beispiel #6
0
        public void GenerateSchemaSerializable()
        {
            JsonSchemaGenerator generator = new JsonSchemaGenerator();

            generator.ContractResolver = new DefaultContractResolver
            {
                IgnoreSerializableAttribute = false
            };
            generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;

            JsonSchema schema = generator.Generate(typeof(Version), true);

            string json = schema.ToString();

            Assert.AreEqual(@"{
  ""id"": ""System.Version"",
  ""type"": [
    ""object"",
    ""null""
  ],
  ""additionalProperties"": false,
  ""properties"": {
    ""_Major"": {
      ""required"": true,
      ""type"": ""integer""
    },
    ""_Minor"": {
      ""required"": true,
      ""type"": ""integer""
    },
    ""_Build"": {
      ""required"": true,
      ""type"": ""integer""
    },
    ""_Revision"": {
      ""required"": true,
      ""type"": ""integer""
    }
  }
}", json);

            JTokenWriter   jsonWriter = new JTokenWriter();
            JsonSerializer serializer = new JsonSerializer();

            serializer.ContractResolver = new DefaultContractResolver
            {
                IgnoreSerializableAttribute = false
            };
            serializer.Serialize(jsonWriter, new Version(1, 2, 3, 4));

            List <string> errors = new List <string>();

            jsonWriter.Token.Validate(schema, (sender, args) => errors.Add(args.Message));

            Assert.AreEqual(0, errors.Count);

            Assert.AreEqual(@"{
  ""_Major"": 1,
  ""_Minor"": 2,
  ""_Build"": 3,
  ""_Revision"": 4
}", jsonWriter.Token.ToString());

            Version version = jsonWriter.Token.ToObject <Version>(serializer);

            Assert.AreEqual(1, version.Major);
            Assert.AreEqual(2, version.Minor);
            Assert.AreEqual(3, version.Build);
            Assert.AreEqual(4, version.Revision);
        }
        public static FileContent GetFile(string requestPath, HubApiConfiguration hubApiConfiguration)
        {
            var    basePath = hubApiConfiguration.ApiInfo?.HubApiEndpoint ?? "/hubapi";
            string filePath;

            if (!basePath.StartsWith("/"))
            {
                basePath = "/" + basePath;
            }

            if (!requestPath.StartsWith(basePath))
            {
                return(new FileContent());
            }

            if (requestPath.EndsWith("/"))
            {
                requestPath = requestPath.Substring(0, requestPath.Length - 1);
            }
            if (requestPath.EndsWith("api.json"))
            {
                var schemaSettings = new JsonSchemaGeneratorSettings
                {
                    SerializerSettings               = JsonSerializerSettings,
                    GenerateExamples                 = true,
                    SchemaType                       = SchemaType.JsonSchema,
                    GenerateAbstractSchemas          = false,
                    DefaultReferenceTypeNullHandling = ReferenceTypeNullHandling.NotNull
                };

                var schema = new JsonSchema();

                var resolver  = new JsonSchemaResolver(schema, schemaSettings);
                var generator = new JsonSchemaGenerator(schemaSettings);

                generator.Generate(schema, typeof(object), resolver);

                var jDoc = JObject.FromObject(hubApiConfiguration);
                // generate schema definitions
                foreach (var hub in hubApiConfiguration.Hubs)
                {
                    foreach (var hubMethod in hub.Methods)
                    {
                        if (hubMethod.Response.Type != typeof(void) && hubMethod.Response.Type != typeof(Task))
                        {
                            generator.Generate(hubMethod.Response.Type, resolver);
                        }

                        foreach (var parameter in hubMethod.Parameters)
                        {
                            generator.Generate(parameter.Type, resolver);
                        }
                    }

                    foreach (var clientMethod in hub.ClientMethods)
                    {
                        if (clientMethod.Response.Type != typeof(void) && clientMethod.Response.Type != typeof(Task))
                        {
                            generator.Generate(clientMethod.Response.Type, resolver);
                        }
                        foreach (var parameter in clientMethod.Parameters)
                        {
                            generator.Generate(parameter.Type, resolver);
                        }
                    }
                }

                var schemaJObject = JObject.Parse(schema.ToJson());
                jDoc["definitions"] = schemaJObject["definitions"];

                var buffer = Encoding.UTF8.GetBytes(jDoc.ToString(Formatting.None));

                var fileResult = new FileContent(requestPath, buffer);

                return(fileResult);
            }
            if (requestPath.Equals(basePath))
            {
                filePath = "index.html";
            }
            else
            {
                filePath = requestPath.Substring(basePath.Length + 1);
                filePath = filePath.Replace("/", ".");
            }
            var embeddedResource = $"{typeof(HubApiConfiguration).Namespace}.web.{filePath}";

            using (var stream = typeof(HubApiConfiguration).Assembly.GetManifestResourceStream(embeddedResource))
            {
                byte[] buffer = null;
                if (stream != null)
                {
                    buffer = ReadToEnd(stream);
                }
                var fileResult = new FileContent(filePath, buffer);
                return(fileResult);
            }
        }
Beispiel #8
0
        public void CircularReferenceError()
        {
            JsonSchemaGenerator generator = new JsonSchemaGenerator();

            generator.Generate(typeof(CircularReferenceClass));
        }
Beispiel #9
0
        private JObject GenerateuSyncSchema()
        {
            var schema = _schemaGenerator.Generate(typeof(AppSettings));

            return(JsonConvert.DeserializeObject <JObject>(schema.ToJson()));
        }