public override OpenApiObject GetCustomOpenApiConfig(LinkGenerator linkGenerator)
        {
            var obj = new OpenApiObject();

            if (RemoveDisabled)
            {
                obj["removeDisabled"] = new OpenApiBoolean(true);
            }

            if (AddDisabled)
            {
                obj["addDisabled"] = new OpenApiBoolean(true);
            }

            if (!string.IsNullOrEmpty(AddButtonContent))
            {
                obj["addButtonContent"] = new OpenApiString(AddButtonContent);
            }

            if (!string.IsNullOrEmpty(RemoveButtonContent))
            {
                obj["removeButtonContent"] = new OpenApiString(RemoveButtonContent);
            }

            return(obj);
        }
        /// <summary>
        /// Converts <see cref="OpenApiResponseBodyAttribute"/> to <see cref="OpenApiResponse"/>.
        /// </summary>
        /// <param name="attribute"><see cref="OpenApiResponseBodyAttribute"/> instance.</param>
        /// <returns><see cref="OpenApiResponse"/> instance.</returns>
        public static OpenApiResponse ToOpenApiResponse(this OpenApiResponseBodyAttribute attribute)
        {
            attribute.ThrowIfNullOrDefault();

            var description = string.IsNullOrWhiteSpace(attribute.Description)
                                  ? $"Payload of {attribute.BodyType.Name}"
                                  : attribute.Description;
            var mediaType = attribute.ToOpenApiMediaType <OpenApiResponseBodyAttribute>();
            var content   = new Dictionary <string, OpenApiMediaType>()
            {
                { attribute.ContentType, mediaType }
            };
            var response = new OpenApiResponse()
            {
                Description = description,
                Content     = content
            };

            if (!string.IsNullOrWhiteSpace(attribute.Summary))
            {
                var summary = new OpenApiString(attribute.Summary);

                response.Extensions.Add("x-ms-summary", summary);
            }

            return(response);
        }
        /// <summary>
        /// Converts <see cref="OpenApiResponseWithoutBodyAttribute"/> to <see cref="OpenApiResponse"/>.
        /// </summary>
        /// <param name="attribute"><see cref="OpenApiResponseWithoutBodyAttribute"/> instance.</param>
        /// <param name="namingStrategy"><see cref="NamingStrategy"/> instance to create the JSON schema from .NET Types.</param>
        /// <returns><see cref="OpenApiResponse"/> instance.</returns>
        public static OpenApiResponse ToOpenApiResponse(this OpenApiResponseWithoutBodyAttribute attribute, NamingStrategy namingStrategy = null)
        {
            attribute.ThrowIfNullOrDefault();

            var description = string.IsNullOrWhiteSpace(attribute.Description)
                                  ? "No description"
                                  : attribute.Description;
            var response = new OpenApiResponse()
            {
                Description = description,
            };

            if (!string.IsNullOrWhiteSpace(attribute.Summary))
            {
                var summary = new OpenApiString(attribute.Summary);

                response.Extensions.Add("x-ms-summary", summary);
            }

            if (attribute.HeaderType.HasInterface <IOpenApiResponseHeaderType>())
            {
                var header = Activator.CreateInstance(attribute.HeaderType) as IOpenApiResponseHeaderType;

                response.Headers = header.Headers;
            }

            return(response);
        }
Exemple #4
0
        public void SetResponseExampleForStatusCode(
            OpenApiOperation operation,
            int statusCode,
            object example,
            IContractResolver contractResolver = null,
            JsonConverter jsonConverter        = null)
        {
            if (example == null)
            {
                return;
            }

            var response = operation.Responses.FirstOrDefault(r => r.Key == statusCode.ToString());

            if (response.Equals(default(KeyValuePair <string, OpenApiResponse>)) == false && response.Value != null)
            {
                var serializerSettings = serializerSettingsDuplicator.SerializerSettings(contractResolver, jsonConverter);
                var jsonExample        = new OpenApiString(jsonFormatter.FormatJson(example, serializerSettings));

                OpenApiString xmlExample = null;
                if (response.Value.Content.Keys.Any(k => k.Contains("xml")))
                {
                    xmlExample = new OpenApiString(example.XmlSerialize());
                }

                foreach (var content in response.Value.Content)
                {
                    content.Value.Example = content.Key.Contains("xml") ? xmlExample : jsonExample;
                }
            }
        }
        /// <inheritdoc />
        public OpenApiOperation GetOpenApiOperation(MethodInfo element, FunctionNameAttribute function, OperationType verb)
        {
            var op = element.GetOpenApiOperation();

            if (op.IsNullOrDefault())
            {
                return(null);
            }

            var operation = new OpenApiOperation()
            {
                OperationId = string.IsNullOrWhiteSpace(op.OperationId) ? $"{function.Name}_{verb}" : op.OperationId,
                Tags        = op.Tags.Select(p => new OpenApiTag()
                {
                    Name = p
                }).ToList(),
                Summary     = op.Summary,
                Description = op.Description
            };

            if (op.Visibility != OpenApiVisibilityType.Undefined)
            {
                var visibility = new OpenApiString(op.Visibility.ToDisplayName());

                operation.Extensions.Add("x-ms-visibility", visibility);
            }

            return(operation);
        }
        private static IOpenApiAny CreateStructuredTypePropertiesExample(ODataContext context, IEdmStructuredType structuredType)
        {
            OpenApiObject example = new OpenApiObject();

            IEdmEntityType entityType = structuredType as IEdmEntityType;

            // properties
            foreach (var property in structuredType.Properties())
            {
                // IOpenApiAny item;
                IEdmTypeReference propertyType = property.Type;

                IOpenApiAny item = GetTypeNameForExample(context, propertyType);

                EdmTypeKind typeKind = propertyType.TypeKind();
                if (typeKind == EdmTypeKind.Primitive && item is OpenApiString)
                {
                    OpenApiString stringAny = item as OpenApiString;
                    string        value     = stringAny.Value;
                    if (entityType != null && entityType.Key().Any(k => k.Name == property.Name))
                    {
                        value += " (identifier)";
                    }
                    if (propertyType.IsDateTimeOffset() || propertyType.IsDate() || propertyType.IsTimeOfDay())
                    {
                        value += " (timestamp)";
                    }
                    item = new OpenApiString(value);
                }

                example.Add(property.Name, item);
            }

            return(example);
        }
        public void SetRequestExampleForOperation(
            OpenApiOperation operation,
            object example,
            IContractResolver contractResolver = null,
            JsonConverter jsonConverter        = null)
        {
            if (example == null)
            {
                return;
            }

            if (operation.RequestBody == null || operation.RequestBody.Content == null)
            {
                return;
            }

            var serializerSettings = serializerSettingsDuplicator.SerializerSettings(contractResolver, jsonConverter);
            var jsonExample        = new OpenApiString(jsonFormatter.FormatJson(example, serializerSettings));

            OpenApiString xmlExample = null;

            if (operation.RequestBody.Content.Keys.Any(k => k.Contains("xml")))
            {
                xmlExample = new OpenApiString(example.XmlSerialize());
            }

            foreach (var content in operation.RequestBody.Content)
            {
                content.Value.Example = content.Key.Contains("xml") ? xmlExample : jsonExample;
            }
        }
        public override void Patch(OpenApiSchema schema, OpenApiObject xProps, OpenApiObject templateOptions,
                                   LinkGenerator linkGenerator,
                                   List <ValidatorModel> validators)
        {
            base.Patch(schema, xProps, templateOptions, linkGenerator, validators);

            var customConfig = templateOptions.GetOrSetDefault <OpenApiObject, IOpenApiAny>("customFieldConfig");

            customConfig["labelProp"] = new OpenApiString(LabelProp);
            customConfig["valueProp"] = new OpenApiString(ValueProp);

            var optionsUrl = OptionsControllerType != null
                ? linkGenerator.GetAbsolutePathByAction(OptionsActionName,
                                                        TypeHelpers.GetControllerName(OptionsControllerType))
                : OptionsUrl;

            customConfig["loadOptionsFromUrl"] = new OpenApiBoolean(true);
            customConfig["optionsUrl"]         = new OpenApiString(optionsUrl);

            customConfig["reloadOptionsOnInit"] = new OpenApiBoolean(ReloadOptionsOnInit);
            customConfig["showReloadButton"]    = new OpenApiBoolean(ShowReloadButton);

            var fieldGroupFill = customConfig.GetOrSetDefault <OpenApiObject, IOpenApiAny>("fieldGroupFill");

            fieldGroupFill["enabled"]           = new OpenApiBoolean(true);
            fieldGroupFill["keepValueProp"]     = new OpenApiBoolean(KeepValueProp);
            fieldGroupFill["selectorFieldType"] = new OpenApiString(SelectorFieldType ?? "autocomplete");
        }
        /// <summary>
        /// Converts <see cref="OpenApiResponseWithBodyAttribute"/> to <see cref="OpenApiResponse"/>.
        /// </summary>
        /// <param name="attribute"><see cref="OpenApiResponseWithBodyAttribute"/> instance.</param>
        /// <param name="namingStrategy"><see cref="NamingStrategy"/> instance to create the JSON schema from .NET Types.</param>
        /// <param name="collection"><see cref="VisitorCollection"/> instance.</param>
        /// <param name="version">OpenAPI spec version.</param>
        /// <returns><see cref="OpenApiResponse"/> instance.</returns>
        public static OpenApiResponse ToOpenApiResponse(this OpenApiResponseWithBodyAttribute attribute, NamingStrategy namingStrategy = null, VisitorCollection collection = null, OpenApiVersionType version = OpenApiVersionType.V2)
        {
            attribute.ThrowIfNullOrDefault();

            var description = string.IsNullOrWhiteSpace(attribute.Description)
                                  ? $"Payload of {attribute.BodyType.GetOpenApiDescription()}"
                                  : attribute.Description;
            var mediaType = attribute.ToOpenApiMediaType <OpenApiResponseWithBodyAttribute>(namingStrategy, collection, version);
            var content   = new Dictionary <string, OpenApiMediaType>()
            {
                { attribute.ContentType, mediaType }
            };
            var response = new OpenApiResponse()
            {
                Description = description,
                Content     = content,
            };

            if (attribute.CustomHeaderType.HasInterface <IOpenApiCustomResponseHeader>())
            {
                var header = Activator.CreateInstance(attribute.CustomHeaderType) as IOpenApiCustomResponseHeader;

                response.Headers = header.Headers;
            }

            if (!string.IsNullOrWhiteSpace(attribute.Summary))
            {
                var summary = new OpenApiString(attribute.Summary);

                response.Extensions.Add("x-ms-summary", summary);
            }

            return(response);
        }
Exemple #10
0
        public static IEnumerable <EnumMember> ApplyEnumExtensions(this Type type, IDictionary <string, IOpenApiExtension> extensions, ISchemaGenerator schemaGenerator, SchemaRepository schemaRepository)
        {
            type = type.UnwrapIfNullable();

            if (!type.IsEnum || extensions == null)
            {
                return(null);
            }

            var underlyingType = type.GetEnumUnderlyingType();
            var members        = type.GetEnumMembers();

            var memberDictionary = new OpenApiObject();

            foreach (var member in members)
            {
                memberDictionary[member.Name] = new OpenApiLong(long.Parse(member.Value.ToString()));  // Will never be wider than a long.
            }

            var obsoleteDictionary = new OpenApiObject();

            foreach (var field in members.Where(f => f.IsObsolete))
            {
                obsoleteDictionary[field.Name] = new OpenApiString(field.ObsoleteMessage ?? string.Empty);
            }

            var dictionary = new OpenApiObject
            {
                ["id"]     = new OpenApiString(type.FullName),
                ["fields"] = memberDictionary,
            };

            if (obsoleteDictionary.Count > 0)
            {
                dictionary["deprecated"] = obsoleteDictionary;
            }

            if (type.GetCustomAttribute <FlagsAttribute>() != null)
            {
                dictionary["flags"] = new OpenApiBoolean(true);
            }

            var enumSchema = schemaGenerator.GenerateSchema(underlyingType, schemaRepository);

            foreach (var extension in enumSchema.Extensions)
            {
                dictionary[extension.Key] = (IOpenApiAny)extension.Value;
            }

            var obsoleteAttribute = type.GetCustomAttribute <ObsoleteAttribute>();

            if (obsoleteAttribute != null)
            {
                dictionary["x-costar-deprecated"] = new OpenApiString(obsoleteAttribute.Message);
            }

            extensions[VendorExtensions.Enum] = dictionary;

            return(members);
        }
Exemple #11
0
        /// <summary>
        /// Converts <see cref="OpenApiParameterAttribute"/> to <see cref="OpenApiParameter"/>.
        /// </summary>
        /// <param name="attribute"><see cref="OpenApiParameterAttribute"/> instance.</param>
        /// <returns><see cref="OpenApiParameter"/> instance.</returns>
        public static OpenApiParameter ToOpenApiParameter(this OpenApiParameterAttribute attribute)
        {
            attribute.ThrowIfNullOrDefault();

            var typeCode = Type.GetTypeCode(attribute.Type);
            var schema   = new OpenApiSchema()
            {
                Type   = typeCode.ToDataType(),
                Format = typeCode.ToDataFormat()
            };
            var parameter = new OpenApiParameter()
            {
                Name        = attribute.Name,
                Description = attribute.Description,
                Required    = attribute.Required,
                In          = attribute.In,
                Schema      = schema
            };

            if (!string.IsNullOrWhiteSpace(attribute.Summary))
            {
                var summary = new OpenApiString(attribute.Summary);

                parameter.Extensions.Add("x-ms-summary", summary);
            }

            if (attribute.Visibility != OpenApiVisibilityType.Undefined)
            {
                var visibility = new OpenApiString(attribute.Visibility.ToDisplayName());

                parameter.Extensions.Add("x-ms-visibility", visibility);
            }

            return(parameter);
        }
Exemple #12
0
        public void Apply(OpenApiSchema model, SchemaFilterContext context)
        {
            // Patch only root level schemas, and not the members(properties) schemas of other schemas
            if (!context.Type.IsEnum || context.MemberInfo != null)
            {
                return;
            }

            model.Enum = Enum.GetValues(context.Type).Cast <Enum>()
                         .Select(value => (IOpenApiAny) new OpenApiString(value.GetCustomValue().ToString()))
                         .ToList();

            var templateOptions = model.Extensions.GetOrSetDefault("x-templateOptions", new OpenApiObject());
            var optionsArray    = templateOptions.GetOrSetDefault("options", new OpenApiArray());

            optionsArray.AddRange(Enum.GetValues(context.Type).Cast <Enum>()
                                  .Select(enumValue =>
            {
                var option = new OpenApiObject
                {
                    ["value"] = OpenApiExtensions.ToOpenApi(enumValue.GetCustomValue()),
                    ["label"] = new OpenApiString(enumValue.GetDisplayName()),
                };
                if (enumValue.GetDisplayDescription() is { } s&& !string.IsNullOrEmpty(s))
                {
                    option["description"] = new OpenApiString(s);
                }

                return(option);
            }));
        }
Exemple #13
0
        public void Apply(OpenApiSchema schema, SchemaFilterContext context)
        {
            var type         = context.Type;
            var genericTypes = type.GetGenericTypes();

            var dictionaryType =
                genericTypes.FirstOrDefault(t => t.GetGenericTypeDefinition() == typeof(IDictionary <,>)) ??
                genericTypes.FirstOrDefault(t => t.GetGenericTypeDefinition() == typeof(IReadOnlyDictionary <,>));

            if (dictionaryType == null)
            {
                return;
            }

            var keyType   = dictionaryType.GetGenericArguments()[0];
            var keySchema = context.SchemaGenerator.GenerateSchema(keyType, context.SchemaRepository);

            var valueType = dictionaryType.GetGenericArguments()[1];

            valueType.ApplyPrimitiveExtensions(schema.AdditionalProperties?.Extensions);
            valueType.ApplyEnumExtensions(schema.AdditionalProperties?.Extensions, context.SchemaGenerator, context.SchemaRepository);

            var dictionary = new OpenApiObject();

            if (keySchema.Reference != null)
            {
                dictionary["$ref"] = new OpenApiString(keySchema.Reference.ReferenceV2);
            }
            else
            {
                dictionary["type"] = new OpenApiString(keySchema.Type);

                if (keySchema.Format != null)
                {
                    dictionary["format"] = new OpenApiString(keySchema.Format);
                }
            }

            foreach (var extension in keySchema.Extensions)
            {
                dictionary[extension.Key] = (IOpenApiAny)extension.Value;
            }

            schema.Extensions[VendorExtensions.KeySchema] = dictionary;

            if (schema != null)
            {
                if (schema.Properties != null)
                {
                    var first = schema.Properties.Values.FirstOrDefault();

                    if (first != null)
                    {
                        // Re-write the schema to be the same "shape" as other dictionaries.
                        schema.Properties           = null;
                        schema.AdditionalProperties = first;
                    }
                }
            }
        }
        public static PropertyDeclarationSyntax CreateAuto(
            ParameterLocation?parameterLocation,
            bool isNullable,
            bool isRequired,
            string dataType,
            string propertyName,
            bool useNullableReferenceTypes,
            IOpenApiAny?initializer)
        {
            if (useNullableReferenceTypes && (isNullable || parameterLocation == ParameterLocation.Query) && !isRequired)
            {
                dataType += "?";
            }

            var propertyDeclaration = CreateAuto(dataType, propertyName);

            if (initializer != null)
            {
                propertyDeclaration = initializer switch
                {
                    OpenApiInteger apiInteger => propertyDeclaration.WithInitializer(
                        SyntaxFactory.EqualsValueClause(SyntaxFactory.LiteralExpression(
                                                            SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(apiInteger !.Value))))
                    .WithSemicolonToken(SyntaxTokenFactory.Semicolon()),
                    OpenApiString apiString => propertyDeclaration.WithInitializer(
                        SyntaxFactory.EqualsValueClause(SyntaxFactory.LiteralExpression(
                                                            SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(apiString !.Value))))
                    .WithSemicolonToken(SyntaxTokenFactory.Semicolon()),
                    _ => throw new NotImplementedException("Property initializer: " + initializer.GetType())
                };
            }

            return(propertyDeclaration);
        }
Exemple #15
0
        public static string GetPrimitiveValue(IOpenApiAny value)
        {
            IOpenApiPrimitive primitive = (IOpenApiPrimitive)value;

            switch (primitive.PrimitiveType)
            {
            case PrimitiveType.String:
                OpenApiString stringValue = (OpenApiString)primitive;
                return(stringValue.Value);

            case PrimitiveType.Boolean:
                OpenApiBoolean booleanValue = (OpenApiBoolean)primitive;
                return(booleanValue.Value.ToString());

            case PrimitiveType.Integer:
                OpenApiInteger integerValue = (OpenApiInteger)primitive;
                return(integerValue.Value.ToString());

            case PrimitiveType.Long:
                OpenApiLong longValue = (OpenApiLong)primitive;
                return(longValue.Value.ToString());

            case PrimitiveType.Float:
                OpenApiFloat floatValue = (OpenApiFloat)primitive;
                return(floatValue.Value.ToString(CultureInfo.InvariantCulture));

            case PrimitiveType.Double:
                OpenApiDouble doubleValue = (OpenApiDouble)primitive;
                return(doubleValue.Value.ToString(CultureInfo.InvariantCulture));

            case PrimitiveType.Byte:
                OpenApiByte byteValue = (OpenApiByte)primitive;
                return(Encoding.Default.GetString(byteValue.Value));

            case PrimitiveType.Binary:
                OpenApiBinary binaryValue = (OpenApiBinary)primitive;
                StringBuilder builder     = new StringBuilder();
                foreach (byte byteVal in binaryValue.Value)
                {
                    builder.Append(Convert.ToString(byteVal, 2).PadLeft(8, '0'));
                }
                return(builder.ToString());

            case PrimitiveType.Date:
                OpenApiDate dateValue = (OpenApiDate)primitive;
                return(dateValue.Value.ToString(CultureInfo.InvariantCulture));

            case PrimitiveType.DateTime:
                OpenApiDateTime dateTimeValue = (OpenApiDateTime)primitive;
                return(dateTimeValue.Value.ToString(CultureInfo.InvariantCulture));

            case PrimitiveType.Password:
                OpenApiPassword passwordValue = (OpenApiPassword)primitive;
                return(passwordValue.Value);

            default:
                throw new NotImplementedException("This data example type is not supported yet!");
            }
        }
        /// <summary>
        /// Converts <see cref="Type"/> to <see cref="OpenApiSchema"/>.
        /// </summary>
        /// <param name="type"><see cref="Type"/> instance.</param>
        /// <param name="attribute"><see cref="OpenApiSchemaVisibilityAttribute"/> instance. Default is <c>null</c>.</param>
        /// <returns><see cref="OpenApiSchema"/> instance.</returns>
        /// <remarks>
        /// It runs recursively to build the entire object type. It only takes properties without <see cref="JsonIgnoreAttribute"/>.
        /// </remarks>
        public static OpenApiSchema ToOpenApiSchema(this Type type, OpenApiSchemaVisibilityAttribute attribute = null)
        {
            type.ThrowIfNullOrDefault();
            OpenApiSchema schema = null;

            var unwrappedValueType = Nullable.GetUnderlyingType(type);

            if (unwrappedValueType != null)
            {
                schema          = unwrappedValueType.ToOpenApiSchema();
                schema.Nullable = true;
                return(schema);
            }

            schema = new OpenApiSchema()
            {
                Type   = type.ToDataType(),
                Format = type.ToDataFormat()
            };
            if (attribute != null)
            {
                var visibility = new OpenApiString(attribute.Visibility.ToDisplayName());

                schema.Extensions.Add("x-ms-visibility", visibility);
            }

            if (type.IsSimpleType())
            {
                return(schema);
            }

            if (typeof(IDictionary).IsAssignableFrom(type))
            {
                schema.AdditionalProperties = type.GetGenericArguments()[1].ToOpenApiSchema();

                return(schema);
            }

            if (typeof(IList).IsAssignableFrom(type))
            {
                schema.Type  = "array";
                schema.Items = (type.GetElementType() ?? type.GetGenericArguments()[0]).ToOpenApiSchema();

                return(schema);
            }

            var properties = type.GetProperties()
                             .Where(p => !p.ExistsCustomAttribute <JsonIgnoreAttribute>());

            foreach (var property in properties)
            {
                var visiblity = property.GetCustomAttribute <OpenApiSchemaVisibilityAttribute>(inherit: false);

                schema.Properties[property.Name] = property.PropertyType.ToOpenApiSchema(visiblity);
            }

            return(schema);
        }
        public void Apply([NotNull] OpenApiSchema schema, [NotNull] SchemaFilterContext context)
        {
            if ((schema == null) || (context == null))
            {
                throw new ArgumentNullException(nameof(schema) + " || " + nameof(context));
            }

            if (!context.Type.IsEnum)
            {
                return;
            }

            if (context.Type.IsDefined(typeof(FlagsAttribute), false))
            {
                schema.Format = "flags";
            }

            OpenApiObject definition = new OpenApiObject();

            foreach (object enumValue in context.Type.GetEnumValues())
            {
                string enumName = Enum.GetName(context.Type, enumValue);

                if (string.IsNullOrEmpty(enumName))
                {
                    enumName = enumValue.ToString();

                    if (string.IsNullOrEmpty(enumName))
                    {
                        continue;
                    }
                }

                IOpenApiAny enumObject;

                if (TryCast(enumValue, out int intValue))
                {
                    enumObject = new OpenApiInteger(intValue);
                }
                else if (TryCast(enumValue, out long longValue))
                {
                    enumObject = new OpenApiLong(longValue);
                }
                else if (TryCast(enumValue, out ulong ulongValue))
                {
                    // OpenApi spec doesn't support ulongs as of now
                    enumObject = new OpenApiString(ulongValue.ToString());
                }
                else
                {
                    throw new ArgumentOutOfRangeException(nameof(enumValue));
                }

                definition.Add(enumName, enumObject);
            }

            schema.AddExtension("x-definition", definition);
        }
        private bool TryParse(JsonElement token, out IOpenApiAny?any)
        {
            any = null;

            switch (token.ValueKind)
            {
            case JsonValueKind.Array:
                var array = new OpenApiArray();

                foreach (var value in token.EnumerateArray())
                {
                    if (TryParse(value, out var child))
                    {
                        array.Add(child);
                    }
                }

                any = array;
                return(true);

            case JsonValueKind.False:
                any = new OpenApiBoolean(false);
                return(true);

            case JsonValueKind.True:
                any = new OpenApiBoolean(true);
                return(true);

            case JsonValueKind.Number:
                any = new OpenApiDouble(token.GetDouble());
                return(true);

            case JsonValueKind.String:
                any = new OpenApiString(token.GetString());
                return(true);

            case JsonValueKind.Object:
                var obj = new OpenApiObject();

                foreach (var child in token.EnumerateObject())
                {
                    if (TryParse(child.Value, out var value))
                    {
                        obj[child.Name] = value;
                    }
                }

                any = obj;
                return(true);

            case JsonValueKind.Null:
            case JsonValueKind.Undefined:
            default:
                return(false);
            }
        }
 public override void Patch(OpenApiSchema schema, OpenApiObject xProps, OpenApiObject templateOptions,
                            LinkGenerator linkGenerator,
                            List <ValidatorModel> validators)
 {
     base.Patch(schema, xProps, templateOptions, linkGenerator, validators);
     templateOptions["buttonClasses"]    = new OpenApiString(ButtonClasses);
     templateOptions["actionExpression"] = new OpenApiString(ActionExpression);
     templateOptions["actionTarget"]     = new OpenApiString(ActionTarget);
     templateOptions["fakeLabel"]        = new OpenApiBoolean(FakeLabel);
 }
        public void ParsingValidContentExample()
        {
            string        attributeContent = "test";
            OpenApiString example          = new OpenApiString(attributeContent);
            Dictionary <string, OpenApiExample> examples = new Dictionary <string, OpenApiExample>();

            string parsedExample = ContentParser.GetStringExampleFromContent(example, examples);

            Assert.AreEqual(attributeContent, parsedExample);
        }
        internal override IDictionary <string, IOpenApiAny> ToDictionary()
        {
            var result = new Dictionary <string, IOpenApiAny>();

            if (ApiKeySource.HasValue)
            {
                result[ApiKeySourceKey] = new OpenApiString(Enum.GetName(typeof(ApiKeySource), ApiKeySource.Value)?.ToUpper());
            }

            return(result);
        }
        /// <inheritdoc />
        public override void Visit(IAcceptor acceptor, KeyValuePair <string, Type> type, NamingStrategy namingStrategy, params Attribute[] attributes)
        {
            var instance = acceptor as OpenApiSchemaAcceptor;

            if (instance.IsNullOrDefault())
            {
                return;
            }

            // Gets the schema for the underlying type.
            var underlyingType = type.Value.GetUnderlyingType();
            var types          = new Dictionary <string, Type>()
            {
                { type.Key, underlyingType }
            };
            var schemas = new Dictionary <string, OpenApiSchema>();

            var subAcceptor = new OpenApiSchemaAcceptor()
            {
                Types   = types,
                Schemas = schemas,
            };

            subAcceptor.Accept(this.VisitorCollection, namingStrategy);

            // Adds the schema for the underlying type.
            var name   = subAcceptor.Schemas.First().Key;
            var schema = subAcceptor.Schemas.First().Value;

            schema.Nullable = true;

            // Adds the extra properties.
            if (attributes.Any())
            {
                Attribute attr = attributes.OfType <OpenApiPropertyAttribute>().SingleOrDefault();
                if (!attr.IsNullOrDefault())
                {
                    schema.Nullable    = this.GetOpenApiPropertyNullable(attr as OpenApiPropertyAttribute);
                    schema.Default     = this.GetOpenApiPropertyDefault(attr as OpenApiPropertyAttribute);
                    schema.Description = this.GetOpenApiPropertyDescription(attr as OpenApiPropertyAttribute);
                    schema.Deprecated  = this.GetOpenApiPropertyDeprecated(attr as OpenApiPropertyAttribute);
                }

                attr = attributes.OfType <OpenApiSchemaVisibilityAttribute>().SingleOrDefault();
                if (!attr.IsNullOrDefault())
                {
                    var extension = new OpenApiString((attr as OpenApiSchemaVisibilityAttribute).Visibility.ToDisplayName());

                    schema.Extensions.Add("x-ms-visibility", extension);
                }
                schema.ApplyValidationAttributes(attributes.OfType <ValidationAttribute>());
            }
            instance.Schemas.Add(name, schema);
        }
Exemple #23
0
 public void Apply(OpenApiSchema schema, SchemaFilterContext context)
 {
     if (context.GetType().IsEnum)
     {
         var obj = new OpenApiObject();
         obj["name"]          = new OpenApiString(context.GetType().Name);
         obj["modelAsString"] = new OpenApiBoolean(false);
         schema.Extensions.Add(
             "x-ms-enum",
             obj);
     }
 }
Exemple #24
0
        public static bool TryCreateFor(OpenApiSchema schema, object value, out IOpenApiAny openApiAny)
        {
            openApiAny = null;

            if (schema.Type == "boolean" && TryCast(value, out bool boolValue))
            {
                openApiAny = new OpenApiBoolean(boolValue);
            }

            else if (schema.Type == "integer" && schema.Format == "int16" && TryCast(value, out short shortValue))
            {
                openApiAny = new OpenApiInteger(shortValue); // preliminary unboxing is required; simply casting to int won't suffice
            }
            else if (schema.Type == "integer" && schema.Format == "int32" && TryCast(value, out int intValue))
            {
                openApiAny = new OpenApiInteger(intValue);
            }

            else if (schema.Type == "integer" && schema.Format == "int64" && TryCast(value, out long longValue))
            {
                openApiAny = new OpenApiLong(longValue);
            }

            else if (schema.Type == "number" && schema.Format == "float" && TryCast(value, out float floatValue))
            {
                openApiAny = new OpenApiFloat(floatValue);
            }

            else if (schema.Type == "number" && schema.Format == "double" && TryCast(value, out double doubleValue))
            {
                openApiAny = new OpenApiDouble(doubleValue);
            }

            else if (schema.Type == "string" && value.GetType().IsEnum)
            {
                openApiAny = new OpenApiString(Enum.GetName(value.GetType(), value));
            }

            else if (schema.Type == "string" && schema.Format == "date-time" && TryCast(value, out DateTime dateTimeValue))
            {
                openApiAny = new OpenApiDate(dateTimeValue);
            }

            else if (schema.Type == "string")
            {
                openApiAny = new OpenApiString(value.ToString());
            }

            return(openApiAny != null);
        }
        /// <inheritdoc />
        public override void Visit(IAcceptor acceptor, KeyValuePair <string, Type> type, NamingStrategy namingStrategy, params Attribute[] attributes)
        {
            var instance = acceptor as OpenApiSchemaAcceptor;

            if (instance.IsNullOrDefault())
            {
                return;
            }

            // Gets the schema for the underlying type.
            type.Value.IsOpenApiNullable(out var underlyingType);

            var types = new Dictionary <string, Type>()
            {
                { type.Key, underlyingType }
            };
            var schemas = new Dictionary <string, OpenApiSchema>();

            var subAcceptor = new OpenApiSchemaAcceptor()
            {
                Types   = types,
                Schemas = schemas,
            };

            var collection = VisitorCollection.CreateInstance();

            subAcceptor.Accept(collection, namingStrategy);

            // Adds the schema for the underlying type.
            var name   = subAcceptor.Schemas.First().Key;
            var schema = subAcceptor.Schemas.First().Value;

            schema.Nullable = true;

            // Adds the visibility property.
            if (attributes.Any())
            {
                var visibilityAttribute = attributes.OfType <OpenApiSchemaVisibilityAttribute>().SingleOrDefault();
                if (!visibilityAttribute.IsNullOrDefault())
                {
                    var extension = new OpenApiString(visibilityAttribute.Visibility.ToDisplayName());

                    schema.Extensions.Add("x-ms-visibility", extension);
                }
            }

            instance.Schemas.Add(name, schema);
        }
 public override void FillProperties(PropertyInfo property)
 {
     if (property.GetCustomAttribute(typeof(BoolInlineEditingAttribute)) is
         BoolInlineEditingAttribute boolInlineEditingAttribute)
     {
         var openApiObject = new OpenApiObject();
         openApiObject["boolInlineEditingChangePath"] =
             new OpenApiString(boolInlineEditingAttribute.BoolInlineEditingChangePath);
         openApiObject["boolInlineDeletingIdQueryParamName"] =
             new OpenApiString(boolInlineEditingAttribute.BoolInlineDeletingIdQueryParamName);
         openApiObject["boolInlineDeletingIdPropertyName"] =
             new OpenApiString(boolInlineEditingAttribute.BoolInlineDeletingIdPropertyName);
         Properties.Add(
             property.Name.ToLower(),
             openApiObject);
     }
 }
        /// <inheritdoc />
        public override void Visit(IAcceptor acceptor, KeyValuePair <string, Type> type, NamingStrategy namingStrategy, params Attribute[] attributes)
        {
            var name = type.Key;

            var instance = acceptor as OpenApiSchemaAcceptor;

            if (instance.IsNullOrDefault())
            {
                return;
            }

            // Adds enum values to the schema.
            var enums = type.Value.ToOpenApiInt64Collection();

            var schema = new OpenApiSchema()
            {
                Type    = "integer",
                Format  = "int64",
                Enum    = enums,
                Default = enums.First()
            };

            // Adds the extra properties.
            if (attributes.Any())
            {
                Attribute attr = attributes.OfType <OpenApiPropertyAttribute>().SingleOrDefault();
                if (!attr.IsNullOrDefault())
                {
                    schema.Nullable    = this.GetOpenApiPropertyNullable(attr as OpenApiPropertyAttribute);
                    schema.Default     = this.GetOpenApiPropertyDefault <long>(attr as OpenApiPropertyAttribute);
                    schema.Description = this.GetOpenApiPropertyDescription(attr as OpenApiPropertyAttribute);
                    schema.Deprecated  = this.GetOpenApiPropertyDeprecated(attr as OpenApiPropertyAttribute);
                }

                attr = attributes.OfType <OpenApiSchemaVisibilityAttribute>().SingleOrDefault();
                if (!attr.IsNullOrDefault())
                {
                    var extension = new OpenApiString((attr as OpenApiSchemaVisibilityAttribute).Visibility.ToDisplayName());

                    schema.Extensions.Add("x-ms-visibility", extension);
                }
            }

            instance.Schemas.Add(name, schema);
        }
        public override OpenApiObject GetCustomOpenApiConfig(LinkGenerator linkGenerator)
        {
            var obj = new OpenApiObject
            {
                ["labelProp"] = new OpenApiString(LabelProp),
                ["valueProp"] = new OpenApiString(ValueProp)
            };
            var optionsUrl = OptionsControllerType != null
                ? linkGenerator.GetAbsolutePathByAction(OptionsActionName,
                                                        TypeHelpers.GetControllerName(OptionsControllerType))
                : OptionsUrl;

            obj["loadOptionsFromUrl"]  = new OpenApiBoolean(true);
            obj["optionsUrl"]          = new OpenApiString(optionsUrl);
            obj["reloadOptionsOnInit"] = new OpenApiBoolean(ReloadOptionsOnInit);
            obj["showReloadButton"]    = new OpenApiBoolean(ShowReloadButton);
            return(obj);
        }
Exemple #29
0
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (schema?.Properties == null)
        {
            return;
        }
        if (schema.Properties.Any())
        {
            foreach (var propType in context.Type.GetProperties().Where(x => x.CustomAttributes != null && x.CustomAttributes.Any()))
            {
                var    schemaProp = schema.Properties.FirstOrDefault(x => x.Key.Equals(propType.Name, StringComparison.InvariantCultureIgnoreCase));
                string newName    = propType.GetCustomAttribute <DataMemberAttribute>()?.Name;
                if (string.IsNullOrEmpty(newName))
                {
                    continue;
                }
                if (schemaProp.Value.Enum != null && schemaProp.Value.Enum.Any())
                {
                    for (int i = 0; i < schemaProp.Value.Enum.Count; i++)
                    {
                        OpenApiString curr       = schemaProp.Value.Enum[i] as OpenApiString;
                        var           memberInfo = propType.PropertyType.GetMember(curr.Value).FirstOrDefault();
                        string        newValue   = memberInfo.GetCustomAttribute <EnumMemberAttribute>()?.Value;
                        if (string.IsNullOrWhiteSpace(newValue))
                        {
                            continue;
                        }
                        OpenApiString newStr = new OpenApiString(newValue);
                        schemaProp.Value.Enum.Remove(curr);
                        schemaProp.Value.Enum.Insert(0, newStr);
                    }
                }
                var newSchemaProp = new KeyValuePair <string, OpenApiSchema>(newName, schemaProp.Value);
                schema.Properties.Remove(schemaProp);
                schema.Properties.Add(newSchemaProp);
            }
        }
        var objAttribute = context.Type.GetCustomAttribute <DataContractAttribute>();

        if (objAttribute != default && objAttribute?.Name?.Length > 0)
        {
            schema.Title = objAttribute.Name;
        }
    }
Exemple #30
0
        public OpenApiObject ToOpenApiObject()
        {
            var oaObject = new OpenApiObject
            {
                { "name", new OpenApiString(Name) }
            };

            if (Args?.ToString() != null)
            {
                oaObject["args"] = OpenApiExtensions.ToOpenApi(Args);
            }

            if (!string.IsNullOrEmpty(Message))
            {
                oaObject["message"] = new OpenApiString(Message);
            }

            return(oaObject);
        }