public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            if (operation.parameters == null) return;

            HandleFromUriArrayParams(operation);
            HandleFromUriObjectParams(operation, schemaRegistry, apiDescription);
        }
        public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
        {
            var attributes = type.GetCustomAttributes(false).OfType<SwaggerSchemaFilterAttribute>();

            foreach (var attribute in attributes)
            {
                var filter = (ISchemaFilter)Activator.CreateInstance(attribute.FilterType);
                filter.Apply(schema, schemaRegistry, type);
            }
        }
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            var attributes = apiDescription.GetControllerAndActionAttributes<SwaggerOperationFilterAttribute>();

            foreach (var attribute in attributes)
            {
                var filter = (IOperationFilter)Activator.CreateInstance(attribute.FilterType);
                filter.Apply(operation, schemaRegistry, apiDescription);
            }
        }
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            var attribute = apiDescription.ActionDescriptor.GetCustomAttributes<SwaggerOperationAttribute>()
                .FirstOrDefault();
            if (attribute == null) return;

            if (attribute.OperationId != null)
                operation.operationId = attribute.OperationId;

            if (attribute.Tags != null)
                operation.tags = attribute.Tags;

            if (attribute.Schemes != null)
                operation.schemes = attribute.Schemes;
        }
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            if (apiDescription.GetControllerAndActionAttributes<SwaggerResponseRemoveDefaultsAttribute>().Any()) 
                operation.responses.Clear();

            var responseAttributes = apiDescription.GetControllerAndActionAttributes<SwaggerResponseAttribute>()
                .OrderBy(attr => attr.StatusCode);

            foreach (var attr in responseAttributes)
            {
                var statusCode = attr.StatusCode.ToString();

                operation.responses[statusCode] = new Response
                {
                    description = attr.Description ?? InferDescriptionFrom(statusCode),
                    schema = (attr.Type != null) ? schemaRegistry.GetOrRegister(attr.Type) : null
                };
            }
        }
        private void HandleFromUriObjectParams(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            var fromUriObjectParams = operation.parameters
                .Where(param => param.@in == "query" && param.type == null)
                .ToArray();

            foreach (var objectParam in fromUriObjectParams)
            {
                var type = apiDescription.ParameterDescriptions
                    .Single(paramDesc => paramDesc.Name == objectParam.name)
                    .ParameterDescriptor.ParameterType;

                var refSchema = schemaRegistry.GetOrRegister(type);
                var schema = schemaRegistry.Definitions[[email protected]("#/definitions/", "")];

                var qualifier = string.IsNullOrEmpty(objectParam.name) ? "" : (objectParam.name + ".");
                ExtractAndAddQueryParams(schema, qualifier, objectParam.required, schemaRegistry, operation.parameters);
                operation.parameters.Remove(objectParam);
            }
        }
        private void ExtractAndAddQueryParams(
            Schema sourceSchema,
            string sourceQualifier,
            bool? sourceRequired,
            SchemaRegistry schemaRegistry,
            IList<Parameter> operationParams)
        {
            foreach (var entry in sourceSchema.properties)
            {
                var propertySchema = entry.Value;
                if (propertySchema.readOnly == true) continue;

                var required = (sourceRequired == true)
                    && sourceSchema.required != null && sourceSchema.required.Contains(entry.Key); 

                if (propertySchema.@ref != null)
                {
                    var schema = schemaRegistry.Definitions[[email protected]("#/definitions/", "")];
                    ExtractAndAddQueryParams(
                        schema,
                        sourceQualifier + entry.Key.ToCamelCase() + ".",
                        required,
                        schemaRegistry,
                        operationParams);
                }
                else
                {
                    var param = new Parameter
                    {
                        name =  sourceQualifier + entry.Key.ToCamelCase(),
                        @in = "query",
                        required = required,
                        description = entry.Value.description
                    };
                    param.PopulateFrom(entry.Value);
                    if (param.type == "array")
                        param.collectionFormat = "multi";
                    operationParams.Add(param);
                }
            }
        }
        static public async Task <AvroKafkaProducer <K, T> > GetProducer <K, T>(KafkaConfiguration configuration, string schemaRegistryEndPoint)
        {
            var schemaRegistry = new SchemaRegistry(schemaRegistryEndPoint);

            var keySchema = Avro.GenerateSchema <K>();
            await schemaRegistry.RegisterSchema(configuration.Topic, keySchema, true);

            var valueSchema = Avro.GenerateSchema <T>();

            if (!await schemaRegistry.IsSchemaCompatible(configuration.Topic, valueSchema))
            {
                throw new ApplicationException("value schema is not compatible");
            }

            var keySchemaId = await schemaRegistry.GetSchemaId(configuration.Topic, true);

            var valueSchemaId = await schemaRegistry.GetSchemaId(configuration.Topic);

            Logger.Info("Creating Kafka Producer for topic: " + configuration.Topic);
            var producer = new RdKafka.Producer(configuration.KafkaBrokers);
            var topic    = producer.Topic(configuration.Topic);

            return(new AvroKafkaProducer <K, T>(producer, topic, keySchemaId, valueSchemaId));
        }
Exemple #9
0
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, System.Web.Http.Description.ApiDescription apiDescription)
        {
            if (operation.parameters == null)
            {
                // no parameter
                return;
            }

            foreach (var param in operation.parameters)
            {
                var summaryAttributes = apiDescription.ParameterDescriptions.First(x => x.Name.Equals(param.name))
                                        .ParameterDescriptor.GetCustomAttributes <CustomSummaryAttribute>();

                if (summaryAttributes != null && summaryAttributes.Count > 0)
                {
                    // add x-ms-summary extension
                    if (param.vendorExtensions == null)
                    {
                        param.vendorExtensions = new Dictionary <string, object>();
                    }
                    param.vendorExtensions.Add("x-ms-summary", summaryAttributes[0].SummaryText);
                }
            }
        }
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            if (operation.parameters == null)
            {
                operation.parameters = new List <Parameter>();
            }

            var headerParam = new List <Parameter>
            {
                new Parameter
                {
                    name        = "Authorization",
                    @in         = "header",
                    type        = "string",
                    description = "Bearer JWT",
                    required    = true
                }
            };


            headerParam.AddRange(operation.parameters);

            operation.parameters = headerParam;
        }
Exemple #11
0
        private static void SetRequestModelExamples(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            var controllerSerializerSettings = apiDescription?.ActionDescriptor?.ControllerDescriptor?.Configuration?.Formatters?.JsonFormatter?.SerializerSettings;

            var requestAttributes = apiDescription.GetControllerAndActionAttributes <SwaggerRequestExampleAttribute>();

            foreach (var attr in requestAttributes)
            {
                var schema = schemaRegistry.GetOrRegister(attr.RequestType);

                var parameter = operation.parameters.FirstOrDefault(p => p.@in == "body" && (p.schema.@ref == schema.@ref || p.schema.items.@ref == schema.@ref));

                if (parameter != null)
                {
                    var serializerSettings = SerializerSettings(controllerSerializerSettings, attr.ContractResolver, attr.JsonConverter);

                    var provider = (IExamplesProvider)Activator.CreateInstance(attr.ExamplesProviderType);

                    // name = attr.RequestType.Name; // this doesn't work for generic types, so need to to schema.ref split

                    var parts = schema.@ref?.Split('/');
                    if (parts == null)
                    {
                        continue;
                    }

                    var name = parts.Last();

                    if (schemaRegistry.Definitions.ContainsKey(name))
                    {
                        var definitionToUpdate = schemaRegistry.Definitions[name];
                        definitionToUpdate.example = FormatJson(provider, serializerSettings, false);
                    }
                }
            }
        }
        public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
        {
            if (schema == null || type == null)
            {
                return;
            }

            applySchemaLookupForDynamicModels(schema, schemaRegistry, type);

            if (schema.properties == null)
            {
                return;
            }

            foreach (var propertyName in schema.properties.Keys)
            {
                var schemaProperty = schema.properties[propertyName];
                var propertyInfo   = type.GetRuntimeProperties().Where(p => p.GetSerializedPropertyName() == propertyName).FirstOrDefault();

                applyValueLookupForDynamicProperties(schemaProperty, propertyInfo);
                applyPropertyMetadata(schemaProperty, propertyInfo);
                applyCallbackUrl(schemaProperty, propertyInfo);
            }
        }
Exemple #13
0
            public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
            {
                // Correspond each "Authorize" role to an oauth2 scope
                var scopes = apiDescription.ActionDescriptor.GetFilterPipeline()
                             .Select(filterInfo => filterInfo.Instance)
                             .OfType <AuthorizeAttribute>()
                             .SelectMany(attr => attr.Roles.Split(','))
                             .Distinct();

                if (scopes.Any())
                {
                    if (operation.security == null)
                    {
                        operation.security = new List <IDictionary <string, IEnumerable <string> > >();
                    }

                    var oAuthRequirements = new Dictionary <string, IEnumerable <string> >
                    {
                        { "oauth2", scopes }
                    };

                    operation.security.Add(oAuthRequirements);
                }
            }
        /// <summary>
        ///
        /// </summary>
        /// <param name="swaggerDoc"></param>
        /// <param name="schemaRegistry"></param>
        /// <param name="apiExplorer"></param>
        public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
        {
            List <string> keys = new List <string>();

            foreach (var item in apiExplorer.ApiDescriptions)
            {
                var apiIgnores = item.GetControllerAndActionAttributes <ApiIgnoreAttribute>().ToList();
                //item.
                if (apiIgnores != null && apiIgnores.Count > 0)
                {
                    string itemID = $"{item.ActionDescriptor.ActionName}{item.RelativePath}".ToLower();
                    foreach (var path in swaggerDoc.paths)
                    {
                        string pathKey = $"{item.ActionDescriptor.ActionName}{path.Key.Remove(0, 1)}".ToLower();

                        if (itemID == pathKey)
                        {
                            keys.Add(path.Key);
                        }
                    }
                }
            }
            keys.ForEach(m => { swaggerDoc.paths.Remove(m); });
        }
Exemple #15
0
        /// <inheritdoc/>
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            var actFilters      = apiDescription.ActionDescriptor.GetFilterPipeline();
            var allowsAnonymous = actFilters.Select(f => f.Instance).OfType <OverrideAuthorizationAttribute>().Any();

            if (allowsAnonymous)
            {
                return; // must be an anonymous method
            }
            if (operation.security == null)
            {
                operation.security = new List <IDictionary <string, IEnumerable <string> > >();
            }

            var oAuthRequirements = new Dictionary <string, IEnumerable <string> >
            {
                //{ "oauth2", new List<string> {"FFAccessAPI"} }
                { "oauth2", new List <string> {
                      "openid"
                  } }
            };

            operation.security.Add(oAuthRequirements);
        }
Exemple #16
0
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            var attribute = apiDescription.ActionDescriptor.GetCustomAttributes <SwaggerOperationAttribute>().FirstOrDefault();

            if (attribute == null)
            {
                return;
            }

            if (attribute.OperationId != null)
            {
                operation.operationId = attribute.OperationId;
            }

            if (attribute.Tags != null)
            {
                operation.tags = attribute.Tags;
            }

            if (attribute.Schemes != null)
            {
                operation.schemes = attribute.Schemes;
            }
        }
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            if (operation.operationId.ToLower() == "municipality_importmunicipalities")
            {
                if (operation.parameters == null)
                {
                    operation.parameters = new List <Parameter>(1);
                }
                else
                {
                    operation.parameters.Clear();
                }

                operation.parameters.Add(new Parameter
                {
                    name        = "File",
                    @in         = "formData",
                    description = "Upload software package",
                    required    = true,
                    type        = "file"
                });
                operation.consumes.Add("application/form-data");
            }
        }
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            operation.parameters = operation.parameters ?? new List <Parameter>();

            var swaggerHeaderParamAttributes = apiDescription.ActionDescriptor.GetCustomAttributes <SwaggerHeaderParamAttribute>().ToList();
            var swaggerPaginationHeaderParametersAttributes = apiDescription.ActionDescriptor.GetCustomAttributes <SwaggerPaginationHeaderParametersAttribute>();

            foreach (SwaggerPaginationHeaderParametersAttribute swaggerPaginationHeaderParametersAttribute in swaggerPaginationHeaderParametersAttributes)
            {
                swaggerHeaderParamAttributes.AddRange(swaggerPaginationHeaderParametersAttribute.RequestHeaderParameters);
            }

            foreach (SwaggerHeaderParamAttribute swaggerHeaderParamAttribute in swaggerHeaderParamAttributes)
            {
                Parameter newParameter = new Parameter
                {
                    name        = swaggerHeaderParamAttribute.Name,
                    description = swaggerHeaderParamAttribute.Description,
                    @in         = "header",
                    required    = swaggerHeaderParamAttribute.Required,
                    type        = swaggerHeaderParamAttribute.Type,
                    @default    = swaggerHeaderParamAttribute.DefaultValue
                };

                if (swaggerHeaderParamAttribute.Type.StartsWith("array["))
                {
                    newParameter.type  = "array";
                    newParameter.items = new PartialSchema()
                    {
                        type = swaggerHeaderParamAttribute.Type.Split(new[] { '[', ']' }, StringSplitOptions.RemoveEmptyEntries)[1]
                    };
                }

                operation.parameters.Add(newParameter);
            }
        }
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            if (operation.parameters == null)
            {
                operation.parameters = new List <Parameter>();
            }

            ////var filterPipeline = apiDescription.ActionDescriptor.GetFilterPipeline(); //判断是否添加权限过滤器
            ////var isAuthorized = filterPipeline.Select(filterInfo => filterInfo.Instance).Any(filter => filter is IAuthorizationFilter); //判断是否允许匿名方法

            //var isNeedLogin = apiDescription.ActionDescriptor.GetCustomAttributes<CustomActionFilterAttribute>().Any(); //是否有验证用户标记
            //if (isNeedLogin)//如果有验证标记则 多输出2个文本框(swagger form提交时会将这2个值放入header里)
            //{
            //    operation.parameters.Add(new Parameter { name = "t8_token", @in = "header", description = "token", required = true, type = "string" });
            //    operation.parameters.Add(new Parameter { name = "t8_tick", @in = "header", description = "tick", required = true, type = "string" });
            //}

            operation.parameters.Add(new Parameter {
                name = "t8_token", @in = "header", description = "token", required = true, type = "string"
            });
            operation.parameters.Add(new Parameter {
                name = "t8_tick", @in = "header", description = "tick", required = true, type = "string"
            });
        }
Exemple #20
0
            public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
            {
                if (operation.parameters == null)
                {
                    operation.parameters = new List <Parameter>();
                }
                var filterPipeline = apiDescription.ActionDescriptor.GetFilterPipeline();
                //判断是否添加权限过滤器
                var isAuthorized = filterPipeline.Select(filterInfo => filterInfo.Instance).Any(filter => filter is IAuthorizationFilter);
                //判断是否允许匿名方法
                var allowAnonymous = apiDescription.ActionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().Any();

                if (isAuthorized && !allowAnonymous)
                {
                    operation.parameters.Add(new Parameter
                    {
                        name        = "token",
                        @in         = "header",
                        description = "token",
                        required    = false,
                        type        = "string"
                    });
                }
            }
        private void ExtractAndAddQueryParams(
            Schema sourceSchema,
            string sourceQualifier,
            bool sourceRequired,
            SchemaRegistry schemaRegistry,
            IList <Parameter> operationParams)
        {
            foreach (var entry in sourceSchema.properties)
            {
                var propertySchema = entry.Value;
                var required       = sourceRequired &&
                                     sourceSchema.required != null && sourceSchema.required.Contains(entry.Key);

                if (propertySchema.@ref != null)
                {
                    var schema = schemaRegistry.Definitions[[email protected]("#/definitions/", "")];
                    ExtractAndAddQueryParams(
                        schema,
                        sourceQualifier + entry.Key.ToLowerInvariant() + ".",
                        required,
                        schemaRegistry,
                        operationParams);
                }
                else
                {
                    var param = new Parameter
                    {
                        name     = sourceQualifier + entry.Key.ToLowerInvariant(),
                        @in      = "query",
                        required = required
                    };
                    param.PopulateFrom(entry.Value);
                    operationParams.Add(param);
                }
            }
        }
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        string[] splitter      = null;
        var      fromUriParams = apiDescription.ActionDescriptor.GetParameters().
                                 Where(param => param.GetCustomAttributes <FromUriAttribute>().Any()).ToArray();

        foreach (var param in fromUriParams)
        {
            var fromUriAttribute = param.GetCustomAttributes <FromUriAttribute>().FirstOrDefault();
            // Check
            if (fromUriAttribute != null)
            {
                var operationParam = operation.parameters;
                foreach (var item in operationParam)
                {
                    if (item.name.Contains(param.ParameterName))
                    {
                        splitter  = item.name.Split('.');
                        item.name = splitter[splitter.Length - 1];
                    }
                }
            }
        }
    }
Exemple #23
0
 public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
 {
     swaggerDoc.paths.Add("/oauth/token", new PathItem
     {
         post = new Operation
         {
             tags = new List <string> {
                 "Auth"
             },
             consumes = new List <string> {
                 "application/x-www-form-urlencoded"
             },
             parameters = new List <Parameter> {
                 new Parameter
                 {
                     type = "string", name = "grant_type", required = true, @in = "formData", @default = "password"
                 },
                 new Parameter
                 {
                     type = "string", name = "username", required = true, @in = "formData"
                 },
                 new Parameter
                 {
                     type = "string", name = "password", required = true, @in = "formData"
                 }
             },
             responses = new Dictionary <string, Response>
             {
                 { "200", new Response()
                   {
                       description = "OK", schema = schemaRegistry.GetOrRegister(typeof(object))
                   } }
             }
         }
     });
 }
        private static void RegisterReferencedTypes(SchemaRegistry registry, IEdmModel edmModel, Schema schema)
        {
            Contract.Requires(registry != null);
            Contract.Requires(schema != null);

            while (true)
            {
                Contract.Assume(schema != null);

                var referencedType = schema.GetReferencedType();

                if (referencedType != null)
                {
                    registry.GetOrRegister(referencedType);
                    FixSchemaReference(registry, schema, referencedType);
                    ApplyEdmModelPropertyNamesToSchema(registry, edmModel, referencedType);
                    return;
                }

                if (schema.properties != null && schema.properties.Any())
                {
                    foreach (var property in schema.properties)
                    {
                        RegisterReferencedTypes(registry, edmModel, property.Value);
                    }
                    return;
                }

                if (schema.items != null)
                {
                    schema = schema.items;
                    continue;
                }
                break;
            }
        }
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            if (operation.parameters == null)
            {
                operation.parameters = new List <Parameter>();
            }

            operation.parameters.Add(new Parameter
            {
                name        = "Authorization",
                @in         = "header",
                description = "Access Token",
                required    = false,
                type        = "string"
            });
            if (operation.operationId == "Location_Get")  // controller and action name
            {
                operation.
                consumes = new List <string>
                {
                    "application/json"
                };
            }
        }
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            if (apiDescription.GetControllerAndActionAttributes <SwaggerResponseRemoveDefaultsAttribute>().Any())
            {
                operation.responses.Clear();
            }

            var responseAttributes = apiDescription.GetControllerAndActionAttributes <SwaggerFileResponseAttribute>()
                                     .OrderBy(attr => attr.StatusCode);

            foreach (var attr in responseAttributes)
            {
                var statusCode = attr.StatusCode.ToString();

                operation.produces = new[] { "application/octet-stream" };
                operation.responses[statusCode] = new Response
                {
                    description = attr.Description ?? InferDescriptionFrom(statusCode),
                    schema      = new Schema {
                        format = "application/octet-stream", type = "file"
                    }
                };
            }
        }
Exemple #27
0
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            var fromBodyAttributes = apiDescription.ActionDescriptor.GetParameters()
                                     .Where(param => param.GetCustomAttributes <FromFormDataBodyAttribute>().Any())
                                     .ToArray();

            if (fromBodyAttributes.Any())
            {
                operation.consumes.Add("application/x-www-form-urlencoded");
            }

            foreach (var headerParam in fromBodyAttributes)
            {
                if (operation.parameters != null)
                {
                    // Select the capitalized parameter names
                    var parameter = operation.parameters.Where(p => p.name == headerParam.ParameterName).FirstOrDefault();
                    if (parameter != null)
                    {
                        parameter.@in = "query";//todo change to "formData" when http://vstfrd:8080/Azure/RD/_workitems/edit/3172874 in autorest is completed
                    }
                }
            }
        }
Exemple #28
0
        public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
        {
            if (type == typeof(GetTemplatesResponse))
            {
                schema.example = new GetTemplatesResponse()
                {
                }
            }
            ;

            if (type == typeof(GetTemplateByResponse))
            {
                schema.example = new GetTemplateByResponse()
                {
                }
            }
            ;

            if (type == typeof(UpdateTemplateRequest))
            {
                schema.example = new UpdateTemplateRequest()
                {
                }
            }
            ;

            if (type == typeof(ChangeStatusRequest))
            {
                schema.example = new ChangeStatusRequest()
                {
                }
            }
            ;
        }
    }
}
 /// <summary>
 /// To remove the NotificationInstallations from default route
 /// </summary>
 /// <param name="swaggerDoc"></param>
 /// <param name="schemaRegistry"></param>
 /// <param name="apiExplorer"></param>
 public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
 {
     if (swaggerDoc != null)
     {
         //NotificationInstallations are not used in Todo mobile app, so the path is removed from swagger document
         //If we need the notifications comment the below lines and enable the UseDefaultConfiguration in SwaggerConfig class
         if (swaggerDoc.paths.ContainsKey("/api/NotificationInstallations"))
         {
             swaggerDoc.paths.Remove("/api/NotificationInstallations");
         }
         if (swaggerDoc.definitions.ContainsKey("NotificationInstallation"))
         {
             swaggerDoc.definitions.Remove("NotificationInstallation");
         }
         if (swaggerDoc.definitions.ContainsKey("NotificationTemplate"))
         {
             swaggerDoc.definitions.Remove("NotificationTemplate");
         }
         if (swaggerDoc.definitions.ContainsKey("NotificationSecondaryTile"))
         {
             swaggerDoc.definitions.Remove("NotificationSecondaryTile");
         }
     }
 }
 public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
 {
     swaggerDoc.tags = new List <Tag>
     {
         new Tag {
             name = "Clients", description = "an ApiController resource"
         },
         new Tag {
             name = "Customers", description = "an ODataController resource"
         },
         new Tag {
             name = "Orders", description = "an ODataController resource"
         },
         new Tag {
             name = "CustomersV1", description = "a versioned ODataController resource"
         },
         new Tag {
             name = "Users", description = "a RESTier resource"
         },
         new Tag {
             name = "Products", description = "demonstrates functions"
         }
     };
 }
        private Parameter CreateParameter(string location, ApiParameterDescription paramDesc, SchemaRegistry schemaRegistry)
        {
            var parameter = new Parameter
            {
                @in  = location,
                name = paramDesc.Name
            };

            if (paramDesc.ParameterDescriptor == null)
            {
                parameter.type     = "string";
                parameter.required = true;
                return(parameter);
            }

            parameter.required = location == "path" || !paramDesc.ParameterDescriptor.IsOptional;
            parameter.@default = paramDesc.ParameterDescriptor.DefaultValue;

            var schema = schemaRegistry.GetOrRegister(paramDesc.ParameterDescriptor.ParameterType);

            if (parameter.@in == "body")
            {
                parameter.schema = schema;
            }
            else
            {
                parameter.PopulateFrom(schema);
            }

            return(parameter);
        }
        private PathItem CreatePathItem(IEnumerable <ApiDescription> apiDescriptions, SchemaRegistry schemaRegistry)
        {
            var pathItem = new PathItem();

            // Group further by http method
            var perMethodGrouping = apiDescriptions
                                    .GroupBy(apiDesc => apiDesc.HttpMethod.Method.ToLower());

            foreach (var group in perMethodGrouping)
            {
                var httpMethod = group.Key;

                var apiDescription = (group.Count() == 1)
                    ? group.First()
                    : _options.ConflictingActionsResolver(group);

                switch (httpMethod)
                {
                case "get":
                    pathItem.get = CreateOperation(apiDescription, schemaRegistry);
                    break;

                case "put":
                    pathItem.put = CreateOperation(apiDescription, schemaRegistry);
                    break;

                case "post":
                    pathItem.post = CreateOperation(apiDescription, schemaRegistry);
                    break;

                case "delete":
                    pathItem.delete = CreateOperation(apiDescription, schemaRegistry);
                    break;

                case "options":
                    pathItem.options = CreateOperation(apiDescription, schemaRegistry);
                    break;

                case "head":
                    pathItem.head = CreateOperation(apiDescription, schemaRegistry);
                    break;

                case "patch":
                    pathItem.patch = CreateOperation(apiDescription, schemaRegistry);
                    break;
                }
            }

            return(pathItem);
        }
        private static Parameter CreateParameter(SwaggerApiParameterDescription paramDesc, bool inPath, SchemaRegistry schemaRegistry, IEdmModel edmModel)
        {
            Contract.Requires(paramDesc != null);
            Contract.Requires(schemaRegistry != null);
            Contract.Assume(paramDesc.ParameterDescriptor != null);

            var @in = inPath
                ? "path"
                : MapToSwaggerParameterLocation(paramDesc.SwaggerSource);

            var parameter = new Parameter
            {
                name        = paramDesc.Name,
                description = paramDesc.Documentation,
                @in         = @in,
                required    = inPath || !paramDesc.ParameterDescriptor.IsOptional,
                @default    = paramDesc.ParameterDescriptor.DefaultValue
            };


            var parameterType = paramDesc.ParameterDescriptor.ParameterType;

            Contract.Assume(parameterType != null);
            var schema = schemaRegistry.GetOrRegisterParameterType(edmModel, paramDesc.ParameterDescriptor);

            if (parameter.@in == "body")
            {
                parameter.schema = schema;
            }
            else
            {
                parameter.PopulateFrom(schema);
            }

            return(parameter);
        }
 public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
 {
     // Include the given data type in the final SwaggerDocument
     //
     //schemaRegistry.GetOrRegister(typeof(ExtraType));
 }
        private PathItem CreatePathItem(IEnumerable <ApiDescription> apiDescriptions, SchemaRegistry schemaRegistry)
        {
            Contract.Requires(apiDescriptions != null);
            Contract.Requires(schemaRegistry != null);

            var pathItem = new PathItem();

            // Group further by http method
            var perMethodGrouping = apiDescriptions
                                    .GroupBy(apiDesc => apiDesc.HttpMethod.Method.ToLower());

            foreach (var group in perMethodGrouping)
            {
                Contract.Assume(group != null);

                var httpMethod = group.Key;

                var apiDescription = group.Count() == 1
                    ? group.First()
                    : _config.GetSwashbuckleOptions().ConflictingActionsResolver(group);

                Contract.Assume(apiDescription != null);
                Contract.Assume(apiDescription.ParameterDescriptions != null);
                switch (httpMethod)
                {
                case "get":
                    pathItem.get = CreateOperation(apiDescription, schemaRegistry);
                    break;

                case "put":
                    pathItem.put = CreateOperation(apiDescription, schemaRegistry);
                    break;

                case "post":
                    pathItem.post = CreateOperation(apiDescription, schemaRegistry);
                    break;

                case "delete":
                    pathItem.delete = CreateOperation(apiDescription, schemaRegistry);
                    break;

                case "patch":
                case "merge":
                    pathItem.patch = CreateOperation(apiDescription, schemaRegistry);
                    break;

                default:
                    throw new InvalidOperationException($"HttpMethod {httpMethod} is not supported.");
                }
            }

            return(pathItem);
        }
Exemple #36
0
        public SwaggerDocument GetSwagger(string rootUrl, string apiVersion)
        {
            var swashbuckleOptions = _config.GetSwashbuckleOptions();

            var schemaRegistry = new SchemaRegistry(
                _config.Configuration.SerializerSettingsOrDefault(),
                swashbuckleOptions.CustomSchemaMappings,
                swashbuckleOptions.SchemaFilters,
                swashbuckleOptions.ModelFilters,
                swashbuckleOptions.IgnoreObsoleteProperties,
                swashbuckleOptions.SchemaIdSelector,
                swashbuckleOptions.DescribeAllEnumsAsStrings,
                swashbuckleOptions.DescribeStringEnumsInCamelCase);

            Info info;

            _config.GetApiVersions().TryGetValue(apiVersion, out info);
            if (info == null)
            {
                throw new UnknownApiVersion(apiVersion);
            }

            var pathsByGroup = GetApiDescriptionsFor(apiVersion)
                               .Where(apiDesc => !(swashbuckleOptions.IgnoreObsoleteActions && apiDesc.IsObsolete()))
                               .OrderBy(swashbuckleOptions.GroupingKeySelector, swashbuckleOptions.GroupingKeyComparer)
                               .GroupBy(apiDesc => apiDesc.RelativePathSansQueryString());
            // .ToDictionary(group => "/" + group.Key, group => CreatePathItem(@group, schemaRegistry));

            var paths = new Dictionary <string, PathItem>();

            foreach (var group in pathsByGroup)
            {
                var apiKey = "/" + group.Key;
                try
                {
                    paths.Add("/" + group.Key, CreatePathItem(@group, schemaRegistry));
                }
                catch (Exception ex)
                {
                    // fail silently and skip adding this path to document
                }
            }
            ;

            var rootUri = new Uri(rootUrl);
            var port    = !rootUri.IsDefaultPort ? ":" + rootUri.Port : string.Empty;

            var odataSwaggerDoc = new SwaggerDocument
            {
                info     = info,
                host     = rootUri.Host + port,
                basePath = rootUri.AbsolutePath != "/" ? rootUri.AbsolutePath : null,
                schemes  = swashbuckleOptions.Schemes?.ToList() ?? new[] { rootUri.Scheme }.ToList(),
                paths               = paths,
                definitions         = schemaRegistry.Definitions,
                securityDefinitions = swashbuckleOptions.SecurityDefinitions
            };

            foreach (var filter in swashbuckleOptions.DocumentFilters)
            {
                Contract.Assume(filter != null);

                filter.Apply(odataSwaggerDoc, schemaRegistry, _config.GetApiExplorer());
            }

            return(MergeODataAndWebApiSwaggerDocs(rootUrl, apiVersion, odataSwaggerDoc));
        }
        private IEnumerable <KeyValuePair <string, PathItem> > BuildPaths(
            string resource, SchemaRegistry registry, IEnumerable <RequestMetadata> requests)
        {
            var stringSchema        = registry.GetOrRegister(typeof(string));
            var unprocessableSchema = registry.GetOrRegister(typeof(ValidationFailureShim));

            return(requests.Select(x =>
            {
                var assembly = x.RequestType.Assembly.GetName();
                var tag = $"{assembly.Name} [{assembly.Version}]";
                var requestSchema = GetMessageSchema(registry, x.RequestType);
                var responseSchema = GetMessageSchema(registry, x.ResponseType);
                var requestPath = ServiceBusRouter.GetRequestPath(x.RequestType);

                var requestSummary = GetReferencedSchema(registry,
                                                         registry.GetOrRegister(x.RequestType))?.description;

                var handlerAssembly = x.HandlerType.Assembly.GetName();
                var handlerNotes = $"Handled by {x.HandlerType.FullName} in {handlerAssembly.Name} [{handlerAssembly.Version}]";

                return new KeyValuePair <string, PathItem>($"/{resource}/{requestPath}", new PathItem
                {
                    post = new Operation
                    {
                        summary = requestSummary,
                        operationId = x.RequestType.FullName,
                        description = handlerNotes,
                        tags = new [] { tag },
                        consumes = JsonFormats,
                        produces = JsonFormats,
                        parameters = new []
                        {
                            new Parameter
                            {
                                @in = "body",
                                name = "message",
                                description = "request to process",
                                schema = requestSchema,
                                required = true
                            }
                        },
                        responses = new Dictionary <string, Response>
                        {
                            {
                                "200", new Response {
                                    description = "OK",
                                    schema = responseSchema
                                }
                            },
                            {
                                "422", new Response {
                                    description = "Unprocessable",
                                    schema = unprocessableSchema
                                }
                            },
                            {
                                "409", new Response {
                                    description = "Concurrency Conflict",
                                    schema = stringSchema
                                }
                            }
                        }
                    }
                });
            }));
        }
		public void TestUninstall(
			[ValueSource("ConnectionStrings")] string connectionString,
			[ValueSource("Schemas")] IEnumerable<string> schema)
		{
			TestWithRollback(connectionString, connection =>
			{
				// try to install the schema and verify that they are there
				Install(connection, schema);
				VerifyObjectsAndRegistry(schema, connection);

				// uninstall it
				SchemaInstaller installer = new SchemaInstaller(connection);
				installer.Uninstall(TestSchemaGroup);

				// make sure the registry is empty
				SchemaRegistry registry = new SchemaRegistry(connection, TestSchemaGroup);
				Assert.IsTrue(!registry.Entries.Any());

				// make sure all of the objects exist in the database
				foreach (var schemaObject in schema.Select(s => new SchemaObject(s)))
					Assert.False(schemaObject.Exists(connection), "Object {0} is not deleted from database", schemaObject.Name);
			});
		}
		/// <summary>
		/// Verify all of the objects in the database and registry.
		/// </summary>
		/// <param name="schema">The schema to verify.</param>
		/// <param name="connection">The connection to use.</param>
		private static void VerifyObjectsAndRegistry(IEnumerable<string> schema, RecordingDbConnection connection)
		{
			connection.DoNotLog(() =>
			{
				// make sure the schema registry was updated
				SchemaRegistry registry = new SchemaRegistry(connection, TestSchemaGroup);

				// make sure all of the objects exist in the database
				foreach (var schemaObject in schema.Select(s => new SchemaObject(s)))
				{
					// azure doesn't support xml index, so lets comment those out
					if (schemaObject.Sql.Contains("XML INDEX") && connection.IsAzure())
						continue;

					Assert.True(schemaObject.Exists(connection), "Object {0} is missing from database", schemaObject.Name);
					Assert.True(registry.Contains(schemaObject), "Object {0} is missing from registry", schemaObject.Name);
				}
			});
		}