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();
            }
            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 #3
0
        /// <summary>
        /// Generate the an operation of an AsyncApi Channel for the given method.
        /// </summary>
        private static Operation GenerateOperationFromMethod(MethodInfo method, AsyncApiSchemaResolver schemaResolver, OperationType operationType, AsyncApiOptions options, JsonSchemaGenerator jsonSchemaGenerator, IServiceProvider serviceProvider)
        {
            var operationAttribute = GetOperationAttribute(method, operationType);

            if (operationAttribute == null)
            {
                return(null);
            }

            IEnumerable <MessageAttribute> messageAttributes = method.GetCustomAttributes <MessageAttribute>();
            var message = messageAttributes.Any()
                ? GenerateMessageFromAttributes(messageAttributes, schemaResolver, jsonSchemaGenerator)
                : GenerateMessageFromType(operationAttribute.MessagePayloadType, schemaResolver, jsonSchemaGenerator);

            var operation = new Operation
            {
                OperationId = operationAttribute.OperationId ?? method.Name,
                Summary     = operationAttribute.Summary ?? method.GetXmlDocsSummary(),
                Description = operationAttribute.Description ?? (method.GetXmlDocsRemarks() != "" ? method.GetXmlDocsRemarks() : null),
                Message     = message,
                Bindings    = operationAttribute.BindingsRef != null ? new OperationBindingsReference(operationAttribute.BindingsRef) : null,
            };

            var filterContext = new OperationFilterContext(method, schemaResolver, jsonSchemaGenerator, operationAttribute);

            foreach (var filterType in options.OperationFilters)
            {
                var filter = (IOperationFilter)serviceProvider.GetRequiredService(filterType);
                filter?.Apply(operation, filterContext);
            }

            return(operation);
        }
Beispiel #4
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);
        }
Beispiel #5
0
 /// <summary>Initializes a new instance of the <see cref="SwaggerGenerator"/> class.</summary>
 /// <param name="schemaGenerator">The schema generator.</param>
 /// <param name="schemaGeneratorSettings">The schema generator settings.</param>
 /// <param name="schemaResolver">The schema resolver.</param>
 public SwaggerGenerator(JsonSchemaGenerator schemaGenerator, JsonSchemaGeneratorSettings schemaGeneratorSettings, JsonSchemaResolver schemaResolver)
 {
     _schemaResolver = schemaResolver;
     _schemaGenerator = schemaGenerator;
     _settings = schemaGeneratorSettings;
 }
Beispiel #6
0
        public static FileContent GetFile(string requestPath, JsonRpcInfo info)
        {
            var    basePath = info?.JsonRpcApiEndpoint ?? "/jsonrpc";
            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("jsonRpcApi.json"))
            {
                var jsonRpcDoc = DocGenerator.GenerateJsonRpcDoc(info);

                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(jsonRpcDoc);
                // generate schema definitions
                foreach (var rpcService in jsonRpcDoc.Services)
                {
                    foreach (var rpcMethod in rpcService.Methods)
                    {
                        if (rpcMethod.Response.Type != typeof(void) && rpcMethod.Response.Type != typeof(Task))
                        {
                            generator.Generate(rpcMethod.Response.Type, resolver);
                        }

                        foreach (var rpcMethodParameter in rpcMethod.Parameters)
                        {
                            generator.Generate(rpcMethodParameter.Type, resolver);
                        }
                    }

                    foreach (var notification in rpcService.Notifications)
                    {
                        foreach (var parameter in notification.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(JsonRpcDoc).Namespace}.web.{filePath}";

            using (var stream = typeof(JsonRpcDoc).Assembly.GetManifestResourceStream(embeddedResource))
            {
                byte[] buffer = null;
                if (stream != null)
                {
                    buffer = ReadToEnd(stream);
                }
                var fileResult = new FileContent(filePath, buffer);
                return(fileResult);
            }
        }
Beispiel #7
0
        private async Task <SigSpecOperation> GenerateOperationAsync(Type type, MethodInfo method, JsonSchemaGenerator generator, SigSpecSchemaResolver resolver, SigSpecOperationType operationType)
        {
            var operation = new SigSpecOperation
            {
                Description = method.GetXmlDocsSummary(),
                Type        = operationType
            };

            foreach (var arg in method.GetParameters())
            {
                var parameter = generator.GenerateWithReferenceAndNullability <SigSpecParameter>(
                    arg.ParameterType.ToContextualType(), arg.ParameterType.ToContextualType().IsNullableType, resolver, (p, s) =>
                {
                    p.Description = arg.GetXmlDocs();
                });

                operation.Parameters[arg.Name] = parameter;
            }

            var returnType =
                operationType == SigSpecOperationType.Observable
                    ? method.ReturnType.GetGenericArguments().First()
                : method.ReturnType == typeof(Task)
                    ? null
                : method.ReturnType.IsGenericType && method.ReturnType.BaseType == typeof(Task)
                    ? method.ReturnType.GetGenericArguments().First()
                    : method.ReturnType;

            operation.ReturnType = returnType == null ? null : generator.GenerateWithReferenceAndNullability <JsonSchema>(
                returnType.ToContextualType(), returnType.ToContextualType().IsNullableType, resolver, async(p, s) =>
            {
                p.Description = method.ReturnType.GetXmlDocsSummary();
            });

            return(operation);
        }
Beispiel #8
0
        private static IMessage GenerateMessageFromAttributes(IEnumerable <MessageAttribute> messageAttributes, AsyncApiSchemaResolver schemaResolver, JsonSchemaGenerator jsonSchemaGenerator)
        {
            if (messageAttributes.Count() == 1)
            {
                return(GenerateMessageFromAttribute(messageAttributes.First(), schemaResolver, jsonSchemaGenerator));
            }

            var messages = new Messages();

            foreach (MessageAttribute messageAttribute in messageAttributes)
            {
                var message = GenerateMessageFromAttribute(messageAttribute, schemaResolver, jsonSchemaGenerator);
                if (message != null)
                {
                    messages.OneOf.Add(message);
                }
            }

            if (messages.OneOf.Count == 1)
            {
                return(messages.OneOf.First());
            }

            return(messages);
        }
Beispiel #9
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 #10
0
 public uSyncSchemaGenerator()
 {
     _schemaGenerator = new JsonSchemaGenerator(new uSyncSchemaGeneratorSettings());
 }
Beispiel #11
0
 public SchemaCustomizerArgs(string name, PropertyInfo typeProperty, JsonProperty schemaProperty, JsonSchema4 schema, JsonSchemaGenerator schemaGenerator, Type type)
 {
     this.Name            = name;
     this.TypeProperty    = typeProperty;
     this.SchemaProperty  = schemaProperty;
     this.Schema          = schema;
     this.SchemaGenerator = schemaGenerator;
     this.Type            = type;
 }
Beispiel #12
0
        /// <summary>
        /// Generate the Channels section of an AsyncApi schema.
        /// </summary>
        private static IDictionary <string, ChannelItem> GenerateChannels(TypeInfo[] asyncApiTypes, AsyncApiSchemaResolver schemaResolver, AsyncApiOptions options, JsonSchemaGenerator jsonSchemaGenerator, IServiceProvider serviceProvider)
        {
            var channels = new Dictionary <string, ChannelItem>();

            channels.AddRange(GenerateChannelsFromMethods(asyncApiTypes, schemaResolver, options, jsonSchemaGenerator, serviceProvider));
            channels.AddRange(GenerateChannelsFromClasses(asyncApiTypes, schemaResolver, options, jsonSchemaGenerator, serviceProvider));
            return(channels);
        }
Beispiel #13
0
        /// <summary>
        /// Generate the Channels section of the AsyncApi schema from the
        /// <see cref="ChannelAttribute"/> on methods.
        /// </summary>
        private static IDictionary <string, ChannelItem> GenerateChannelsFromMethods(IEnumerable <TypeInfo> asyncApiTypes, AsyncApiSchemaResolver schemaResolver, AsyncApiOptions options, JsonSchemaGenerator jsonSchemaGenerator, IServiceProvider serviceProvider)
        {
            var channels = new Dictionary <string, ChannelItem>();

            var methodsWithChannelAttribute = asyncApiTypes
                                              .SelectMany(type => type.DeclaredMethods)
                                              .Select(method => new
            {
                Channel = method.GetCustomAttribute <ChannelAttribute>(),
                Method  = method,
            })
                                              .Where(mc => mc.Channel != null);

            foreach (var mc in methodsWithChannelAttribute)
            {
                var channelItem = new ChannelItem
                {
                    Description = mc.Channel.Description,
                    Parameters  = GetChannelParametersFromAttributes(mc.Method, schemaResolver, jsonSchemaGenerator),
                    Publish     = GenerateOperationFromMethod(mc.Method, schemaResolver, OperationType.Publish, options, jsonSchemaGenerator, serviceProvider),
                    Subscribe   = GenerateOperationFromMethod(mc.Method, schemaResolver, OperationType.Subscribe, options, jsonSchemaGenerator, serviceProvider),
                    Bindings    = mc.Channel.BindingsRef != null ? new ChannelBindingsReference(mc.Channel.BindingsRef) : null,
                    Servers     = mc.Channel.Servers?.ToList(),
                };
                channels.Add(mc.Channel.Name, channelItem);

                var context = new ChannelItemFilterContext(mc.Method, schemaResolver, jsonSchemaGenerator, mc.Channel);
                foreach (var filterType in options.ChannelItemFilters)
                {
                    var filter = (IChannelItemFilter)serviceProvider.GetRequiredService(filterType);
                    filter.Apply(channelItem, context);
                }
            }

            return(channels);
        }
Beispiel #14
0
        private static IDictionary <string, IParameter> GetChannelParametersFromAttributes(MemberInfo memberInfo, AsyncApiSchemaResolver schemaResolver, JsonSchemaGenerator jsonSchemaGenerator)
        {
            IEnumerable <ChannelParameterAttribute> attributes = memberInfo.GetCustomAttributes <ChannelParameterAttribute>();
            var parameters = new Dictionary <string, IParameter>();

            if (attributes.Any())
            {
                foreach (ChannelParameterAttribute attribute in attributes)
                {
                    var parameter = schemaResolver.GetParameterOrReference(new Parameter
                    {
                        Description = attribute.Description,
                        Name        = attribute.Name,
                        Schema      = jsonSchemaGenerator.Generate(attribute.Type, schemaResolver),
                        Location    = attribute.Location,
                    });

                    parameters.Add(attribute.Name, parameter);
                }
            }

            return(parameters);
        }
Beispiel #15
0
        private static IMessage GenerateMessageFromType(Type payloadType, AsyncApiSchemaResolver schemaResolver, JsonSchemaGenerator jsonSchemaGenerator)
        {
            if (payloadType == null)
            {
                return(null);
            }

            var message = new Message
            {
                Payload = jsonSchemaGenerator.Generate(payloadType, schemaResolver),
            };

            message.Name = message.Payload.Id;

            return(schemaResolver.GetMessageOrReference(message));
        }
Beispiel #16
0
        private static IMessage GenerateMessageFromAttribute(MessageAttribute messageAttribute, AsyncApiSchemaResolver schemaResolver, JsonSchemaGenerator jsonSchemaGenerator)
        {
            if (messageAttribute?.PayloadType == null)
            {
                return(null);
            }

            var message = new Message
            {
                Payload     = jsonSchemaGenerator.Generate(messageAttribute.PayloadType, schemaResolver),
                Title       = messageAttribute.Title,
                Summary     = messageAttribute.Summary,
                Description = messageAttribute.Description,
                Bindings    = messageAttribute.BindingsRef != null ? new MessageBindingsReference(messageAttribute.BindingsRef) : null,
            };

            message.Name = messageAttribute.Name ?? message.Payload.ActualSchema.Id;

            return(schemaResolver.GetMessageOrReference(message));
        }
Beispiel #17
0
        public static async Task <JsonSchema4> GetErrorDtoSchemaAsync(this JsonSchemaGenerator schemaGenerator, JsonSchemaResolver resolver)
        {
            var errorType = typeof(ErrorDto);

            return(await schemaGenerator.GenerateWithReference <JsonSchema4>(errorType, Enumerable.Empty <Attribute>(), resolver));
        }
        public void CircularReferenceError()
        {
            JsonSchemaGenerator generator = new JsonSchemaGenerator();

            generator.Generate(typeof(CircularReferenceClass));
        }
Beispiel #19
0
        /// <summary>
        /// The main.
        /// </summary>
        /// <param name="args">
        /// The args.
        /// </param>
        /// <exception cref="Exception">exception thrown
        /// </exception>
        public static void Main(string[] args)
        {
            if (!args.Any())
            {
                throw new Exception("Please pass the job.xml file as a parameter");
            }

            if (args[0] == "-generateschema")
            {
                if (args.Length < 2 || string.IsNullOrEmpty(args[1]))
                {
                    throw new Exception("You must specify a valid filename to write the schema to.");
                }

                var filename = args[1];

                JsonSchemaGenerator.WriteSchemaToFile(typeof(QueryConfig), filename);

                Console.WriteLine($"Written schema to {filename}");
                return;
            }

            string inputFile = args[0];

            var config = new ConfigReader().ReadXml(inputFile);

            var stopwatch = new Stopwatch();

            stopwatch.Start();

            ILogger logger = new LoggerConfiguration()
                             .MinimumLevel.Verbose()
                             .WriteTo.File(Path.Combine(Path.GetTempPath(), "Databus.out.txt"))
                             .CreateLogger();

            using (ProgressMonitor progressMonitor = new ProgressMonitor(new ConsoleProgressLogger()))
            {
                using (var cancellationTokenSource = new CancellationTokenSource())
                {
                    var container = new UnityContainer();
                    container.RegisterInstance <IProgressMonitor>(progressMonitor);

                    var databusSqlReader = new DatabusSqlReader(config.Config.ConnectionString, 0);
                    container.RegisterInstance <IDatabusSqlReader>(databusSqlReader);
                    container.RegisterType <IElasticSearchUploaderFactory, ElasticSearchUploaderFactory>();
                    container.RegisterType <IFileUploaderFactory, FileUploaderFactory>();
                    container.RegisterType <IElasticSearchUploader, ElasticSearchUploader>();
                    container.RegisterType <IFileUploader, FileUploader>();

                    container.RegisterType <IHttpClientFactory, HttpClientFactory>();
                    container.RegisterInstance(logger);

                    if (config.Config.UseMultipleThreads)
                    {
                        container.RegisterType <IPipelineExecutorFactory, MultiThreadedPipelineExecutorFactory>();
                    }
                    else
                    {
                        container.RegisterType <IPipelineExecutorFactory, SingleThreadedPipelineExecutorFactory>();
                    }

                    var pipelineRunner = new DatabusRunner();

                    if (config.Config.UploadToElasticSearch)
                    {
                        pipelineRunner.RunElasticSearchPipeline(container, config, cancellationTokenSource.Token);
                    }
                    else
                    {
                        pipelineRunner.RunRestApiPipeline(container, config, cancellationTokenSource.Token);
                    }
                }
            }

            stopwatch.Stop();
            var timeElapsed = stopwatch.Elapsed.ToString(@"hh\:mm\:ss");
            var threadText  = config.Config.UseMultipleThreads ? "multiple threads" : "single thread";

            Console.WriteLine($"Finished in {timeElapsed} using {threadText}");

#if TRUE
            logger.Verbose("Finished in {ElapsedMinutes} minutes on {Date}.", stopwatch.Elapsed.TotalMinutes, DateTime.Today);
            //logger.Error(new Exception("test"), "An error has occurred.");

            Log.CloseAndFlush();

            //file.Flush();
            //file.Close();
            //file.Dispose();
            //file = null;
#endif
            Console.WriteLine("(Type any key to exit)");
            Console.ReadKey();
        }
Beispiel #20
0
        /// <summary>
        /// Generate the an operation of an AsyncApi Channel for the given class.
        /// </summary>
        private static Operation GenerateOperationFromClass(TypeInfo type, AsyncApiSchemaResolver schemaResolver, OperationType operationType, JsonSchemaGenerator jsonSchemaGenerator)
        {
            var operationAttribute = GetOperationAttribute(type, operationType);

            if (operationAttribute == null)
            {
                return(null);
            }

            var messages  = new Messages();
            var operation = new Operation
            {
                OperationId = operationAttribute.OperationId ?? type.Name,
                Summary     = operationAttribute.Summary ?? type.GetXmlDocsSummary(),
                Description = operationAttribute.Description ?? (type.GetXmlDocsRemarks() != "" ? type.GetXmlDocsRemarks() : null),
                Message     = messages,
                Bindings    = operationAttribute.BindingsRef != null ? new OperationBindingsReference(operationAttribute.BindingsRef) : null,
            };

            var methodsWithMessageAttribute = type.DeclaredMethods
                                              .Select(method => new
            {
                MessageAttributes = method.GetCustomAttributes <MessageAttribute>(),
                Method            = method,
            })
                                              .Where(mm => mm.MessageAttributes.Any());

            foreach (MessageAttribute messageAttribute in methodsWithMessageAttribute.SelectMany(x => x.MessageAttributes))
            {
                var message = GenerateMessageFromAttribute(messageAttribute, schemaResolver, jsonSchemaGenerator);
                if (message != null)
                {
                    messages.OneOf.Add(message);
                }
            }

            if (messages.OneOf.Count == 1)
            {
                operation.Message = messages.OneOf.First();
            }

            return(operation);
        }
Beispiel #21
0
 /// <summary>Initializes a new instance of the <see cref="SwaggerGenerator"/> class.</summary>
 /// <param name="schemaGenerator">The schema generator.</param>
 /// <param name="schemaGeneratorSettings">The schema generator settings.</param>
 /// <param name="schemaResolver">The schema resolver.</param>
 public SwaggerGenerator(JsonSchemaGenerator schemaGenerator, JsonSchemaGeneratorSettings schemaGeneratorSettings, JsonSchemaResolver schemaResolver)
 {
     _schemaGenerator = schemaGenerator;
     _schemaResolver  = schemaResolver;
     _settings        = schemaGeneratorSettings;
 }
Beispiel #22
0
 /// <summary>Initializes a new instance of the <see cref="AspNetCoreOperationProcessorContext" /> class.</summary>
 /// <param name="document">The document.</param>
 /// <param name="operationDescription">The operation description.</param>
 /// <param name="controllerType">Type of the controller.</param>
 /// <param name="methodInfo">The method information.</param>
 /// <param name="swaggerGenerator">The swagger generator.</param>
 /// <param name="schemaResolver">The schema resolver.</param>
 /// <param name="allOperationDescriptions">All operation descriptions.</param>
 /// <param name="schemaGenerator">The schema generator.</param>
 public AspNetCoreOperationProcessorContext(SwaggerDocument document, SwaggerOperationDescription operationDescription, Type controllerType, MethodInfo methodInfo, SwaggerGenerator swaggerGenerator, JsonSchemaGenerator schemaGenerator, JsonSchemaResolver schemaResolver, IList <SwaggerOperationDescription> allOperationDescriptions)
     : base(document, operationDescription, controllerType, methodInfo, swaggerGenerator, schemaGenerator, schemaResolver, allOperationDescriptions)
 {
 }
 /// <summary>Initializes a new instance of the <see cref="DocumentProcessorContext" /> class.</summary>
 /// <param name="document">The document.</param>
 /// <param name="controllerTypes">The controller types.</param>
 /// <param name="schemaResolver">The schema resolver.</param>
 /// <param name="schemaGenerator">The schema generator.</param>
 public DocumentProcessorContext(SwaggerDocument document, IEnumerable <Type> controllerTypes, JsonSchemaResolver schemaResolver, JsonSchemaGenerator schemaGenerator)
 {
     Document        = document;
     ControllerTypes = controllerTypes;
     SchemaResolver  = schemaResolver;
     SchemaGenerator = schemaGenerator;
 }
        /// <summary>Creates a <see cref="JsonSchema4" /> from a given type.</summary>
        /// <typeparam name="TType">The type to create the schema for.</typeparam>
        /// <param name="settings">The settings.</param>
        /// <returns>The <see cref="JsonSchema4" />.</returns>
        public static async Task <JsonSchema4> FromTypeAsync <TType>(JsonSchemaGeneratorSettings settings)
        {
            var generator = new JsonSchemaGenerator(settings);

            return(await generator.GenerateAsync(typeof(TType)).ConfigureAwait(false));
        }
Beispiel #25
0
 public DocumentFilterContext(IEnumerable <Type> asyncApiTypes, JsonSchemaResolver schemaResolver, JsonSchemaGenerator schemaGenerator)
 {
     AsyncApiTypes   = asyncApiTypes;
     SchemaResolver  = schemaResolver;
     SchemaGenerator = schemaGenerator;
 }
 public JsonParameterValidationHelper()
 {
     _jsonSchemaGenerator = new JsonSchemaGenerator();
 }
Beispiel #27
0
        private async Task <SigSpecOperation> GenerateOperationAsync(Type type, MethodInfo method, JsonSchemaGenerator generator, SigSpecSchemaResolver resolver, SigSpecOperationType operationType)
        {
            var operation = new SigSpecOperation
            {
                Description = await type.GetXmlSummaryAsync(),
                Type        = operationType
            };

            foreach (var arg in method.GetParameters())
            {
                var parameter = await generator.GenerateWithReferenceAndNullabilityAsync <SigSpecParameter>(
                    arg.ParameterType, arg.GetCustomAttributes(), resolver, async (p, s) =>
                {
                    p.Description = await arg.GetXmlDocumentationAsync();
                });

                operation.Parameters[arg.Name] = parameter;
            }

            var returnType =
                operationType == SigSpecOperationType.Observable
                    ? method.ReturnType.GetGenericTypeArguments().First()
                : method.ReturnType == typeof(Task)
                    ? null
                : method.ReturnType.IsGenericType && method.ReturnType.BaseType == typeof(Task)
                    ? method.ReturnType.GetGenericTypeArguments().First()
                    : method.ReturnType;

            operation.ReturnType = returnType == null ? null : await generator.GenerateWithReferenceAndNullabilityAsync <JsonSchema4>(
                returnType, null, resolver, async (p, s) =>
            {
                p.Description = await method.ReturnType.GetXmlSummaryAsync();
            });

            return(operation);
        }
        /// <summary>Gets the schema for the mapped type.</summary>
        /// <typeparam name="TSchemaType">The type of the schema type.</typeparam>
        /// <param name="schema">The schema.</param>
        /// <param name="schemaGenerator">The schema generator.</param>
        /// <param name="schemaResolver">The schema resolver.</param>
        /// <returns>The schema.</returns>
#pragma warning disable 1998
        public async Task GenerateSchemaAsync <TSchemaType>(TSchemaType schema, JsonSchemaGenerator schemaGenerator, JsonSchemaResolver schemaResolver)
#pragma warning restore 1998
            where TSchemaType : JsonSchema4, new()
        {
            _transformer(schema);
        }
Beispiel #29
0
        public void GenerateSchemaForDirectoryInfo()
        {
            JsonSchemaGenerator generator = new JsonSchemaGenerator();

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

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

            string json = schema.ToString();

            Assert.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)
                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);
        }
Beispiel #30
0
 /// <summary>Initializes a new instance of the <see cref="SchemaProcessorContext" /> class.</summary>
 /// <param name="schema">The JSON Schema.</param>
 /// <param name="resolver">The resolver.</param>
 /// <param name="generator">The generator.</param>
 public SchemaProcessorContext(JsonSchema4 schema, JsonSchemaResolver resolver, JsonSchemaGenerator generator)
 {
     Schema    = schema;
     Resolver  = resolver;
     Generator = generator;
 }
Beispiel #31
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 #32
0
        /// <summary>
        /// The main entry point.
        /// </summary>
        /// <param name="args">The console arguments.</param>
        /// <returns>A statuc code.</returns>
        public static async Task <int> Main(string[] args)
        {
            if (args == null)
            {
                throw new ArgumentNullException(nameof(args));
            }

            Logger.Default = new ColoredConsoleLogger(nameof(CodeGenConsole));

            // Check for special case / internal use arguments.
            if (args.Length == 1)
            {
                switch (args[0].ToUpperInvariant())
                {
                case "--GENERATEENTITYXMLSCHEMA": return(SpecialActivitiesCenter("Generate Entity XML Schema", "./Schema/codegen.entity.xsd", fn => XmlSchemaGenerator.Create <Config.Entity.CodeGenConfig>(ConfigType.Entity).Save(fn, System.Xml.Linq.SaveOptions.None)));

                case "--GENERATEENTITYJSONSCHEMA": return(SpecialActivitiesCenter("Generate Entity JSON Schema", "./Schema/entity.beef.json", fn => File.WriteAllText(fn, JsonSchemaGenerator.Create <Config.Entity.CodeGenConfig>("JSON Schema for Beef Entity code-generation (https://github.com/Avanade/Beef)."))));

                case "--GENERATEDATABASEXMLSCHEMA": return(SpecialActivitiesCenter("Generate Database XML Schema", "./Schema/codegen.table.xsd", fn => XmlSchemaGenerator.Create <Config.Database.CodeGenConfig>(ConfigType.Database).Save(fn, System.Xml.Linq.SaveOptions.None)));

                case "--GENERATEDATABASEJSONSCHEMA": return(SpecialActivitiesCenter("Generate Database JSON Schema", "./Schema/database.beef.json", fn => File.WriteAllText(fn, JsonSchemaGenerator.Create <Config.Database.CodeGenConfig>("JSON Schema for Beef Database code-generation (https://github.com/Avanade/Beef)."))));

                case "--GENERATEENTITYMARKDOWN": return(SpecialActivitiesCenter("Generate Entity YAML documentation markdown file(s)", "../../docs/", fn => SchemaMarkdownGenerator.Create <Config.Entity.CodeGenConfig>(fn, ConfigType.Entity, true)));

                case "--GENERATEENTITYXMLMARKDOWN": return(SpecialActivitiesCenter("Generate Entity XML documentation markdown file(s)", "../../docs/", fn => SchemaMarkdownGenerator.Create <Config.Entity.CodeGenConfig>(fn, ConfigType.Entity, false)));

                case "--GENERATEDATABASEMARKDOWN": return(SpecialActivitiesCenter("Generate Database YAML documentation markdown file(s)", "../../docs/", fn => SchemaMarkdownGenerator.Create <Config.Database.CodeGenConfig>(fn, ConfigType.Database, true)));

                case "--GENERATEDATABASEXMLMARKDOWN": return(SpecialActivitiesCenter("Generate Database XML documentation markdown file(s)", "../../docs/", fn => SchemaMarkdownGenerator.Create <Config.Database.CodeGenConfig>(fn, ConfigType.Database, false)));
                }
            }

            return(await CodeGenConsole.Create().RunAsync(args).ConfigureAwait(false));
        }
        public void GenerateSchemaSerializable()
        {
            JsonSchemaGenerator generator = new JsonSchemaGenerator();

            DefaultContractResolver contractResolver = new DefaultContractResolver
            {
                IgnoreSerializableAttribute = false
            };

            generator.ContractResolver          = contractResolver;
            generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;

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

            string json = schema.ToString();

            StringAssert.AreEqual(
                @"{
  ""id"": ""Newtonsoft.Json.Tests.Schema.SerializableTestObject"",
  ""type"": [
    ""object"",
    ""null""
  ],
  ""additionalProperties"": false,
  ""properties"": {
    ""_name"": {
      ""required"": true,
      ""type"": [
        ""string"",
        ""null""
      ]
    }
  }
}",
                json
                );

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

            serializer.ContractResolver = contractResolver;
            serializer.Serialize(jsonWriter, new SerializableTestObject {
                Name = "Name!"
            });

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

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

            Assert.AreEqual(0, errors.Count);

            StringAssert.AreEqual(
                @"{
  ""_name"": ""Name!""
}",
                jsonWriter.Token.ToString()
                );

            SerializableTestObject c = jsonWriter.Token.ToObject <SerializableTestObject>(
                serializer
                );

            Assert.AreEqual("Name!", c.Name);
        }
Beispiel #34
0
        /// <summary>
        /// Generate the Channels section of the AsyncApi schema from the
        /// <see cref="ChannelAttribute"/> on classes.
        /// </summary>
        private static IDictionary <string, ChannelItem> GenerateChannelsFromClasses(IEnumerable <TypeInfo> asyncApiTypes, AsyncApiSchemaResolver schemaResolver, AsyncApiOptions options, JsonSchemaGenerator jsonSchemaGenerator, IServiceProvider serviceProvider)
        {
            var channels = new Dictionary <string, ChannelItem>();

            var classesWithChannelAttribute = asyncApiTypes
                                              .Select(type => new
            {
                Channel = type.GetCustomAttribute <ChannelAttribute>(),
                Type    = type,
            })
                                              .Where(cc => cc.Channel != null);

            foreach (var cc in classesWithChannelAttribute)
            {
                var channelItem = new ChannelItem
                {
                    Description = cc.Channel.Description,
                    Parameters  = GetChannelParametersFromAttributes(cc.Type, schemaResolver, jsonSchemaGenerator),
                    Publish     = GenerateOperationFromClass(cc.Type, schemaResolver, OperationType.Publish, jsonSchemaGenerator),
                    Subscribe   = GenerateOperationFromClass(cc.Type, schemaResolver, OperationType.Subscribe, jsonSchemaGenerator),
                    Bindings    = cc.Channel.BindingsRef != null ? new ChannelBindingsReference(cc.Channel.BindingsRef) : null,
                    Servers     = cc.Channel.Servers?.ToList(),
                };

                channels.AddOrAppend(cc.Channel.Name, channelItem);

                var context = new ChannelItemFilterContext(cc.Type, schemaResolver, jsonSchemaGenerator, cc.Channel);
                foreach (var filterType in options.ChannelItemFilters)
                {
                    var filter = (IChannelItemFilter)serviceProvider.GetRequiredService(filterType);
                    filter.Apply(channelItem, context);
                }
            }

            return(channels);
        }