Ejemplo n.º 1
0
        internal override string GetExceptionType(SwaggerOperation operation)
        {
            if (operation.Responses.Count(r => r.Key != "200") != 1)
                return "Exception";

            return GetType(operation.Responses.Single(r => r.Key != "200").Value.Schema, "Exception");
        }
Ejemplo n.º 2
0
        internal override string GetExceptionType(SwaggerOperation operation)
        {
            if (operation.Responses.Count(r => !HttpUtilities.IsSuccessStatusCode(r.Key)) != 1)
                return "Exception";

            return GetType(operation.Responses.Single(r => !HttpUtilities.IsSuccessStatusCode(r.Key)).Value.Schema, "Exception");
        }
Ejemplo n.º 3
0
 internal string GetResultDescription(SwaggerOperation operation)
 {
     var response = GetSuccessResponse(operation);
     if (response != null)
         return ConversionUtilities.TrimWhiteSpaces(response.Description);
     return null;
 }
Ejemplo n.º 4
0
        internal override string GetResultType(SwaggerOperation operation)
        {
            var response = GetSuccessResponse(operation);
            if (response == null)
                return "Task";

            return "Task<" + GetType(response.Schema, "Response") + ">";
        }
Ejemplo n.º 5
0
        internal override string GetResultType(SwaggerOperation operation)
        {
            var response = GetSuccessResponse(operation);
            if (response?.Schema == null)
                return "System.Threading.Tasks.Task";

            return "System.Threading.Tasks.Task<" + GetType(response.ActualResponseSchema, response.IsNullable(BaseSettings.CodeGeneratorSettings.NullHandling), "Response") + ">";
        }
Ejemplo n.º 6
0
        internal override string GetExceptionType(SwaggerOperation operation)
        {
            if (operation.Responses.Count(r => !HttpUtilities.IsSuccessStatusCode(r.Key)) != 1)
                return "System.Exception";

            var response = operation.Responses.Single(r => !HttpUtilities.IsSuccessStatusCode(r.Key)).Value;
            return GetType(response.ActualResponseSchema, response.IsNullable(BaseSettings.CodeGeneratorSettings.NullHandling), "Exception");
        }
Ejemplo n.º 7
0
        /// <summary>Initializes a new instance of the <see cref="ParameterModel" /> class.</summary>
        /// <param name="typeName">The type name.</param>
        /// <param name="operation">The operation.</param>
        /// <param name="parameter">The parameter.</param>
        /// <param name="parameterName">Name of the parameter.</param>
        /// <param name="variableName">Name of the variable.</param>
        /// <param name="settings">The settings.</param>
        /// <param name="clientGeneratorBase">The client generator base.</param>
        public ParameterModel(string typeName, SwaggerOperation operation, SwaggerParameter parameter, 
            string parameterName, string variableName, CodeGeneratorSettingsBase settings, ClientGeneratorBase clientGeneratorBase)
        {
            Type = typeName;
            Name = parameterName;
            VariableName = variableName;

            _operation = operation;
            _parameter = parameter;
            _settings = settings;
            _clientGeneratorBase = clientGeneratorBase;
        }
        /// <summary>Gets the operation name for a given operation.</summary>
        /// <param name="document">The Swagger document.</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(SwaggerDocument document, string path, SwaggerOperationMethod httpMethod, SwaggerOperation operation)
        {
            var clientName = GetClientName(operation);
            var operationName = GetOperationName(operation);

            var hasOperationWithSameName = document.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;
        }
Ejemplo n.º 9
0
 /// <summary>Gets the client name for a given operation (may be empty).</summary>
 /// <param name="document">The Swagger document.</param>
 /// <param name="path">The HTTP path.</param>
 /// <param name="httpMethod">The HTTP method.</param>
 /// <param name="operation">The operation.</param>
 /// <returns>The client name.</returns>
 public virtual string GetClientName(SwaggerDocument document, string path, string httpMethod, SwaggerOperation operation)
 {
     return(GetClientName(operation));
 }
Ejemplo n.º 10
0
 /// <summary>Creates the response model.</summary>
 /// <param name="operation">The operation.</param>
 /// <param name="statusCode">The status code.</param>
 /// <param name="response">The response.</param>
 /// <param name="exceptionSchema">The exception schema.</param>
 /// <param name="generator">The generator.</param>
 /// <param name="resolver">The resolver.</param>
 /// <param name="settings">The settings.</param>
 /// <returns>The response model.</returns>
 protected abstract TResponseModel CreateResponseModel(SwaggerOperation operation, string statusCode, SwaggerResponse response, JsonSchema4 exceptionSchema, IClientGenerator generator,
                                                       TypeResolverBase resolver, ClientGeneratorBaseSettings settings);
Ejemplo n.º 11
0
        internal override string GetResultType(SwaggerOperation operation)
        {
            if (operation.Responses.Count(r => HttpUtilities.IsSuccessStatusCode(r.Key)) == 0)
                return "Task";

            var response = GetOkResponse(operation);
            return "Task<" + GetType(response.Schema, "Response") + ">";
        }
Ejemplo n.º 12
0
 internal abstract string GetExceptionType(SwaggerOperation operation);
 /// <summary>Gets the client name for a given operation.</summary>
 /// <param name="document">The Swagger document.</param>
 /// <param name="path">The HTTP path.</param>
 /// <param name="httpMethod">The HTTP method.</param>
 /// <param name="operation">The operation.</param>
 /// <returns>The client name.</returns>
 public string GetClientName(SwaggerDocument document, string path, SwaggerOperationMethod httpMethod, SwaggerOperation operation)
 {
     return GetClientName(operation);
 }
Ejemplo n.º 14
0
        internal override string GetResultType(SwaggerOperation operation)
        {
            if (operation.Responses.Count(r => r.Key == "200") == 0)
                return "void";

            var response = GetOkResponse(operation);
            return GetType(response.Schema, "Response");
        }
Ejemplo n.º 15
0
        private void AddPrimitiveParametersFromUri(string name, SwaggerOperation operation, ParameterInfo parameter, JsonObjectTypeDescription typeDescription, SwaggerGenerator swaggerGenerator)
        {
            if (typeDescription.Type.HasFlag(JsonObjectType.Array))
            {
                var operationParameter = swaggerGenerator.CreatePrimitiveParameter(name,
                    parameter.GetXmlDocumentation(), parameter.ParameterType.GetEnumerableItemType(), parameter.GetCustomAttributes().ToList());

                operationParameter.Kind = SwaggerParameterKind.Query;
                operationParameter.CollectionFormat = SwaggerParameterCollectionFormat.Multi;
                operation.Parameters.Add(operationParameter);
            }
            else
            {
                foreach (var property in parameter.ParameterType.GetRuntimeProperties())
                {
                    var attributes = property.GetCustomAttributes().ToList();
                    var fromQueryAttribute = attributes.SingleOrDefault(a => a.GetType().Name == "FromQueryAttribute");

                    var propertyName = TryGetStringPropertyValue(fromQueryAttribute, "Name") ?? JsonPathUtilities.GetPropertyName(property, _settings.DefaultPropertyNameHandling);
                    var operationParameter = swaggerGenerator.CreatePrimitiveParameter(propertyName, property.GetXmlSummary(), property.PropertyType, attributes);

                    // 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);
                }
            }
        }
Ejemplo n.º 16
0
        private void AddBodyParameter(SwaggerService service, SwaggerOperation operation, ParameterInfo parameter, ISchemaResolver schemaResolver)
        {
            var operationParameter = CreateBodyParameter(service, parameter, schemaResolver);

            operation.Parameters.Add(operationParameter);
        }
Ejemplo n.º 17
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 xmlDescription = method.ReturnParameter.GetXmlDocumentation();

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

            var typeDescription = JsonObjectTypeDescription.FromType(returnType, method.ReturnParameter?.GetCustomAttributes(), Settings.DefaultEnumHandling);
            var mayBeNull       = typeDescription.IsNullable;

            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 description = xmlDescription;
                    if (responseTypeAttribute.GetType().GetRuntimeProperty("Description") != null)
                    {
                        if (!string.IsNullOrEmpty(dynResultTypeAttribute.Description))
                        {
                            description = dynResultTypeAttribute.Description;
                        }
                    }

                    operation.Responses[httpStatusCode] = new SwaggerResponse
                    {
                        Description   = description ?? string.Empty,
                        IsNullableRaw = mayBeNull,
                        Schema        = CreateAndAddSchema(service, returnType, mayBeNull, null, schemaResolver)
                    };
                }
            }
            else
            {
                if (IsVoidResponse(returnType))
                {
                    operation.Responses["204"] = new SwaggerResponse();
                }
                else
                {
                    operation.Responses["200"] = new SwaggerResponse
                    {
                        Description   = xmlDescription ?? string.Empty,
                        IsNullableRaw = mayBeNull,
                        Schema        = CreateAndAddSchema(service, returnType, mayBeNull, null, schemaResolver)
                    };
                }
            }
        }
Ejemplo n.º 18
0
        static string GetClassName(SwaggerOperation watchOperation)
        {
            var groupVersionKind = (Dictionary <string, object>)watchOperation.ExtensionData["x-kubernetes-group-version-kind"];

            return(GetClassName(groupVersionKind));
        }
Ejemplo n.º 19
0
        private bool TryAddFileParameter(JsonObjectTypeDescription info, SwaggerService service, SwaggerOperation operation, ISchemaResolver schemaResolver, ParameterInfo parameter)
        {
            var isFileArray = IsFileArray(parameter.ParameterType, info);

            if (info.Type == JsonObjectType.File || isFileArray)
            {
                AddFileParameter(parameter, isFileArray, operation, service, schemaResolver);
                return(true);
            }

            return(false);
        }
Ejemplo n.º 20
0
        private static async Task AddInternalErrorResponseAsync(OperationProcessorContext context, SwaggerOperation operation)
        {
            if (operation.Responses.ContainsKey("500"))
            {
                return;
            }

            operation.AddResponse("500", "Operation failed", await context.SchemaGenerator.GetErrorDtoSchemaAsync(context.SchemaResolver));
        }
Ejemplo n.º 21
0
        private void LoadReturnType(SwaggerOperation operation, MethodInfo method, SwaggerGenerator swaggerGenerator)
        {
            var successXmlDescription = method.ReturnParameter.GetXmlDocumentation() ?? string.Empty;

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

            var producesResponseTypeAttributes = method.GetCustomAttributes()
                                                 .Where(a => a.GetType().Name == "ProducesResponseTypeAttribute")
                                                 .ToList();

            if (responseTypeAttributes.Any() || producesResponseTypeAttributes.Any())
            {
                foreach (var responseTypeAttribute in responseTypeAttributes)
                {
                    dynamic dynResultTypeAttribute = responseTypeAttribute;
                    var     returnType             = dynResultTypeAttribute.ResponseType;

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

                    var description = HttpUtilities.IsSuccessStatusCode(httpStatusCode) ? successXmlDescription : string.Empty;
                    if (responseTypeAttribute.GetType().GetRuntimeProperty("Description") != null)
                    {
                        if (!string.IsNullOrEmpty(dynResultTypeAttribute.Description))
                        {
                            description = dynResultTypeAttribute.Description;
                        }
                    }

                    var typeDescription = JsonObjectTypeDescription.FromType(returnType, method.ReturnParameter?.GetCustomAttributes(), Settings.DefaultEnumHandling);
                    var response        = new SwaggerResponse
                    {
                        Description = description ?? string.Empty
                    };

                    if (IsVoidResponse(returnType) == false)
                    {
                        response.IsNullableRaw = typeDescription.IsNullable;
                        response.Schema        = swaggerGenerator.GenerateAndAppendSchemaFromType(returnType, typeDescription.IsNullable, null);
                    }

                    operation.Responses[httpStatusCode] = response;
                }

                foreach (dynamic producesResponseTypeAttribute in producesResponseTypeAttributes)
                {
                    var returnType      = producesResponseTypeAttribute.Type;
                    var typeDescription = JsonObjectTypeDescription.FromType(returnType, method.ReturnParameter?.GetCustomAttributes(), Settings.DefaultEnumHandling);

                    var httpStatusCode = producesResponseTypeAttribute.StatusCode.ToString(CultureInfo.InvariantCulture);
                    var response       = new SwaggerResponse
                    {
                        Description = HttpUtilities.IsSuccessStatusCode(httpStatusCode) ? successXmlDescription : string.Empty
                    };

                    if (IsVoidResponse(returnType) == false)
                    {
                        response.IsNullableRaw = typeDescription.IsNullable;
                        response.Schema        = swaggerGenerator.GenerateAndAppendSchemaFromType(returnType, typeDescription.IsNullable, null);
                    }

                    operation.Responses[httpStatusCode] = response;
                }
            }
            else
            {
                LoadDefaultSuccessResponse(operation, method, successXmlDescription, swaggerGenerator);
            }
        }
Ejemplo n.º 22
0
        private void AddBodyParameter(string name, ParameterInfo parameter, SwaggerOperation operation, SwaggerGenerator swaggerGenerator)
        {
            var operationParameter = swaggerGenerator.CreateBodyParameter(name, parameter);

            operation.Parameters.Add(operationParameter);
        }
        internal override string GetResultType(SwaggerOperation operation)
        {
            var response = GetSuccessResponse(operation);
            if (response?.Schema == null)
                return "void";

            return GetType(response.ActualResponseSchema, response.IsNullable(Settings.CodeGeneratorSettings.NullHandling), "Response");
        }
Ejemplo n.º 24
0
 /// <summary>
 /// WebApiClient的请求方法数据模型
 /// </summary>
 /// <param name="operation">Swagger操作</param>
 /// <param name="settings">设置项</param>
 /// <param name="generator">代码生成器</param>
 /// <param name="resolver">语法解析器</param>
 public HttpApiMethod(SwaggerOperation operation, SwaggerToCSharpGeneratorSettings settings, SwaggerToCSharpGeneratorBase generator, CSharpTypeResolver resolver)
     : base(operation, settings, generator, resolver)
 {
 }
 /// <summary>Gets the client name for a given operation.</summary>
 /// <param name="document">The Swagger document.</param>
 /// <param name="path">The HTTP path.</param>
 /// <param name="httpMethod">The HTTP method.</param>
 /// <param name="operation">The operation.</param>
 /// <returns>The client name.</returns>
 public string GetOperationName(SwaggerDocument document, string path, SwaggerOperationMethod httpMethod, SwaggerOperation operation)
 {
     var pathSegments = path.Split('/').Where(p => !p.Contains("{")).Reverse().ToArray();
     return pathSegments.First();
 }
 /// <summary>
 ///     Gets the client name for a given operation.
 /// </summary>
 /// <param name="document">The Swagger document.</param>
 /// <param name="path">The HTTP path.</param>
 /// <param name="httpMethod">The HTTP method.</param>
 /// <param name="operation">The operation.</param>
 /// <returns>
 ///     The client name.
 /// </returns>
 public string GetClientName(SwaggerDocument document, string path, SwaggerOperationMethod httpMethod, SwaggerOperation operation)
 {
     return("HelloClient");
 }
Ejemplo n.º 27
0
        private void AddFileParameter(ParameterInfo parameter, bool isFileArray, SwaggerOperation operation, SwaggerGenerator swaggerGenerator)
        {
            var attributes = parameter.GetCustomAttributes().ToList();

            // TODO: Check if there is a way to control the property name
            var operationParameter = swaggerGenerator.CreatePrimitiveParameter(parameter.Name, parameter.GetXmlDocumentation(), parameter.ParameterType, attributes);

            InitializeFileParameter(operationParameter, isFileArray);
            operation.Parameters.Add(operationParameter);
        }
 /// <summary>
 ///     Gets the operation name for a given operation.
 /// </summary>
 /// <param name="document">The Swagger document.</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(SwaggerDocument document, string path, SwaggerOperationMethod httpMethod, SwaggerOperation operation)
 {
     return("assadasdasd");
 }
Ejemplo n.º 29
0
        internal override string GetExceptionType(SwaggerOperation operation)
        {
            if (operation.Responses.Count(r => !HttpUtilities.IsSuccessStatusCode(r.Key)) == 0)
                return "string";

            return string.Join(" | ", operation.Responses
                .Where(r => !HttpUtilities.IsSuccessStatusCode(r.Key) && r.Value.Schema != null)
                .Select(r => GetType(r.Value.Schema.ActualSchema, "Exception"))
                .Concat(new [] { "string" }));
        }
Ejemplo n.º 30
0
 /// <summary>Creates an operation model.</summary>
 /// <param name="operation">The operation.</param>
 /// <param name="settings">The settings.</param>
 /// <returns>The operation model.</returns>
 protected abstract TOperationModel CreateOperationModel(SwaggerOperation operation, ClientGeneratorBaseSettings settings);
Ejemplo n.º 31
0
 internal bool HasResultType(SwaggerOperation operation)
 {
     var response = GetSuccessResponse(operation);
     return response?.Schema != null;
 }
Ejemplo n.º 32
0
        private async Task <bool> TryAddFileParameterAsync(JsonObjectTypeDescription info, SwaggerOperation operation, ParameterInfo parameter, SwaggerGenerator swaggerGenerator)
        {
            var isFileArray = IsFileArray(parameter.ParameterType, info);

            if (info.Type == JsonObjectType.File || isFileArray)
            {
                await AddFileParameterAsync(parameter, isFileArray, operation, swaggerGenerator).ConfigureAwait(false);

                return(true);
            }

            return(false);
        }
Ejemplo n.º 33
0
        /// <exception cref="InvalidOperationException">The operation has more than one body parameter.</exception>
        private void LoadParameters(SwaggerOperation operation, List <ParameterInfo> parameters, string httpPath, SwaggerGenerator swaggerGenerator)
        {
            // TODO: Also check other attributes (e.g. FromHeader, ...)
            // https://docs.asp.net/en/latest/mvc/models/model-binding.html#customize-model-binding-behavior-with-attributes

            foreach (var parameter in parameters.Where(p => p.ParameterType != typeof(CancellationToken) &&
                                                       p.GetCustomAttributes().All(a => a.GetType().Name != "FromServicesAttribute") &&
                                                       p.GetCustomAttributes().All(a => a.GetType().Name != "BindNeverAttribute")))
            {
                var nameLower = parameter.Name.ToLowerInvariant();
                if (httpPath.ToLowerInvariant().Contains("{" + nameLower + "}") ||
                    httpPath.ToLowerInvariant().Contains("{" + nameLower + ":")) // path parameter
                {
                    var operationParameter = swaggerGenerator.CreatePrimitiveParameter(parameter.Name, parameter);
                    operationParameter.Kind          = SwaggerParameterKind.Path;
                    operationParameter.IsNullableRaw = false;
                    operationParameter.IsRequired    = true; // Path is always required => property not needed

                    operation.Parameters.Add(operationParameter);
                }
                else
                {
                    var parameterInfo = JsonObjectTypeDescription.FromType(parameter.ParameterType, parameter.GetCustomAttributes(), Settings.DefaultEnumHandling);
                    if (TryAddFileParameter(parameterInfo, operation, parameter, swaggerGenerator) == false)
                    {
                        dynamic fromBodyAttribute = parameter.GetCustomAttributes()
                                                    .SingleOrDefault(a => a.GetType().Name == "FromBodyAttribute");

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

                        var bodyParameterName = TryGetStringPropertyValue(fromBodyAttribute, "Name") ?? parameter.Name;
                        var uriParameterName  = TryGetStringPropertyValue(fromUriAttribute, "Name") ?? parameter.Name;

                        if (parameterInfo.IsComplexType)
                        {
                            if (fromBodyAttribute != null || (fromUriAttribute == null && Settings.IsAspNetCore == false))
                            {
                                AddBodyParameter(bodyParameterName, parameter, operation, swaggerGenerator);
                            }
                            else
                            {
                                AddPrimitiveParametersFromUri(uriParameterName, operation, parameter, parameterInfo, swaggerGenerator);
                            }
                        }
                        else
                        {
                            if (fromBodyAttribute != null)
                            {
                                AddBodyParameter(bodyParameterName, parameter, operation, swaggerGenerator);
                            }
                            else
                            {
                                AddPrimitiveParameter(uriParameterName, operation, parameter, swaggerGenerator);
                            }
                        }
                    }
                }
            }

            if (Settings.AddMissingPathParameters)
            {
                foreach (Match match in Regex.Matches(httpPath, "{(.*?)(:(.*?))?}"))
                {
                    var parameterName = match.Groups[1].Value;
                    if (operation.Parameters.All(p => p.Name != parameterName))
                    {
                        var parameterType      = match.Groups.Count == 4 ? match.Groups[3].Value : "string";
                        var operationParameter = swaggerGenerator.CreatePathParameter(parameterName, parameterType);
                        operation.Parameters.Add(operationParameter);
                    }
                }
            }

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

            if (operation.ActualParameters.Count(p => p.Kind == SwaggerParameterKind.Body) > 1)
            {
                throw new InvalidOperationException("The operation '" + operation.OperationId + "' has more than one body parameter.");
            }
        }
Ejemplo n.º 34
0
        private async Task AddFileParameterAsync(ParameterInfo parameter, bool isFileArray, SwaggerOperation operation, SwaggerGenerator swaggerGenerator)
        {
            var attributes = parameter.GetCustomAttributes().ToList();

            // TODO: Check if there is a way to control the property name
            var parameterDocumentation = await parameter.GetDescriptionAsync(parameter.GetCustomAttributes()).ConfigureAwait(false);

            var operationParameter = await swaggerGenerator.CreatePrimitiveParameterAsync(parameter.Name, parameterDocumentation, parameter.ParameterType, attributes).ConfigureAwait(false);

            InitializeFileParameter(operationParameter, isFileArray);
            operation.Parameters.Add(operationParameter);
        }
 /// <summary>Gets the client name for a given operation.</summary>
 /// <param name="document">The Swagger document.</param>
 /// <param name="path">The HTTP path.</param>
 /// <param name="httpMethod">The HTTP method.</param>
 /// <param name="operation">The operation.</param>
 /// <returns>The client name.</returns>
 public string GetOperationName(SwaggerDocument document, string path, SwaggerOperationMethod httpMethod, SwaggerOperation operation)
 {
     return operation.OperationId; 
 }
Ejemplo n.º 36
0
        private async Task AddBodyParameterAsync(string name, ParameterInfo parameter, SwaggerOperation operation, SwaggerGenerator swaggerGenerator)
        {
            if (parameter.ParameterType.Name == "XmlDocument" || parameter.ParameterType.InheritsFrom("XmlDocument", TypeNameStyle.Name))
            {
                operation.Consumes = new List <string> {
                    "application/xml"
                };
                operation.Parameters.Add(new SwaggerParameter
                {
                    Name          = name,
                    Kind          = SwaggerParameterKind.Body,
                    IsRequired    = parameter.HasDefaultValue == false,
                    IsNullableRaw = true,
                    Description   = await parameter.GetDescriptionAsync(parameter.GetCustomAttributes()).ConfigureAwait(false)
                });
            }
            else
            {
                var operationParameter = await swaggerGenerator.CreateBodyParameterAsync(name, parameter).ConfigureAwait(false);

                operation.Parameters.Add(operationParameter);
            }
        }
Ejemplo n.º 37
0
        /// <summary>Gets the operation name for a given operation.</summary>
        /// <param name="document">The Swagger document.</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 virtual string GetOperationName(SwaggerDocument document, string path, string httpMethod, SwaggerOperation operation)
        {
            var clientName    = GetClientName(operation);
            var operationName = GetOperationName(operation);

            var hasOperationWithSameName = document.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.ActualResponses.ContainsKey("200") &&
                                          operation.ActualResponses["200"].ActualResponseSchema != null &&
                                          operation.ActualResponses["200"].ActualResponseSchema.Type.HasFlag(JsonObjectType.Array);

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

            return(operationName);
        }
Ejemplo n.º 38
0
        private async Task AddPrimitiveParametersFromUriAsync(string httpPath, string name, SwaggerOperation operation, ParameterInfo parameter, JsonObjectTypeDescription typeDescription, SwaggerGenerator swaggerGenerator)
        {
            if (typeDescription.Type.HasFlag(JsonObjectType.Array))
            {
                var parameterDocumentation = await parameter.GetDescriptionAsync(parameter.GetCustomAttributes()).ConfigureAwait(false);

                var operationParameter = await swaggerGenerator.CreatePrimitiveParameterAsync(name, parameterDocumentation,
                                                                                              parameter.ParameterType, parameter.GetCustomAttributes().ToList()).ConfigureAwait(false);

                operationParameter.Kind = SwaggerParameterKind.Query;
                operation.Parameters.Add(operationParameter);
            }
            else
            {
                foreach (var property in parameter.ParameterType.GetRuntimeProperties())
                {
                    var attributes = property.GetCustomAttributes().ToList();
                    if (attributes.All(a => a.GetType().Name != "SwaggerIgnoreAttribute" && a.GetType().Name != "JsonIgnoreAttribute"))
                    {
                        var fromQueryAttribute = attributes.SingleOrDefault(a => a.GetType().Name == "FromQueryAttribute");
                        var propertyName       = TryGetStringPropertyValue(fromQueryAttribute, "Name") ?? JsonReflectionUtilities.GetPropertyName(property, _settings.DefaultPropertyNameHandling);

                        dynamic fromRouteAttribute = attributes.SingleOrDefault(a => a.GetType().FullName == "Microsoft.AspNetCore.Mvc.FromRouteAttribute");
                        if (fromRouteAttribute != null && !string.IsNullOrEmpty(fromRouteAttribute?.Name))
                        {
                            propertyName = fromRouteAttribute?.Name;
                        }

                        dynamic fromHeaderAttribute = attributes.SingleOrDefault(a => a.GetType().FullName == "Microsoft.AspNetCore.Mvc.FromHeaderAttribute");
                        if (fromHeaderAttribute != null && !string.IsNullOrEmpty(fromHeaderAttribute?.Name))
                        {
                            propertyName = fromHeaderAttribute?.Name;
                        }

                        var propertySummary = await property.GetXmlSummaryAsync().ConfigureAwait(false);

                        var operationParameter = await swaggerGenerator.CreatePrimitiveParameterAsync(propertyName, propertySummary, property.PropertyType, attributes).ConfigureAwait(false);

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

                        var parameterInfo = JsonObjectTypeDescription.FromType(property.PropertyType, _settings.ResolveContract(property.PropertyType), attributes, _settings.DefaultEnumHandling);
                        var isFileArray   = IsFileArray(property.PropertyType, parameterInfo);
                        if (parameterInfo.Type == JsonObjectType.File || isFileArray)
                        {
                            InitializeFileParameter(operationParameter, isFileArray);
                        }
                        else if (fromRouteAttribute != null ||
                                 httpPath.ToLowerInvariant().Contains("{" + propertyName.ToLower() + "}") ||
                                 httpPath.ToLowerInvariant().Contains("{" + propertyName.ToLower() + ":"))
                        {
                            operationParameter.Kind          = SwaggerParameterKind.Path;
                            operationParameter.IsNullableRaw = false;
                            operationParameter.IsRequired    = true; // Path is always required => property not needed
                        }
                        else if (fromHeaderAttribute != null)
                        {
                            operationParameter.Kind = SwaggerParameterKind.Header;
                        }
                        else
                        {
                            operationParameter.Kind = SwaggerParameterKind.Query;
                        }

                        operation.Parameters.Add(operationParameter);
                    }
                }
            }
        }
        private string GetResultType(SwaggerOperation operation)
        {
            if (operation.Responses.Count(r => r.Key == "200") == 0)
                return "void";

            if (operation.Responses.Count(r => r.Key == "200") != 1)
                return "any";

            var response = operation.Responses.Single(r => r.Key == "200").Value;
            return GetType(response.Schema, "Response");
        }
Ejemplo n.º 40
0
        /// <summary>Gets the client 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 client name.</returns>
        public string GetClientName(SwaggerService service, string path, SwaggerOperationMethod httpMethod, SwaggerOperation operation)
        {
            var pathSegments = path.Split('/').Where(p => !p.Contains("{")).Reverse().ToArray();

            return(pathSegments.Length >= 2 ? pathSegments[1] : string.Empty);
        }
 /// <summary>Creates an operation model.</summary>
 /// <param name="operation">The operation.</param>
 /// <param name="settings">The settings.</param>
 /// <returns>The operation model.</returns>
 protected override CSharpOperationModel CreateOperationModel(SwaggerOperation operation, ClientGeneratorBaseSettings settings)
 {
     return(new CSharpControllerOperationModel(operation, (SwaggerToCSharpControllerGeneratorSettings)settings, this, (CSharpTypeResolver)Resolver));
 }
Ejemplo n.º 42
0
        /// <summary>Gets the client 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 client name.</returns>
        public string GetOperationName(SwaggerService service, string path, SwaggerOperationMethod httpMethod, SwaggerOperation operation)
        {
            var pathSegments = path.Split('/').Where(p => !p.Contains("{")).Reverse().ToArray();

            return(pathSegments.First());
        }
Ejemplo n.º 43
0
        internal override string GetExceptionType(SwaggerOperation operation)
        {
            if (operation.Responses.Count(r => r.Key != "200") == 0)
                return "string";

            return string.Join(" | ", operation.Responses
                .Where(r => r.Key != "200")
                .Select(r => GetType(r.Value.Schema.ActualSchema, "Exception"))) + " | string";
        }
Ejemplo n.º 44
0
 internal abstract string GetExceptionType(SwaggerOperation operation);
Ejemplo n.º 45
0
        private bool TryAddFileParameter(JsonObjectTypeDescription info, SwaggerOperation operation, ParameterInfo parameter, SwaggerGenerator swaggerGenerator)
        {
            var isFileArray = IsFileArray(parameter.ParameterType, info);
            if (info.Type == JsonObjectType.File || isFileArray)
            {
                AddFileParameter(parameter, isFileArray, operation, swaggerGenerator);
                return true;
            }

            return false;
        }
Ejemplo n.º 46
0
 internal abstract string GetResultType(SwaggerOperation operation);
Ejemplo n.º 47
0
 private void AddBodyParameter(string name, ParameterInfo parameter, SwaggerOperation operation, SwaggerGenerator swaggerGenerator)
 {
     var operationParameter = swaggerGenerator.CreateBodyParameter(name, parameter);
     operation.Parameters.Add(operationParameter);
 }
 private string GetClientName(SwaggerOperation operation)
 {
     var segments = operation.OperationId.Split('_').Reverse().ToArray();
     return segments.Length >= 2 ? segments[1] : string.Empty;
 }
Ejemplo n.º 49
0
 private void AddPrimitiveParameter(string name, SwaggerOperation operation, ParameterInfo parameter, SwaggerGenerator swaggerGenerator)
 {
     var operationParameter = swaggerGenerator.CreatePrimitiveParameter(name, parameter);
     operationParameter.Kind = SwaggerParameterKind.Query;
     operationParameter.IsRequired = operationParameter.IsRequired || parameter.HasDefaultValue == false;
     operation.Parameters.Add(operationParameter);
 }
Ejemplo n.º 50
0
 /// <summary>Creates the response model.</summary>
 /// <param name="operation">The operation.</param>
 /// <param name="statusCode">The status code.</param>
 /// <param name="response">The response.</param>
 /// <param name="exceptionSchema">The exception schema.</param>
 /// <param name="generator">The generator.</param>
 /// <param name="resolver">The resolver.</param>
 /// <param name="settings">The settings.</param>
 /// <returns></returns>
 protected override CSharpResponseModel CreateResponseModel(SwaggerOperation operation, string statusCode, SwaggerResponse response, JsonSchema4 exceptionSchema, IClientGenerator generator, TypeResolverBase resolver, ClientGeneratorBaseSettings settings)
 {
     return(new CSharpResponseModel(this, operation, statusCode, response, response == GetSuccessResponse().Value, exceptionSchema, generator, resolver, settings.CodeGeneratorSettings));
 }
Ejemplo n.º 51
0
        internal SwaggerResponse GetSuccessResponse(SwaggerOperation operation)
        {
            if (operation.Responses.Any(r => r.Key == "200"))
                return operation.Responses.Single(r => r.Key == "200").Value;

            var response = operation.Responses.FirstOrDefault(r => HttpUtilities.IsSuccessStatusCode(r.Key)).Value;
            if (response != null)
                return response;

            return operation.Responses.FirstOrDefault(r => r.Key == "default").Value;
        }
Ejemplo n.º 52
0
        private string GetClientName(SwaggerOperation operation)
        {
            var segments = operation.OperationId.Split('_').Reverse().ToArray();

            return(segments.Length >= 2 ? segments[1] : string.Empty);
        }
Ejemplo n.º 53
0
 internal abstract string GetResultType(SwaggerOperation operation);
Ejemplo n.º 54
0
        private ApplicationAPIModel GenerateBasicModel(SwaggerOperation Operation, SwaggerOperationMethod method, ref bool supportBody, string path)
        {
            ApplicationAPIModel AAM = new ApplicationAPIModel();

            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("{[a-zA-Z]*}");
            foreach (var Match in reg.Matches(path))
            {
                string modal = "<" + Match.ToString().ToUpper() + ">";
                path = path.Replace(Match.ToString(), modal);
                AAM.AppModelParameters.Add(new AppModelParameter(modal, Match.ToString() + "in url", "", "", new ObservableList <OptionalValue>()));
            }
            AAM.EndpointURL = Swaggerdoc.BaseUrl + path;
            AAM.APIType     = ApplicationAPIUtils.eWebApiType.REST;
            AAM.Name        = Operation.Summary;
            if (string.IsNullOrWhiteSpace(AAM.Name))
            {
                AAM.Name = Operation.OperationId;
            }
            AAM.URLDomain = Swaggerdoc.BaseUrl;
            supportBody   = true;
            switch (method)
            {
            case SwaggerOperationMethod.Get:
                AAM.RequestType = ApplicationAPIUtils.eRequestType.GET;
                supportBody     = false;
                break;

            case SwaggerOperationMethod.Delete:
                AAM.RequestType = ApplicationAPIUtils.eRequestType.DELETE;
                break;

            case SwaggerOperationMethod.Head:
                AAM.RequestType = ApplicationAPIUtils.eRequestType.Head;
                break;

            case SwaggerOperationMethod.Options:
                AAM.RequestType = ApplicationAPIUtils.eRequestType.Options;
                break;

            case SwaggerOperationMethod.Patch:
                AAM.RequestType = ApplicationAPIUtils.eRequestType.PATCH;
                break;

            case SwaggerOperationMethod.Post:
                AAM.RequestType = ApplicationAPIUtils.eRequestType.POST;
                break;

            case SwaggerOperationMethod.Put:
                AAM.RequestType = ApplicationAPIUtils.eRequestType.PUT;
                break;

            case SwaggerOperationMethod.Trace:
                AAM.RequestType = ApplicationAPIUtils.eRequestType.POST;
                break;

            case SwaggerOperationMethod.Undefined:
                AAM.RequestType = ApplicationAPIUtils.eRequestType.POST;
                break;
            }


            foreach (SwaggerParameter param in Operation.Parameters)
            {
                if (param.Kind == SwaggerParameterKind.Header)
                {
                    string           modelName = "<" + param.Name + ">";
                    APIModelKeyValue header    = new APIModelKeyValue();
                    header.ItemName = param.Name;
                    header.Param    = param.Name;
                    header.Value    = modelName;
                    AAM.AppModelParameters.Add(new AppModelParameter(modelName, param.Name + " in headers", "", "", new ObservableList <OptionalValue>()));
                    AAM.HttpHeaders.Add(header);
                }
            }

            return(AAM);
        }
 /// <summary>Gets the client name for a given operation.</summary>
 /// <param name="document">The Swagger document.</param>
 /// <param name="path">The HTTP path.</param>
 /// <param name="httpMethod">The HTTP method.</param>
 /// <param name="operation">The operation.</param>
 /// <returns>The client name.</returns>
 public string GetClientName(SwaggerDocument document, string path, SwaggerOperationMethod httpMethod, SwaggerOperation operation)
 {
     var pathSegments = path.Split('/').Where(p => !p.Contains("{")).Reverse().ToArray();
     return pathSegments.Length >= 2 ? pathSegments[1] : string.Empty;
 }
Ejemplo n.º 56
0
        public override ObservableList <ApplicationAPIModel> ParseDocument(string FileName, ObservableList <ApplicationAPIModel> SwaggerModels, bool avoidDuplicatesNodes = false)
        {
            string FinalFileName = "";
            Uri    url           = new Uri(FileName);

            string orignaljson = "";

            if (url.IsFile)
            {
                orignaljson = System.IO.File.ReadAllText(FileName);
            }
            {
                orignaljson = GeneralLib.HttpUtilities.Download(url);
            }
            try
            {
                JToken.Parse(orignaljson);
                FinalFileName = FileName;
            }
            catch
            {
                var          r            = new StringReader(orignaljson);
                var          deserializer = new Deserializer();
                var          yamlObject   = deserializer.Deserialize(r);
                StringWriter tw           = new StringWriter();
                var          serializer   = new Newtonsoft.Json.JsonSerializer();
                serializer.Serialize(tw, yamlObject);
                orignaljson = tw.ToString();
                string tempfile = System.IO.Path.GetTempFileName();

                System.IO.File.WriteAllText(tempfile, orignaljson);
                FinalFileName = tempfile;
            }


            Swaggerdoc = SwaggerDocument.FromJsonAsync(orignaljson).Result;
            foreach (var paths in Swaggerdoc.Paths)
            {
                SwaggerPathItem SPi = paths.Value;
                foreach (KeyValuePair <SwaggerOperationMethod, SwaggerOperation> so in SPi.AsEnumerable())
                {
                    SwaggerOperation Operation = so.Value;


                    bool supportBody = true;
                    if (Operation.RequestBody == null && Operation.ActualConsumes.Count() == 0)
                    {
                        ApplicationAPIModel basicModal = GenerateBasicModel(Operation, so.Key, ref supportBody, paths.Key);
                        SwaggerModels.Add(basicModal);
                        GenerateResponse(Operation, basicModal);
                    }


                    else if (Operation.ActualConsumes.Count() == 0 && Operation.RequestBody.Content.Count() != 0)
                    {
                        foreach (var body in Operation.RequestBody.Content)
                        {
                            ApplicationAPIModel AAM = GenerateBasicModel(Operation, so.Key, ref supportBody, paths.Key);



                            if (supportBody)
                            {
                                switch (body.Key)
                                {
                                case "application/x-www-form-urlencoded":
                                    GenerateFormParameters(AAM, Operation);
                                    break;

                                case "multipart/form-data":
                                    GenerateFormParameters(AAM, Operation, true);
                                    break;

                                case "application/json":
                                    AAM.ContentType         = ApplicationAPIUtils.eContentType.JSon;
                                    AAM.ResponseContentType = ApplicationAPIUtils.eContentType.JSon;
                                    if (Operation.RequestBody != null)
                                    {
                                        AAM.AppModelParameters.Append(GenerateJsonBody(AAM, Operation.RequestBody.Content.ElementAt(0).Value.Schema));
                                    }
                                    if (Operation.ActualConsumes.Count() > 1)
                                    {
                                        AAM.Name += "-JSON"; AAM.Description = "Body Type is JSON";
                                    }

                                    break;

                                case "application/xml":
                                    AAM.ContentType         = ApplicationAPIUtils.eContentType.XML;
                                    AAM.ResponseContentType = ApplicationAPIUtils.eContentType.XML;
                                    if (Operation.RequestBody != null)
                                    {
                                        AAM.AppModelParameters.Append(GenerateXMLBody(AAM, Operation.RequestBody.Content.ElementAt(0).Value.Schema));
                                    }
                                    if (Operation.ActualConsumes.Count() > 1)
                                    {
                                        AAM.Name       += "-XML";
                                        AAM.Description = "Body Type is XML";
                                    }

                                    break;
                                }
                            }
                            GenerateResponse(Operation, AAM);
                            SwaggerModels.Add(AAM);
                        }
                    }

                    foreach (var body in    Operation.ActualConsumes)
                    {
                        ApplicationAPIModel AAM = GenerateBasicModel(Operation, so.Key, ref supportBody, paths.Key);



                        if (supportBody)
                        {
                            switch (body)
                            {
                            case "application/x-www-form-urlencoded":
                                GenerateFormParameters(AAM, Operation);
                                break;

                            case "multipart/form-data":
                                GenerateFormParameters(AAM, Operation, true);
                                break;

                            case "application/json":
                                AAM.ContentType         = ApplicationAPIUtils.eContentType.JSon;
                                AAM.ResponseContentType = ApplicationAPIUtils.eContentType.JSon;
                                if (Operation.RequestBody != null)
                                {
                                    AAM.AppModelParameters.Append(GenerateJsonBody(AAM, Operation.RequestBody.Content.ElementAt(0).Value.Schema));
                                }
                                if (Operation.ActualConsumes.Count() > 1)
                                {
                                    AAM.Name       += "-JSON";
                                    AAM.Description = "Body Type is JSON";
                                }

                                break;

                            case "application/xml":
                                AAM.ContentType         = ApplicationAPIUtils.eContentType.XML;
                                AAM.ResponseContentType = ApplicationAPIUtils.eContentType.XML;
                                if (Operation.RequestBody != null)
                                {
                                    AAM.AppModelParameters.Append(GenerateXMLBody(AAM, Operation.RequestBody.Content.ElementAt(0).Value.Schema));
                                }
                                if (Operation.ActualConsumes.Count() > 1)
                                {
                                    AAM.Name       += "-XML";
                                    AAM.Description = "Body Type is XML";
                                }
                                break;
                            }
                        }
                        GenerateResponse(Operation, AAM);

                        SwaggerModels.Add(AAM);
                    }
                }
            }
            return(SwaggerModels);
        }
Ejemplo n.º 57
0
        internal bool HasResultType(SwaggerOperation operation)
        {
            var response = GetSuccessResponse(operation);

            return(response?.Schema != null);
        }
Ejemplo n.º 58
0
        private string GetOperationName(SwaggerOperation operation)
        {
            var segments = operation.OperationId.Split('_').Reverse().ToArray();

            return(segments.FirstOrDefault() ?? "Index");
        }
 private string GetOperationName(SwaggerOperation operation)
 {
     var segments = operation.OperationId.Split('_').Reverse().ToArray();
     return segments.First();
 }
        internal override string GetResultType(SwaggerOperation operation)
        {
            var response = GetSuccessResponse(operation);
            if (response == null || response.Schema == null)
                return "void";

            return GetType(response.Schema, "Response");
        }