コード例 #1
0
        private void LoadReturnType(SwaggerService service, SwaggerOperation operation, MethodInfo method, ISchemaResolver schemaResolver)
        {
            var returnType = method.ReturnType;

            if (returnType == typeof(Task))
            {
                returnType = typeof(void);
            }
            else if (returnType.Name == "Task`1")
            {
                returnType = returnType.GenericTypeArguments[0];
            }

            var description = method.ReturnParameter.GetXmlDocumentation();

            if (description == string.Empty)
            {
                description = null;
            }

            var responseTypeAttributes = method.GetCustomAttributes().Where(a => a.GetType().Name == "ResponseTypeAttribute").ToList();

            if (responseTypeAttributes.Count > 0)
            {
                foreach (var responseTypeAttribute in responseTypeAttributes)
                {
                    dynamic dynResultTypeAttribute = responseTypeAttribute;
                    returnType = dynResultTypeAttribute.ResponseType;

                    var httpStatusCode = IsVoidResponse(returnType) ? "204" : "200";
                    if (responseTypeAttribute.GetType().GetRuntimeProperty("HttpStatusCode") != null)
                    {
                        httpStatusCode = dynResultTypeAttribute.HttpStatusCode;
                    }

                    var schema = CreateAndAddSchema(service, returnType, null, schemaResolver);
                    operation.Responses[httpStatusCode] = new SwaggerResponse
                    {
                        Description = description,
                        Schema      = schema
                    };
                }
            }
            else
            {
                if (IsVoidResponse(returnType))
                {
                    operation.Responses["204"] = new SwaggerResponse();
                }
                else
                {
                    var schema = CreateAndAddSchema(service, returnType, null, schemaResolver);
                    operation.Responses["200"] = new SwaggerResponse
                    {
                        Description = description,
                        Schema      = schema
                    };
                }
            }
        }
コード例 #2
0
        private string GetOperationId(SwaggerService service, string controllerName, string methodName)
        {
            // TODO: Implement IOperationIdGenerator

            if (controllerName.EndsWith("Controller"))
            {
                controllerName = controllerName.Substring(0, controllerName.Length - 10);
            }

            if (methodName.EndsWith("Async"))
            {
                methodName = methodName.Substring(0, methodName.Length - 5);
            }

            var operationId = controllerName + "_" + methodName;

            var number = 1;

            while (service.Operations.Any(o => o.Operation.OperationId == (operationId + (number > 1 ? "_" + number : string.Empty))))
            {
                number++;
            }

            return(operationId + (number > 1 ? "_" + number : string.Empty));
        }
コード例 #3
0
        private void AddPrimitiveParameter(SwaggerService service, SwaggerOperation operation, ParameterInfo parameter, ISchemaResolver schemaResolver)
        {
            var operationParameter = CreatePrimitiveParameter(service, parameter, schemaResolver, setRequiredProperty: true);

            operationParameter.Kind = SwaggerParameterKind.Query;
            operation.Parameters.Add(operationParameter);
        }
コード例 #4
0
        private string GetOperationId(SwaggerService service, string controllerName, MethodInfo method)
        {
            string operationId;

            dynamic swaggerOperationAttribute = method.GetCustomAttributes().FirstOrDefault(a => a.GetType().Name == "SwaggerOperationAttribute");

            if (swaggerOperationAttribute != null && !string.IsNullOrEmpty(swaggerOperationAttribute.OperationId))
            {
                operationId = swaggerOperationAttribute.OperationId;
            }
            else
            {
                if (controllerName.EndsWith("Controller"))
                {
                    controllerName = controllerName.Substring(0, controllerName.Length - 10);
                }

                var methodName = method.Name;
                if (methodName.EndsWith("Async"))
                {
                    methodName = methodName.Substring(0, methodName.Length - 5);
                }

                operationId = controllerName + "_" + methodName;
            }

            var number = 1;

            while (service.Operations.Any(o => o.Operation.OperationId == operationId + (number > 1 ? "_" + number : string.Empty)))
            {
                number++;
            }

            return(operationId + (number > 1 ? number.ToString() : string.Empty));
        }
コード例 #5
0
        internal string GenerateFile(SwaggerService service, ClientGeneratorOutputType type)
        {
            var clientCode    = string.Empty;
            var operations    = GetOperations(service);
            var clientClasses = new List <string>();

            if (BaseSettings.OperationNameGenerator.SupportsMultipleClients)
            {
                foreach (var controllerOperations in operations.GroupBy(o => BaseSettings.OperationNameGenerator.GetClientName(service, o.Path, o.HttpMethod, o.Operation)))
                {
                    var controllerName      = controllerOperations.Key;
                    var controllerClassName = GetClassName(controllerOperations.Key);
                    clientCode += GenerateClientClass(controllerName, controllerClassName, controllerOperations.ToList(), type) + "\n\n";
                    clientClasses.Add(controllerClassName);
                }
            }
            else
            {
                var controllerName      = string.Empty;
                var controllerClassName = GetClassName(controllerName);
                clientCode = GenerateClientClass(controllerName, controllerClassName, operations, type);
                clientClasses.Add(controllerClassName);
            }

            return(GenerateFile(clientCode, clientClasses, type)
                   .Replace("\r", string.Empty)
                   .Replace("\n\n\n\n", "\n\n")
                   .Replace("\n\n\n", "\n\n"));
        }
コード例 #6
0
ファイル: ClientGeneratorBase.cs プロジェクト: csnyded3/NSwag
        internal string GenerateFile <TGenerator>(SwaggerService service, TypeResolverBase <TGenerator> resolver)
            where TGenerator : TypeGeneratorBase
        {
            var clients       = string.Empty;
            var operations    = GetOperations(service, resolver);
            var clientClasses = new List <string>();

            if (BaseSettings.OperationNameGenerator.SupportsMultipleClients)
            {
                foreach (var controllerOperations in operations.GroupBy(o => BaseSettings.OperationNameGenerator.GetClientName(service, o.Path, o.HttpMethod, o.Operation)))
                {
                    var controllerName = GetClassName(controllerOperations.Key);
                    clients += RenderClientCode(controllerName, controllerOperations.ToList()) + "\n\n";
                    clientClasses.Add(controllerName);
                }
            }
            else
            {
                var controllerName = GetClassName(string.Empty);
                clients = RenderClientCode(controllerName, operations);
                clientClasses.Add(controllerName);
            }

            return(RenderFile(clients, clientClasses.ToArray())
                   .Replace("\r", string.Empty)
                   .Replace("\n\n\n\n", "\n\n")
                   .Replace("\n\n\n", "\n\n"));
        }
コード例 #7
0
        private void AddOperationDescriptionsToDocument(SwaggerService service, List <Tuple <SwaggerOperationDescription, MethodInfo> > operations, ISchemaResolver schemaResolver)
        {
            var allOperation = operations.Select(t => t.Item1).ToList();

            foreach (var tuple in operations)
            {
                var operation = tuple.Item1;
                var method    = tuple.Item2;

                var addOperation = RunOperationProcessors(method, operation, allOperation, schemaResolver);
                if (addOperation)
                {
                    if (!service.Paths.ContainsKey(operation.Path))
                    {
                        service.Paths[operation.Path] = new SwaggerOperations();
                    }

                    if (service.Paths[operation.Path].ContainsKey(operation.Method))
                    {
                        throw new InvalidOperationException("The method '" + operation.Method + "' on path '" + operation.Path + "' is registered multiple times.");
                    }

                    service.Paths[operation.Path][operation.Method] = operation.Operation;
                }
            }
        }
        /// <summary>Gets the operation name for a given operation.</summary>
        /// <param name="service">The Swagger service.</param>
        /// <param name="path">The HTTP path.</param>
        /// <param name="httpMethod">The HTTP method.</param>
        /// <param name="operation">The operation.</param>
        /// <returns>The operation name.</returns>
        public string GetOperationName(SwaggerService service, string path, SwaggerOperationMethod httpMethod, SwaggerOperation operation)
        {
            var clientName    = GetClientName(operation);
            var operationName = GetOperationName(operation);

            var hasOperationWithSameName = service.Operations
                                           .Where(o => o.Operation != operation)
                                           .Any(o => GetClientName(o.Operation) == clientName && GetOperationName(o.Operation) == operationName);

            if (hasOperationWithSameName)
            {
                if (operationName.ToLowerInvariant().StartsWith("get"))
                {
                    var isArrayResponse = operation.Responses.ContainsKey("200") &&
                                          operation.Responses["200"].Schema != null &&
                                          operation.Responses["200"].Schema.Type.HasFlag(JsonObjectType.Array);

                    if (isArrayResponse)
                    {
                        return("GetAll" + operationName.Substring(3));
                    }
                }
            }

            return(operationName);
        }
コード例 #9
0
        private string GetOperationId(SwaggerService service, string controllerName, MethodInfo method)
        {
            if (controllerName.EndsWith("Controller"))
            {
                controllerName = controllerName.Substring(0, controllerName.Length - 10);
            }

            var methodName = method.Name;

            if (methodName.EndsWith("Async"))
            {
                methodName = methodName.Substring(0, methodName.Length - 5);
            }

            var operationId = controllerName + "_" + methodName;

            var number = 1;

            while (service.Operations.Any(o => o.Operation.OperationId == (operationId + (number > 1 ? "_" + number : string.Empty))))
            {
                number++;
            }

            return(operationId + (number > 1 ? number.ToString() : string.Empty));
        }
コード例 #10
0
        private void AddBodyParameter(SwaggerService service, SwaggerOperation operation, ISchemaResolver schemaResolver,
                                      ParameterInfo parameter)
        {
            var operationParameter = CreateBodyParameter(service, parameter, schemaResolver);

            operation.Parameters.Add(operationParameter);
        }
コード例 #11
0
        private SwaggerParameter CreatePrimitiveParameter(SwaggerService service, string name, string description,
                                                          Type type, IList <Attribute> parentAttributes, ISchemaResolver schemaResolver)
        {
            var schemaDefinitionAppender = new SwaggerServiceSchemaDefinitionAppender(service, Settings.TypeNameGenerator);
            var schemaGenerator          = new RootTypeJsonSchemaGenerator(service, schemaDefinitionAppender, Settings);

            var typeDescription = JsonObjectTypeDescription.FromType(type, parentAttributes, Settings.DefaultEnumHandling);
            var parameterType   = typeDescription.IsComplexType ? typeof(string) : type; // complex types must be treated as string

            var operationParameter = new SwaggerParameter();

            typeDescription.ApplyType(operationParameter);

            if (parameterType.GetTypeInfo().IsEnum)
            {
                operationParameter.SchemaReference = schemaGenerator.Generate <JsonSchema4>(parameterType, null, parentAttributes, schemaDefinitionAppender, schemaResolver);
            }
            else
            {
                schemaGenerator.ApplyPropertyAnnotations(operationParameter, type, parentAttributes, typeDescription);
            }

            operationParameter.Name          = name;
            operationParameter.IsRequired    = parentAttributes?.Any(a => a.GetType().Name == "RequiredAttribute") ?? false;
            operationParameter.IsNullableRaw = typeDescription.IsNullable;

            if (description != string.Empty)
            {
                operationParameter.Description = description;
            }

            return(operationParameter);
        }
コード例 #12
0
        private void AddPrimitiveParametersFromUri(SwaggerService service, SwaggerOperation operation, ParameterInfo parameter, ISchemaResolver schemaResolver)
        {
            foreach (var property in parameter.ParameterType.GetRuntimeProperties())
            {
                var attributes         = property.GetCustomAttributes().ToList();
                var operationParameter = CreatePrimitiveParameter(// TODO: Check if there is a way to control the property name
                    service, JsonPathUtilities.GetPropertyName(property, Settings.DefaultPropertyNameHandling),
                    property.GetXmlDocumentation(), property.PropertyType, attributes, schemaResolver);

                // TODO: Check if required can be controlled with mechanisms other than RequiredAttribute

                var parameterInfo = JsonObjectTypeDescription.FromType(property.PropertyType, attributes, Settings.DefaultEnumHandling);
                var isFileArray   = IsFileArray(property.PropertyType, parameterInfo);
                if (parameterInfo.Type == JsonObjectType.File || isFileArray)
                {
                    InitializeFileParameter(operationParameter, isFileArray);
                }
                else
                {
                    operationParameter.Kind = SwaggerParameterKind.Query;
                }

                operation.Parameters.Add(operationParameter);
            }
        }
コード例 #13
0
        /// <exception cref="InvalidOperationException">The operation has more than one body parameter.</exception>
        private void GenerateForController(SwaggerService service, Type controllerType, string excludedMethodName, SchemaResolver schemaResolver)
        {
            var methods = controllerType.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

            foreach (var method in methods.Where(m => m.Name != excludedMethodName))
            {
                var parameters = method.GetParameters().ToList();
                var methodName = method.Name;

                var operation = new SwaggerOperation();
                operation.OperationId = methodName;

                var httpPath = GetHttpPath(service, operation, controllerType, method, parameters, schemaResolver);

                LoadParameters(service, operation, parameters, schemaResolver);
                LoadReturnType(service, operation, method, schemaResolver);
                LoadMetaData(operation, method);

                foreach (var httpMethod in GetSupportedHttpMethods(method))
                {
                    if (!service.Paths.ContainsKey(httpPath))
                    {
                        var path = new SwaggerOperations();
                        service.Paths[httpPath] = path;
                    }

                    service.Paths[httpPath][httpMethod] = operation;
                }
            }

            foreach (var schema in schemaResolver.Schemes)
            {
                service.Definitions[schema.TypeName] = schema;
            }
        }
コード例 #14
0
ファイル: OperationIdTests.cs プロジェクト: pszyller/NSwag
        public void When_generating_operation_id()
        {
            //// Arrange
            var service = new SwaggerService();

            service.Paths["path"] = new SwaggerOperations
            {
                {
                    SwaggerOperationMethod.Get,
                    new SwaggerOperation {
                    }
                },
                {
                    SwaggerOperationMethod.Post,
                    new SwaggerOperation {
                    }
                }
            };

            //// Act
            service.GenerateOperationIds();

            //// Assert
            Assert.IsTrue(service.Operations.GroupBy(o => o.Operation.OperationId).All(g => g.Count() == 1));
        }
コード例 #15
0
        private SwaggerParameter CreateBodyParameter(SwaggerService service, ParameterInfo parameter, ISchemaResolver schemaResolver)
        {
            var isRequired = IsParameterRequired(parameter);

            var operationParameter = new SwaggerParameter
            {
                Name       = parameter.Name,
                Kind       = SwaggerParameterKind.Body,
                IsRequired = isRequired,
                Schema     = CreateAndAddSchema(service, parameter.ParameterType, !isRequired, parameter.GetCustomAttributes(), schemaResolver)
            };

            var typeDescription = JsonObjectTypeDescription.FromType(parameter.ParameterType, parameter.GetCustomAttributes(), Settings.DefaultEnumHandling);

            operationParameter.IsNullableRaw = typeDescription.IsNullable;

            var description = parameter.GetXmlDocumentation();

            if (description != string.Empty)
            {
                operationParameter.Description = description;
            }

            return(operationParameter);
        }
コード例 #16
0
        /// <exception cref="InvalidOperationException">The operation has more than one body parameter.</exception>
        private void GenerateForController(SwaggerService service, Type controllerType, string excludedMethodName, SchemaResolver schemaResolver)
        {
            foreach (var method in GetActionMethods(controllerType, excludedMethodName))
            {
                var operation = new SwaggerOperation
                {
                    IsDeprecated = method.GetCustomAttribute <ObsoleteAttribute>() != null
                };

                var parameters = method.GetParameters().ToList();
                var httpPath   = GetHttpPath(service, operation, controllerType, method, parameters, schemaResolver);

                LoadParameters(service, operation, parameters, schemaResolver);
                LoadReturnType(service, operation, method, schemaResolver);
                LoadMetaData(operation, method);
                LoadOperationTags(method, operation, controllerType);

                operation.OperationId = GetOperationId(service, controllerType.Name, method);

                foreach (var httpMethod in GetSupportedHttpMethods(method))
                {
                    if (!service.Paths.ContainsKey(httpPath))
                    {
                        var path = new SwaggerOperations();
                        service.Paths[httpPath] = path;
                    }

                    service.Paths[httpPath][httpMethod] = operation;
                }
            }

            AppendRequiredSchemasToDefinitions(service, schemaResolver);
        }
コード例 #17
0
        public SwaggerService Generate(Type type, InterfaceMapping map, string excludedMethodName = "Swagger", string controllernameused = null)
        {
            _service     = new SwaggerService();
            _serviceType = type;

            _exceptionType          = new JsonSchema4();
            _exceptionType.TypeName = "SwaggerException";
            _exceptionType.Properties.Add("ExceptionType", new JsonProperty {
                Type = JsonObjectType.String
            });
            _exceptionType.Properties.Add("Message", new JsonProperty {
                Type = JsonObjectType.String
            });
            _exceptionType.Properties.Add("StackTrace", new JsonProperty {
                Type = JsonObjectType.String
            });

            _service.Definitions[_exceptionType.TypeName] = _exceptionType;

            var schemaResolver = new SchemaResolver();
            var methods        = type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

            foreach (var method in methods.Where(m => m.Name != excludedMethodName))
            {
                if (Array.IndexOf(map.TargetMethods, method) == -1)
                {
                    continue;
                }

                var parameters = method.GetParameters().ToList();
                var methodName = method.Name;

                var operation = new SwaggerOperation();
                operation.OperationId = methodName;

                var httpPath = GetHttpPath(operation, method, parameters, schemaResolver, controllernameused);

                LoadParameters(operation, parameters, schemaResolver);
                LoadReturnType(operation, method, schemaResolver);
                LoadMetaData(operation, method);

                var httpMethod = GetMethod(method);

                if (!_service.Paths.ContainsKey(httpPath))
                {
                    var path = new SwaggerOperations();
                    _service.Paths[httpPath] = path;
                }

                _service.Paths[httpPath][httpMethod] = operation;
            }

            foreach (var schema in schemaResolver.Schemes)
            {
                _service.Definitions[schema.TypeName] = schema;
            }

            _service.GenerateOperationIds();
            return(_service);
        }
コード例 #18
0
 /// <summary>Generates the Swagger definition for all controllers in the assembly.</summary>
 /// <param name="controllerClassNames">The controller class names.</param>
 /// <exception cref="InvalidOperationException">No assembly paths have been provided.</exception>
 /// <returns>The Swagger definition.</returns>
 public SwaggerService GenerateForControllers(IEnumerable <string> controllerClassNames)
 {
     using (var isolated = new AppDomainIsolation <WebApiAssemblyLoader>(Path.GetDirectoryName(Path.GetFullPath(Settings.AssemblyPaths.First())), Settings.AssemblyConfig))
     {
         var service = isolated.Object.GenerateForControllers(controllerClassNames, JsonConvert.SerializeObject(Settings));
         return(SwaggerService.FromJson(service));
     }
 }
コード例 #19
0
        private void AddPrimitiveParameter(SwaggerService service, SwaggerOperation operation, ParameterInfo parameter, ISchemaResolver schemaResolver)
        {
            var operationParameter = CreatePrimitiveParameter(service, parameter, schemaResolver);

            operationParameter.Kind       = SwaggerParameterKind.Query;
            operationParameter.IsRequired = operationParameter.IsRequired || parameter.HasDefaultValue == false;
            operation.Parameters.Add(operationParameter);
        }
コード例 #20
0
 /// <summary>
 /// Create a new <see cref="JabApiOperation"/>
 /// </summary>
 /// <param name="service"></param>
 /// <param name="path"></param>
 /// <param name="method"></param>
 /// <param name="operation"></param>
 public JabApiOperation(SwaggerService service, string path, SwaggerOperationMethod method,
                        SwaggerOperation operation)
 {
     Service   = service;
     Path      = path;
     Method    = method;
     Operation = operation;
 }
コード例 #21
0
ファイル: ClientTemplateModel.cs プロジェクト: pszyller/NSwag
        public ClientTemplateModel(string controllerName, IList <OperationModel> operations, SwaggerService service, SwaggerToCSharpClientGeneratorSettings settings)
        {
            _service  = service;
            _settings = settings;

            Class      = controllerName;
            Operations = operations;
        }
コード例 #22
0
 /// <summary>Generates the Swagger definition for the given controller.</summary>
 /// <param name="controllerClassName">The full name of the controller class.</param>
 /// <returns>The Swagger definition.</returns>
 public SwaggerService GenerateForController(string controllerClassName)
 {
     using (var isolated = new AppDomainIsolation <WebApiAssemblyLoader>(Path.GetDirectoryName(Settings.AssemblyPath)))
     {
         var service = isolated.Object.GenerateForController(controllerClassName, JsonConvert.SerializeObject(Settings));
         return(SwaggerService.FromJson(service));
     }
 }
コード例 #23
0
        private TSchemaType CreateAndAddSchema <TSchemaType>(SwaggerService service, Type type, ISchemaResolver schemaResolver)
            where TSchemaType : JsonSchema4, new()
        {
            if (type.Name == "Task`1")
            {
                type = type.GenericTypeArguments[0];
            }

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

            if (type.Name == "IHttpActionResult" || type.Name == "HttpResponseMessage" || type.InheritsFrom("HttpResponseMessage"))
            {
                type = typeof(object);
            }

            var info = JsonObjectTypeDescription.FromType(type);

            if (info.Type.HasFlag(JsonObjectType.Object))
            {
                if (type == typeof(object))
                {
                    return(new TSchemaType
                    {
                        Type = JsonObjectType.Object,
                        AllowAdditionalProperties = false
                    });
                }

                if (!schemaResolver.HasSchema(type, false))
                {
                    var schemaGenerator = new RootTypeJsonSchemaGenerator(service, Settings);
                    schemaGenerator.Generate <JsonSchema4>(type, schemaResolver);
                }

                return(new TSchemaType
                {
                    Type = JsonObjectType.Object,
                    SchemaReference = schemaResolver.GetSchema(type, false)
                });
            }

            if (info.Type.HasFlag(JsonObjectType.Array))
            {
                var itemType = type.GenericTypeArguments.Length == 0 ? type.GetElementType() : type.GenericTypeArguments[0];
                return(new TSchemaType
                {
                    Type = JsonObjectType.Array,
                    Item = CreateAndAddSchema <JsonSchema4>(service, itemType, schemaResolver)
                });
            }

            var generator = new RootTypeJsonSchemaGenerator(service, Settings);

            return(generator.Generate <TSchemaType>(type, schemaResolver));
        }
コード例 #24
0
        /// <summary>Initializes a new instance of the <see cref="SwaggerToCSharpGenerator"/> class.</summary>
        /// <param name="service">The service.</param>
        /// <exception cref="ArgumentNullException"><paramref name="service"/> is <see langword="null" />.</exception>
        public SwaggerToCSharpGenerator(SwaggerService service)
        {
            if (service == null)
                throw new ArgumentNullException("service");

            _service = service;
            _resolver = new CSharpTypeResolver(_service.Definitions.Select(p => p.Value).ToArray());
            //            _types = _service.Definitions.ToDictionary(t => t.Key, t => new CSharpClassGenerator(t.Value, _resolver));
        }
コード例 #25
0
        internal List <OperationModel> GetOperations <TGenerator>(SwaggerService service, TypeResolverBase <TGenerator> resolver)
            where TGenerator : TypeGeneratorBase
        {
            service.GenerateOperationIds();

            var operations = service.Paths
                             .SelectMany(pair => pair.Value.Select(p => new { Path = pair.Key.Trim('/'), HttpMethod = p.Key, Operation = p.Value }))
                             .Select(tuple =>
            {
                var operation = tuple.Operation;
                var responses = operation.Responses.Select(r => new ResponseModel(this)
                {
                    StatusCode = r.Key,
                    Schema     = r.Value.Schema?.ActualSchema
                }).ToList();

                var defaultResponse = responses.SingleOrDefault(r => r.StatusCode == "default");
                if (defaultResponse != null)
                {
                    responses.Remove(defaultResponse);
                }

                return(new OperationModel
                {
                    Path = tuple.Path,
                    HttpMethod = tuple.HttpMethod,
                    Operation = tuple.Operation,
                    OperationName = BaseSettings.OperationNameGenerator.GetOperationName(service, tuple.Path, tuple.HttpMethod, tuple.Operation),
                    ResultType = GetResultType(operation),
                    HasResultType = HasResultType(operation),
                    ResultDescription = GetResultDescription(operation),
                    ExceptionType = GetExceptionType(operation),
                    Responses = responses,
                    DefaultResponse = defaultResponse,
                    Parameters = operation.Parameters.Select(p =>
                    {
                        if (p.ActualSchema.Type == JsonObjectType.File)
                        {
                            p.ActualSchema.Type = JsonObjectType.String;     // TODO: Implement File type handling
                        }
                        return new ParameterModel
                        {
                            Schema = p.ActualSchema,
                            Name = p.Name,
                            VariableNameLower = ConvertToLowerCamelCase(p.Name.Replace("-", "_")),
                            Kind = p.Kind,
                            IsRequired = p.IsRequired,
                            Type = resolver.Resolve(p.ActualSchema, p.Type.HasFlag(JsonObjectType.Null), p.Name),
                            IsLast = operation.Parameters.LastOrDefault() == p,
                            Description = RemoveLineBreaks(p.Description)
                        };
                    }).ToList(),
                });
            }).ToList();

            return(operations);
        }
コード例 #26
0
ファイル: ClientTemplateModel.cs プロジェクト: rkalasky/NSwag
        /// <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="service">The service.</param>
        /// <param name="settings">The settings.</param>
        public ClientTemplateModel(string controllerName, string controllerClassName, IList <OperationModel> operations, SwaggerService service, SwaggerToCSharpClientGeneratorSettings settings)
        {
            _service  = service;
            _settings = settings;

            Class          = controllerClassName;
            ExceptionClass = _settings.ExceptionClass.Replace("{controller}", controllerName);
            Operations     = operations;
        }
コード例 #27
0
ファイル: FileTemplateModel.cs プロジェクト: cpx86/NSwag
 /// <summary>Initializes a new instance of the <see cref="FileTemplateModel" /> class.</summary>
 /// <param name="clientCode"></param>
 /// <param name="outputType"></param>
 /// <param name="service">The service.</param>
 /// <param name="settings">The settings.</param>
 /// <param name="resolver">The resolver.</param>
 public FileTemplateModel(string clientCode, ClientGeneratorOutputType outputType, SwaggerService service,
                          SwaggerToCSharpGeneratorSettings settings, SwaggerToCSharpTypeResolver resolver)
 {
     _clientCode = clientCode;
     _outputType = outputType;
     _service    = service;
     _settings   = settings;
     _resolver   = resolver;
 }
コード例 #28
0
        /// <summary>
        /// Create a new <see cref="JabTestConfiguration"/>.
        /// </summary>
        /// <param name="swaggerJson">
        /// The Swagger file to use for the test. This cannot be null, empty or whitespace.
        /// </param>
        /// <param name="baseUrl">
        /// An optional base URL to test against.
        /// </param>
        public JabTestConfiguration(string swaggerJson, Uri baseUrl)
        {
            if (string.IsNullOrWhiteSpace(swaggerJson))
            {
                throw new ArgumentException("Cannot be null, empty or whitespace", nameof(swaggerJson));
            }

            SwaggerService = SwaggerService.FromJson(swaggerJson);
            BaseUrl        = baseUrl;
        }
コード例 #29
0
        /// <summary>Generates a Swagger specification for the given controller type.</summary>
        /// <param name="controllerType">The type of the controller.</param>
        /// <param name="excludedMethodName">The name of the excluded method name.</param>
        /// <returns>The <see cref="SwaggerService" />.</returns>
        /// <exception cref="InvalidOperationException">The operation has more than one body parameter.</exception>
        public SwaggerService GenerateForController(Type controllerType, string excludedMethodName = "Swagger")
        {
            var service        = new SwaggerService();
            var schemaResolver = new SchemaResolver();

            GenerateForController(service, controllerType, excludedMethodName, schemaResolver);

            service.GenerateOperationIds();
            return(service);
        }
コード例 #30
0
            internal string FromAssemblyType(string assemblyPath, string className)
            {
                var assembly = Assembly.LoadFrom(assemblyPath);
                var type = assembly.GetType(className);

                var service = new SwaggerService();
                var schema = JsonSchema4.FromType(type);
                service.Definitions[type.Name] = schema;
                return service.ToJson();
            }
コード例 #31
0
        /// <summary>Generates the Swagger definition for all controllers in the assembly.</summary>
        /// <param name="urlTemplate">The default Web API URL template.</param>
        /// <returns>The Swagger definition.</returns>
        public SwaggerService GenerateForAssemblyControllers(string urlTemplate)
        {
            using (var isolated = new AppDomainIsolation <AssemblyLoader>(Path.GetDirectoryName(_assemblyPath)))
            {
                var service = isolated.Object.GenerateForAssemblyControllers(
                    _assemblyPath, urlTemplate, JsonConvert.SerializeObject(JsonSchemaGeneratorSettings));

                return(SwaggerService.FromJson(service));
            }
        }
コード例 #32
0
        /// <exception cref="InvalidOperationException">The operation has more than one body parameter.</exception>
        private void LoadParameters(SwaggerService service, SwaggerOperation operation, List <ParameterInfo> parameters, ISchemaResolver schemaResolver)
        {
            foreach (var parameter in parameters)
            {
                var parameterInfo = JsonObjectTypeDescription.FromType(parameter.ParameterType, parameter.GetCustomAttributes(), Settings.DefaultEnumHandling);
                if (TryAddFileParameter(parameterInfo, service, operation, schemaResolver, parameter) == false)
                {
                    // http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx

                    dynamic fromBodyAttribute = parameter.GetCustomAttributes()
                                                .SingleOrDefault(a => a.GetType().Name == "FromBodyAttribute");

                    dynamic fromUriAttribute = parameter.GetCustomAttributes()
                                               .SingleOrDefault(a => a.GetType().Name == "FromUriAttribute");

                    // TODO: Add support for ModelBinder attribute

                    if (parameterInfo.IsComplexType)
                    {
                        if (fromUriAttribute != null)
                        {
                            AddPrimitiveParametersFromUri(service, operation, parameter, schemaResolver);
                        }
                        else
                        {
                            AddBodyParameter(service, operation, parameter, schemaResolver);
                        }
                    }
                    else
                    {
                        if (fromBodyAttribute != null)
                        {
                            AddBodyParameter(service, operation, parameter, schemaResolver);
                        }
                        else
                        {
                            AddPrimitiveParameter(service, operation, parameter, schemaResolver);
                        }
                    }
                }
            }

            if (operation.Parameters.Any(p => p.Type == JsonObjectType.File))
            {
                operation.Consumes = new List <string> {
                    "multipart/form-data"
                }
            }
            ;

            if (operation.Parameters.Count(p => p.Kind == SwaggerParameterKind.Body) > 1)
            {
                throw new InvalidOperationException("The operation '" + operation.OperationId + "' has more than one body parameter.");
            }
        }
コード例 #33
0
        /// <summary>Initializes a new instance of the <see cref="SwaggerToTypeScriptGenerator"/> class.</summary>
        /// <param name="service">The service.</param>
        /// <exception cref="ArgumentNullException"><paramref name="service"/> is <see langword="null" />.</exception>
        public SwaggerToTypeScriptGenerator(SwaggerService service)
        {
            if (service == null)
                throw new ArgumentNullException("service");

            Class = "Client";
            AsyncType = TypeScriptAsyncType.Callbacks;

            _service = service;
            _resolver = new TypeScriptTypeResolver(_service.Definitions.Select(p => p.Value).ToArray());
        }
コード例 #34
0
        /// <summary>Initializes a new instance of the <see cref="SwaggerToCSharpGenerator"/> class.</summary>
        /// <param name="service">The service.</param>
        /// <exception cref="ArgumentNullException"><paramref name="service"/> is <see langword="null" />.</exception>
        public SwaggerToCSharpGenerator(SwaggerService service)
        {
            if (service == null)
                throw new ArgumentNullException("service");

            _service = service;

            foreach (var definition in _service.Definitions)
                definition.Value.TypeName = definition.Key;

            _resolver = new SwaggerToCSharpTypeResolver(_service.Definitions);
        }
コード例 #35
0
        /// <summary>Initializes a new instance of the <see cref="SwaggerToCSharpWebApiControllerGenerator" /> class.</summary>
        /// <param name="service">The service.</param>
        /// <param name="settings">The settings.</param>
        /// <exception cref="System.ArgumentNullException">service</exception>
        /// <exception cref="ArgumentNullException"><paramref name="service" /> is <see langword="null" />.</exception>
        public SwaggerToCSharpWebApiControllerGenerator(SwaggerService service, SwaggerToCSharpWebApiControllerGeneratorSettings settings) 
            : base(service, settings.CSharpGeneratorSettings)
        {
            if (service == null)
                throw new ArgumentNullException("service");

            Settings = settings; 

            _service = service;
            foreach (var definition in _service.Definitions)
                definition.Value.TypeName = definition.Key;
        }
コード例 #36
0
        /// <summary>Initializes a new instance of the <see cref="SwaggerToTypeScriptGenerator" /> class.</summary>
        /// <param name="service">The service.</param>
        /// <param name="settings">The settings.</param>
        /// <exception cref="System.ArgumentNullException">service</exception>
        /// <exception cref="ArgumentNullException"><paramref name="service" /> is <see langword="null" />.</exception>
        public SwaggerToTypeScriptGenerator(SwaggerService service, SwaggerToTypeScriptGeneratorSettings settings)
        {
            if (service == null)
                throw new ArgumentNullException("service");

            Settings = settings;

            _service = service;
            foreach (var definition in _service.Definitions)
                definition.Value.TypeName = definition.Key;

            _resolver = new TypeScriptTypeResolver(_service.Definitions.Select(p => p.Value).ToArray());
        }
コード例 #37
0
        /// <summary>Initializes a new instance of the <see cref="SwaggerToTypeScriptGenerator"/> class.</summary>
        /// <param name="service">The service.</param>
        /// <exception cref="ArgumentNullException"><paramref name="service"/> is <see langword="null" />.</exception>
        public SwaggerToTypeScriptGenerator(SwaggerService service)
        {
            if (service == null)
                throw new ArgumentNullException("service");

            Class = "{controller}Client";
            AsyncType = TypeScriptAsyncType.Callbacks;

            _service = service;

            foreach (var definition in _service.Definitions)
                definition.Value.TypeName = definition.Key;

            _resolver = new TypeScriptTypeResolver(_service.Definitions.Select(p => p.Value).ToArray());
        }
コード例 #38
0
            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();
            }
コード例 #39
0
ファイル: OperationIdTests.cs プロジェクト: chenkaibin/NSwag
        public void When_generating_operation_id()
        {
            //// Arrange
            var service = new SwaggerService();
            service.Paths["path"] = new SwaggerOperations
            {
                {
                    SwaggerOperationMethod.get,
                    new SwaggerOperation { }
                },
                {
                    SwaggerOperationMethod.post,
                    new SwaggerOperation { }
                }
            };

            //// Act
            service.GenerateOperationIds();

            //// Assert
            Assert.IsTrue(service.Operations.GroupBy(o => o.Operation.OperationId).All(g => g.Count() == 1));
        }
コード例 #40
0
        public void When_using_json_schema_with_references_in_service_then_references_are_correctly_resolved()
        {
            //// Arrange
            var jsonSchema = @"{
  ""definitions"": {
    ""app"": {
      ""definitions"": {
        ""name"": {
          ""pattern"": ""^[a-z][a-z0-9-]{3,30}$"",
          ""type"": ""string""
        }
      },
      ""properties"": {
        ""name"": {
          ""$ref"": ""#/definitions/app/definitions/name""
        }
      },
      ""required"": [""name""],
      ""type"": ""object""
    }
  },
  ""properties"": {
    ""app"": {
      ""$ref"": ""#/definitions/app""
    },
  },
  ""type"": ""object""
}";

            //// Act
            var schema = JsonSchema4.FromJson(jsonSchema);
            var service = new SwaggerService();
            service.Definitions["Foo"] = schema;

            //// Assert
            var jsonService = service.ToJson(); // no exception expected
        }
コード例 #41
0
            internal string FromAssemblyType(string assemblyPath, string className, string jsonSchemaGeneratorSettingsData)
            {
                var jsonSchemaGeneratorSettings = JsonConvert.DeserializeObject<JsonSchemaGeneratorSettings>(jsonSchemaGeneratorSettingsData);

                var assembly = Assembly.LoadFrom(assemblyPath);
                var type = assembly.GetType(className);

                var service = new SwaggerService();
                var schema = JsonSchema4.FromType(type, jsonSchemaGeneratorSettings);
                service.Definitions[type.Name] = schema;
                return service.ToJson();
            }
コード例 #42
0
 internal SwaggerToCSharpGenerator(SwaggerService service, CSharpGeneratorSettings settings)
 {
     Resolver = new SwaggerToCSharpTypeResolver(settings, service.Definitions);
 }
コード例 #43
0
 private static SwaggerService CreateService()
 {
     var service = new SwaggerService();
     service.Paths["/Person"] = new SwaggerOperations();
     service.Paths["/Person"][SwaggerOperationMethod.Get] = new SwaggerOperation
     {
         Responses = new Dictionary<string, SwaggerResponse>
         {
             {
                 "200", new SwaggerResponse
                 {
                     Schema = JsonSchema4.FromType(typeof (Person))
                 }
             }
         }
     };
     return service;
 }