public byte[] BuildSwaggerJson()
        {
            try
            {
                if (options.XmlDocumentPath != null && !File.Exists(options.XmlDocumentPath))
                {
                    xDocLookup = null;
                }
                else
                {
                    xDocLookup = (options.XmlDocumentPath != null)
                        ? BuildXmlMemberCommentStructure(options.XmlDocumentPath)
                        : null;
                }

                var doc = new SwaggerDocument();
                doc.info        = options.Info;
                doc.host        = (options.CustomHost != null) ? options.CustomHost(httpContext) : httpContext.Request.Headers["Host"][0];
                doc.basePath    = options.ApiBasePath;
                doc.schemes     = (options.ForceSchemas.Length == 0) ? new[] { httpContext.Request.IsHttps ? "https" : httpContext.Request.Scheme } : options.ForceSchemas;
                doc.paths       = new Dictionary <string, PathItem>();
                doc.definitions = new Dictionary <string, Schema>();

                // tags.
                var xmlServiceName = (xDocLookup != null)
                    ? BuildXmlTypeSummary(options.XmlDocumentPath)
                    : null;

                doc.tags = handlers
                           // MemberInfo.DeclaringType is null only if it is a member of a VB Module.
                           .Select(x => x.DeclaringType !.Name)
                           .Distinct()
                           .Select(x =>
                {
                    string desc = null;
                    if (xmlServiceName != null)
                    {
                        xmlServiceName.TryGetValue(x, out desc);
                    }
                    return(new Tag()
                    {
                        name = x,
                        description = desc
                    });
                })
                           .ToArray();

                foreach (var item in handlers)
                {
                    // MemberInfo.DeclaringType is null only if it is a member of a VB Module.
                    string declaringTypeName       = item.DeclaringType !.Name;
                    XmlCommentStructure xmlComment = null;
                    if (xDocLookup != null)
                    {
                        // ParameterInfo.Name will be null only it is ReturnParameter.
                        xmlComment = xDocLookup[Tuple.Create(declaringTypeName, item.Name !)].FirstOrDefault();
Exemplo n.º 2
0
 private static OpenApiOperation BuildOperation(MethodDescriptor descriptor, XmlCommentStructure xmlComment,
                                                IDictionary <string, OpenApiSchema> schemas, string httpPath, OperationType operationType)
 {
     return(new OpenApiOperation
     {
         Tags = new[] { new OpenApiTag {
                            Name = descriptor.Service.Name
                        } },
         Summary = xmlComment?.Summary ?? string.Empty,
         Description = xmlComment?.Remarks ?? string.Empty,
         Parameters = BuildParametersList(descriptor, httpPath, operationType),
         RequestBody = BuildRequestBody(schemas, descriptor, operationType),
         Responses = new OpenApiResponses
         {
             ["200"] = BuildResponse(schemas, descriptor.OutputType, xmlComment)
         },
     });
 }
        public byte[] BuildSwagger(NetStitchServer server)
        {
            try
            {
                if (options.XmlDocumentPath != null && !File.Exists(options.XmlDocumentPath))
                {
                    return(Encoding.UTF8.GetBytes("Xml doesn't exists at " + options.XmlDocumentPath));
                }

                xDocLookup = (options.XmlDocumentPath != null)
                    ? BuildXmlMemberCommentStructure(options.XmlDocumentPath)
                    : null;

                var doc = new SwaggerDocument();
                doc.info        = options.Info;
                doc.host        = (options.CustomHost != null) ? options.CustomHost(httpContext) : httpContext.Request.Headers["Host"][0];
                doc.basePath    = options.ApiBasePath;
                doc.schemes     = (options.ForceSchemas.Length == 0) ? new[] { httpContext.Request.IsHttps ? "https" : httpContext.Request.Scheme } : options.ForceSchemas;
                doc.paths       = new Dictionary <string, PathItem>();
                doc.definitions = new Dictionary <string, Schema>();

                // tags.
                var xmlServiceName = (options.XmlDocumentPath != null)
                    ? BuildXmlTypeSummary(options.XmlDocumentPath)
                    : null;

                doc.tags = server.OperationMap.Values
                           .Select(x => x.OperationID)
                           .Distinct()
                           .Select(x =>
                {
                    string desc = null;
                    if (xmlServiceName != null)
                    {
                        xmlServiceName.TryGetValue(x, out desc);
                    }
                    return(new Tag()
                    {
                        name = x,
                        description = desc
                    });
                })
                           .ToArray();

                foreach (var item in server.OperationMap.Values)
                {
                    XmlCommentStructure xmlComment = null;
                    if (xDocLookup != null)
                    {
                        xmlComment = xDocLookup[Tuple.Create(item.OperationID, item.MethodInfo.Name)].FirstOrDefault();
                    }

                    var parameters = BuildParameters(doc.definitions, xmlComment, item.MethodInfo);
                    var operation  = new Operation
                    {
                        tags        = new[] { item.InterfaceType.Name },
                        summary     = (xmlComment != null) ? xmlComment.Summary : "",
                        description = (xmlComment != null) ? xmlComment.Remarks : "",
                        parameters  = parameters
                    };

                    doc.paths.Add("/" + item.ToString(), new PathItem {
                        post = operation
                    });
                }

                using (var ms = new MemoryStream())
                    using (var sw = new StreamWriter(ms, new UTF8Encoding(false)))
                    {
                        var serializer = new JsonSerializer()
                        {
                            NullValueHandling = NullValueHandling.Ignore,
                            ContractResolver  = IgnoreEmptyEnumerablesResolver.Instance
                        };
                        serializer.Serialize(sw, doc);

                        //todo gzip encording

                        sw.Flush();
                        return(ms.ToArray());
                    }
            }
            catch (Exception ex)
            {
                return(Encoding.UTF8.GetBytes(ex.ToString()));
            }
        }
        Parameter[] BuildParameters(IDictionary <string, Schema> definitions, XmlCommentStructure xmlComment, MethodInfo method)
        {
            var parameterInfos = method.GetParameters();
            var parameters     = parameterInfos
                                 .Select(x =>
            {
                var parameterXmlComment = UnwrapTypeName(x.ParameterType);
                if (xmlComment != null)
                {
                    xmlComment.Parameters.TryGetValue(x.Name, out parameterXmlComment);
                    parameterXmlComment = UnwrapTypeName(x.ParameterType) + " " + parameterXmlComment;
                }

                var defaultValue = x.DefaultValue;
                if (defaultValue != null && x.ParameterType.GetTypeInfo().IsEnum)
                {
                    defaultValue = defaultValue.ToString();
                }

                var collectionType = GetCollectionType(x.ParameterType);
                var items          = collectionType != null
                        ? new PartialSchema {
                    type = ToSwaggerDataType(collectionType),
                }
                        : null;

                string defaultObjectExample = null;
                object[] enums = null;
                if (x.ParameterType.GetTypeInfo().IsEnum || (collectionType != null && collectionType.GetTypeInfo().IsEnum))
                {
                    var enumType = (x.ParameterType.GetTypeInfo().IsEnum) ? x.ParameterType : collectionType;

                    var enumValues = Enum.GetNames(enumType);

                    if (collectionType != null)
                    {
                        defaultObjectExample = string.Join("\r\n", Enum.GetNames(collectionType));
                    }
                    else
                    {
                        enums = enumValues;
                    }
                }

                var swaggerDataType = ToSwaggerDataType(x.ParameterType);
                Schema refSchema    = null;
                if (swaggerDataType == "object")
                {
                    BuildSchema(definitions, x.ParameterType);
                    refSchema = new Schema {
                        @ref = BuildSchema(definitions, x.ParameterType)
                    };
                    if (parameterInfos.Length != 1)
                    {
                        var unknownObj       = Activator.CreateInstance(x.ParameterType);
                        defaultObjectExample = JsonConvert.SerializeObject(unknownObj, new[] { new Newtonsoft.Json.Converters.StringEnumConverter() });
                    }
                }

                return(new Parameter
                {
                    name = x.Name,
                    @in = parameterInfos.Length == 1 ? "body" : "formData",
                    type = swaggerDataType,
                    description = parameterXmlComment,
                    required = !x.IsOptional,
                    @default = defaultObjectExample ?? ((x.IsOptional) ? defaultValue : null),
                    items = items,
                    @enum = enums,
                    collectionFormat = "multi",
                    schema = refSchema
                });
            })
                                 .ToArray();

            return(parameters);
        }
Exemplo n.º 5
0
        Schemas.Parameter[] BuildParameters(IDictionary <string, Schema> definitions, XmlCommentStructure xmlComment, MethodInfo method)
        {
            var parameterInfos = method.GetParameters();
            var parameters     = parameterInfos
                                 .Select(x =>
            {
                var parameterXmlComment = UnwrapTypeName(x.ParameterType);
                if (xmlComment != null)
                {
                    xmlComment.Parameters.TryGetValue(x.Name, out parameterXmlComment);
                    parameterXmlComment = UnwrapTypeName(x.ParameterType) + " " + parameterXmlComment;
                }

                var defaultValue = x.DefaultValue;
                if (defaultValue != null && x.ParameterType.GetTypeInfo().IsEnum)
                {
                    defaultValue = defaultValue.ToString();
                }

                var collectionType = GetCollectionType(x.ParameterType);
                var items          = collectionType != null
                        ? new PartialSchema {
                    type = ToSwaggerDataType(collectionType)
                }
                        : null;

                string defaultObjectExample = null;
                object[] enums = null;
                if (x.ParameterType.GetTypeInfo().IsEnum || (collectionType != null && collectionType.GetTypeInfo().IsEnum))
                {
                    var enumType = (x.ParameterType.GetTypeInfo().IsEnum) ? x.ParameterType : collectionType;

                    var enumValues = Enum.GetNames(enumType);

                    if (collectionType != null)
                    {
                        // Current Swagger-UI's enum array selector is too buggy...
                        //items.@enum = enumValues;
                        defaultObjectExample = string.Join("\r\n", Enum.GetNames(collectionType));
                    }
                    else
                    {
                        enums = enumValues;
                    }
                }

                var swaggerDataType = ToSwaggerDataType(x.ParameterType);
                Schema refSchema    = null;
                if (swaggerDataType == "object")
                {
                    BuildSchema(definitions, x.ParameterType);
                    refSchema = new Schema {
                        @ref = BuildSchema(definitions, x.ParameterType)
                    };
                    var unknownObj       = System.Runtime.Serialization.FormatterServices.GetUninitializedObject(x.ParameterType);
                    defaultObjectExample = JsonConvert.SerializeObject(unknownObj, new[] { new Newtonsoft.Json.Converters.StringEnumConverter() });
                    swaggerDataType      = "string"; // object can not attach formData.
                }

                return(new Schemas.Parameter
                {
                    name = x.Name,
                    @in = "formData",
                    type = swaggerDataType,
                    description = parameterXmlComment,
                    required = !x.IsOptional,
                    @default = defaultObjectExample ?? ((x.IsOptional) ? defaultValue : null),
                    items = items,
                    @enum = enums,
                    collectionFormat = "multi",     // csv or multi
                    schema = refSchema
                });
            })
                                 .ToArray();

            return(parameters);
        }
Exemplo n.º 6
0
 private static OpenApiResponse BuildResponse(IDictionary <string, OpenApiSchema> schemas,
                                              MessageDescriptor itemOutputType, XmlCommentStructure xmlComment)
 {
     return(new OpenApiResponse
     {
         Content = new Dictionary <string, OpenApiMediaType>
         {
             ["object"] = new OpenApiMediaType
             {
                 Schema = new OpenApiSchema
                 {
                     Reference = BuildReference(schemas, itemOutputType.ClrType)
                 }
             }
         },
         Description = xmlComment?.Returns ?? ToCamelCase(itemOutputType.Name)
     });
 }
Exemplo n.º 7
0
        static byte[] BuildSwaggerJson(SwaggerOptions options, IDictionary <string, object> environment, RegisteredHandlersInfo handlersInfo)
        {
            try
            {
                if (options.XmlDocumentPath != null && !File.Exists(options.XmlDocumentPath))
                {
                    return(Encoding.UTF8.GetBytes("Xml doesn't exists at " + options.XmlDocumentPath));
                }

                var xDocLookup = (options.XmlDocumentPath != null)
                    ? BuildXmlCommentStructure(options.XmlDocumentPath)
                    : null;

                var doc = new SwaggerDocument();
                doc.swagger  = "2.0";
                doc.info     = options.Info;
                doc.host     = (options.CustomHost != null) ? options.CustomHost(environment) : environment.AsRequestHeaders()["Host"][0];
                doc.basePath = options.ApiBasePath;
                doc.schemes  = new[] { environment.AsRequestScheme() };
                doc.paths    = new Dictionary <string, PathItem>();

                foreach (var item in handlersInfo.RegisteredHandlers)
                {
                    XmlCommentStructure xmlComment = null;
                    if (xDocLookup != null)
                    {
                        xmlComment = xDocLookup[Tuple.Create(item.Value.ClassName, item.Value.MethodName)].FirstOrDefault();
                    }

                    var parameters = item.Value.Parameters
                                     .Select(x =>
                    {
                        var parameterXmlComment = x.ParameterType.Name;
                        if (xmlComment != null)
                        {
                            xmlComment.Parameters.TryGetValue(x.Name, out parameterXmlComment);
                            parameterXmlComment = x.ParameterType.Name + " " + parameterXmlComment;
                        }

                        var defaultValue = x.DefaultValue;
                        if (defaultValue != null && x.ParameterType.IsEnum)
                        {
                            defaultValue = (options.IsEmitEnumAsString)
                                    ? defaultValue.ToString()
                                    : Convert.ChangeType(defaultValue, Enum.GetUnderlyingType(defaultValue.GetType()));
                        }

                        var items = (x.ParameterTypeIsArray)
                                ? new Items {
                            type = TypeToType(x.ParameterType.GetElementType())
                        }
                                : null;

                        object[] enums = null;
                        if (x.ParameterType.IsEnum || (x.ParameterType.IsArray && x.ParameterType.GetElementType().IsEnum))
                        {
                            var enumType = (x.ParameterType.IsEnum) ? x.ParameterType : x.ParameterType.GetElementType();

                            var enumValues = Enum.GetValues(enumType).Cast <object>()
                                             .Select(v =>
                            {
                                return((options.IsEmitEnumAsString)
                                            ? v.ToString()
                                            : Convert.ChangeType(v, Enum.GetUnderlyingType(enumType)));
                            })
                                             .ToArray();

                            if (x.ParameterType.IsArray)
                            {
                                items.@enum = enumValues;
                            }
                            else
                            {
                                enums = enumValues;
                            }
                        }

                        return(new Parameter
                        {
                            name = x.Name,
                            @in = item.Value.AcceptVerbs.HasFlag(AcceptVerbs.Get) ? "query" : "formData",
                            type = TypeToType(x.ParameterType),
                            description = parameterXmlComment,
                            required = !x.IsOptional,
                            @default = (x.IsOptional) ? defaultValue : null,
                            items = items,
                            @enum = enums,
                            collectionFormat = "multi"
                        });
                    })
                                     .ToArray();

                    var operation = new Operation
                    {
                        tags        = new[] { item.Value.ClassName },
                        summary     = (xmlComment != null) ? xmlComment.Summary : "",
                        description = (xmlComment != null) ? xmlComment.Remarks : "",
                        parameters  = parameters
                    };

                    doc.paths.Add(item.Key, CreatePathItem(item.Value.AcceptVerbs, operation));
                }

                using (var ms = new MemoryStream())
                {
                    var serializer = new DataContractJsonSerializer(typeof(SwaggerDocument), new DataContractJsonSerializerSettings
                    {
                        SerializeReadOnlyTypes    = true,
                        UseSimpleDictionaryFormat = true
                    });
                    serializer.WriteObject(ms, doc);
                    return(ms.ToArray());
                }
            }
            catch (Exception ex)
            {
                return(Encoding.UTF8.GetBytes(ex.ToString()));
            }
        }
Exemplo n.º 8
0
        public byte[] BuildSwaggerJson()
        {
            try
            {
                var xmlList = new List <XmlCommentStructure>();
                foreach (var srvXml in handlers.SrvGroup)
                {
                    var xmlDocumentPath = srvXml.Value;
                    xmlDocumentPath = xmlDocumentPath.Substring(0, xmlDocumentPath.Length - 4) + ".xml";
                    if (File.Exists(xmlDocumentPath))
                    {
                        var lookUp = BuildXmlMemberCommentStructureList(xmlDocumentPath);
                        xmlList = xmlList.Concat(lookUp).ToList();
                    }
                }
                var methodList = handlers.MethodList();
                xDocLookup = xmlList.ToLookup(x => Tuple.Create(x.ClassName, x.MethodName));

                var doc = new SwaggerDocument();
                doc.info        = options.Info;
                doc.host        = (options.CustomHost != null) ? options.CustomHost(httpContext) : httpContext.Request.Headers["Host"][0];
                doc.basePath    = options.ApiBasePath;
                doc.schemes     = (options.ForceSchemas.Length == 0) ? new[] { httpContext.Request.IsHttps ? "https" : httpContext.Request.Scheme } : options.ForceSchemas;
                doc.paths       = new Dictionary <string, PathItem>();
                doc.definitions = new Dictionary <string, Schema>();

                // tags.
                var xmlServiceName = (options.XmlDocumentPath != null)
                    ? BuildXmlTypeSummary(options.XmlDocumentPath)
                    : null;

                doc.tags = methodList.Select(t => t.Service.FullName).Distinct()
                           .Select(x =>
                {
                    string desc = null;
                    if (xmlServiceName != null)
                    {
                        xmlServiceName.TryGetValue(x, out desc);
                    }
                    return(new Tag()
                    {
                        name = x,
                        description = desc
                    });
                })
                           .ToArray();

                foreach (var item in handlers.MethodList())
                {
                    XmlCommentStructure xmlComment = null;
                    if (xDocLookup != null)
                    {
                        xmlComment = xDocLookup[Tuple.Create(item.Service.Name, item.Name)].FirstOrDefault();
                    }

                    var parameters = BuildParameters(doc.definitions, xmlComment, item);
                    var operation  = new Operation
                    {
                        tags        = new[] { item.Service.FullName },
                        summary     = (xmlComment != null) ? xmlComment.Summary : "",
                        description = (xmlComment != null) ? xmlComment.Remarks : "",
                        parameters  = parameters
                    };

                    doc.paths.Add("/" + item.Service.FullName + "/" + item.Name, new PathItem {
                        post = operation
                    });                                                                                              // everything post.
                }

                using (var ms = new MemoryStream())
                    using (var sw = new StreamWriter(ms, new UTF8Encoding(false)))
                    {
                        var serializer = new JsonSerializer()
                        {
                            NullValueHandling = NullValueHandling.Ignore,
                            ContractResolver  = IgnoreEmptyEnumerablesResolver.Instance // omit empty collection.
                        };
                        serializer.Serialize(sw, doc);

                        sw.Flush();
                        return(ms.ToArray());
                    }
            }
            catch (Exception ex)
            {
                return(Encoding.UTF8.GetBytes(ex.ToString()));
            }
        }
Exemplo n.º 9
0
        private Parameter[] BuildParameters(IDictionary <string, Schema> definitions, XmlCommentStructure xmlComment, MethodDescriptor method)
        {
            var input = method.InputType;
            var parameterXmlComment = UnwrapTypeName(input.ClrType);

            if (xmlComment != null)
            {
                xmlComment.Parameters.TryGetValue(input.Name, out parameterXmlComment);
                parameterXmlComment = UnwrapTypeName(input.ClrType) + " " + parameterXmlComment;
            }

            var collectionType = GetCollectionType(input.ClrType);
            var items          = collectionType != null
                ? new PartialSchema {
                type = ToSwaggerDataType(collectionType),
            }
                : null;

            var    swaggerDataType = ToSwaggerDataType(input.ClrType);
            Schema refSchema       = null;

            if (swaggerDataType == "object")
            {
                BuildSchema(definitions, input.ClrType);
                refSchema = new Schema {
                    @ref = BuildSchema(definitions, input.ClrType)
                };
            }

            var param = new Parameter
            {
                name             = input.Name,
                @in              = "body",
                type             = swaggerDataType,
                description      = parameterXmlComment,
                required         = false,
                @default         = null,
                items            = items,
                @enum            = null,
                collectionFormat = "multi",
                schema           = refSchema
            };

            return(new Parameter[] { param });
        }
Exemplo n.º 10
0
        private Parameter[] BuildParameters(IDictionary <string, Schema> definitions, XmlCommentStructure xmlComment, Type ParameterType)
        {
            var parameterXmlComment = UnwrapTypeName(ParameterType);

            if (xmlComment != null)
            {
                xmlComment.Parameters.TryGetValue(ParameterType.Name, out parameterXmlComment);
                parameterXmlComment = UnwrapTypeName(ParameterType) + " " + parameterXmlComment;
            }
            var    swaggerDataType      = ToSwaggerDataType(ParameterType);
            Schema refSchema            = null;
            string defaultObjectExample = null;

            if (swaggerDataType == "object")
            {
                BuildSchema(definitions, ParameterType);
                refSchema = new Schema {
                    @ref = BuildSchema(definitions, ParameterType)
                };

                var unknownObj = Activator.CreateInstance(ParameterType);
                defaultObjectExample = JsonConvert.SerializeObject(unknownObj, new[] { new Newtonsoft.Json.Converters.StringEnumConverter() });
            }
            return(new Parameter[] { });
            //return new Parameter
            //{
            //    name = ParameterType.Name,
            //    @in = "body",
            //    type = swaggerDataType,
            //    description = parameterXmlComment,
            //    required = !x.IsOptional,
            //    @default = defaultObjectExample,
            //    //items = items,
            //    //@enum = enums,
            //    collectionFormat = "multi",
            //    schema = refSchema
            //};
        }