Пример #1
0
        internal override IDictionary <string, IOpenApiAny> ToDictionary()
        {
            var children = new OpenApiObject();

            if (Types != null && Types.Any())
            {
                var types = new OpenApiArray();
                types.AddRange(Types.Select(x => new OpenApiString(x)));

                children[TypesKey] = types;
            }

            if (VpcEndpointIds != null && VpcEndpointIds.Any())
            {
                var vpcIds = new OpenApiArray();
                vpcIds.AddRange(VpcEndpointIds.Select(x => new OpenApiString(x)));

                children[VpcEndpointIdsKey] = vpcIds;
            }

            if (DisableExecuteApiEndpoint.HasValue)
            {
                children[DisableExecuteApiEndpointKey] = new OpenApiBoolean(DisableExecuteApiEndpoint.Value);
            }

            return(new Dictionary <string, IOpenApiAny>()
            {
                { EndpointConfigurationRootKey, children }
            });
        }
Пример #2
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);
        }
Пример #3
0
        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");
        }
Пример #4
0
 public override void Patch(OpenApiSchema schema, OpenApiObject xProps, OpenApiObject templateOptions,
                            LinkGenerator linkGenerator,
                            List <ValidatorModel> validators)
 {
     base.Patch(schema, xProps, templateOptions, linkGenerator, validators);
     templateOptions["requiredFromList"] = new OpenApiBoolean(true);
 }
Пример #5
0
        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);
        }
Пример #6
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!");
            }
        }
        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);
            }
        }
Пример #8
0
 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);
 }
Пример #9
0
        public void WriteOpenApiBooleanAsJsonWorks(bool input, bool produceTerseOutput)
        {
            // Arrange
            var boolValue = new OpenApiBoolean(input);

            var json = WriteAsJson(boolValue, produceTerseOutput);

            // Assert
            json.Should().Be(input.ToString().ToLower());
        }
Пример #10
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);
     }
 }
Пример #11
0
        internal override IDictionary <string, IOpenApiAny> ToDictionary()
        {
            var children = new OpenApiObject();

            if (AllowOrigins != null && AllowOrigins.Any())
            {
                var allowOrigins = new OpenApiArray();
                allowOrigins.AddRange(AllowOrigins.Select(x => new OpenApiString(x)));

                children[AllowOriginsKey] = allowOrigins;
            }

            if (AllowCredentials.HasValue)
            {
                children[AllowCredentialsKey] = new OpenApiBoolean(AllowCredentials.Value);
            }

            if (ExposeHeaders != null && ExposeHeaders.Any())
            {
                var exposeHeaders = new OpenApiArray();
                exposeHeaders.AddRange(ExposeHeaders.Select(x => new OpenApiString(x)));

                children[ExposeHeadersKey] = exposeHeaders;
            }

            if (MaxAge.HasValue)
            {
                children[MaxAgeKey] = new OpenApiInteger(MaxAge.Value);
            }

            if (AllowMethods != null && AllowMethods.Any())
            {
                var allowMethods = new OpenApiArray();
                allowMethods.AddRange(AllowMethods.Select(x => new OpenApiString(x)));

                children[AllowMethodsKey] = allowMethods;
            }

            if (AllowHeaders != null && AllowHeaders.Any())
            {
                var allowHeaders = new OpenApiArray();
                allowHeaders.AddRange(AllowHeaders.Select(x => new OpenApiString(x)));

                children[AllowHeadersKey] = allowHeaders;
            }

            return(new Dictionary <string, IOpenApiAny>()
            {
                { CORSRootKey, children }
            });
        }
Пример #12
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);
        }
Пример #13
0
        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);
        }
Пример #14
0
        public static Dictionary <string, OpenApiSchema> CreateProperties(Type sourceType)
        {
            var result = new Dictionary <string, OpenApiSchema>();
            var props  = sourceType.GetProperties();

            foreach (var prop in props)
            {
                if (prop.GetAccessors().Any(x => x.IsStatic))
                {
                    continue;
                }
                var schema = new OpenApiSchema {
                    Type = "object"
                };
                if (prop.PropertyType == typeof(string))
                {
                    var stringProperty = new OpenApiString("");
                    schema.Type    = stringProperty.PrimitiveType.ToString();
                    schema.Default = stringProperty;
                }
                else if (prop.PropertyType == typeof(bool))
                {
                    var boolJsonProperty = new OpenApiBoolean(false);
                    schema.Type    = boolJsonProperty.PrimitiveType.ToString();
                    schema.Default = boolJsonProperty;
                }
                else if (prop.PropertyType == typeof(int))
                {
                    var intPropertyType = new OpenApiInteger(0);
                    schema.Type    = intPropertyType.PrimitiveType.ToString();
                    schema.Default = intPropertyType;
                    schema.Format  = "Int32";
                }
                schema.Description = GetAttributeValue <DescriptionAttribute>(prop.PropertyType)?.Description;
                result.Add(prop.Name, schema);
            }
            return(result);
        }
Пример #15
0
 public QueryStringParameterAttribute(string name, string description, bool example)
 {
     Initialise(name, description);
     DataType = typeof(bool);
     Example  = new OpenApiBoolean(example);
 }
Пример #16
0
        private static IOpenApiPrimitive GetStructValue(Type type, object value)
        {
            var openValue = default(IOpenApiPrimitive);

            if (type == typeof(DateTime?) && ((DateTime?)value).HasValue)
            {
                openValue = new OpenApiDate(((DateTime?)value).Value.ToUniversalTime());
            }
            else if (type == typeof(DateTime) && ((DateTime)value) != default(DateTime))
            {
                openValue = new OpenApiDate(((DateTime)value).ToUniversalTime());
            }
            else if (type == typeof(string))
            {
                openValue = new OpenApiString((string)value);
            }
            else if (type == typeof(int) || type == typeof(int?))
            {
                openValue = new OpenApiInteger((int)value);
            }
            else if (type == typeof(short) || type == typeof(short?))
            {
                openValue = new OpenApiInteger((short)value);
            }
            else if (type == typeof(long) || type == typeof(long?))
            {
                openValue = new OpenApiLong((long)value);
            }
            else if (type == typeof(float) || type == typeof(float?))
            {
                openValue = new OpenApiFloat((float)value);
            }
            else if (type == typeof(decimal) || type == typeof(decimal?))
            {
                openValue = new OpenApiDouble((double)(decimal)value);
            }
            else if (type == typeof(double) || type == typeof(double?))
            {
                openValue = new OpenApiDouble((double)value);
            }
            else if (type == typeof(bool) || type == typeof(bool?))
            {
                openValue = new OpenApiBoolean((bool)value);
            }
            else if (type == typeof(Guid) || type == typeof(Guid?))
            {
                openValue = new OpenApiString($"{value}");
            }
            else if (type == typeof(byte) || type == typeof(byte?))
            {
                openValue = new OpenApiByte((byte)value);
            }
            else if (
#if NETSTANDARD14
                type.GetTypeInfo().IsEnum || Nullable.GetUnderlyingType(type)?.GetTypeInfo().IsEnum == true)
            {
#else
                type.IsEnum || Nullable.GetUnderlyingType(type)?.IsEnum == true) {
#endif
                openValue = new OpenApiString($"{value}");
            }
            else if (type.IsValueType && !type.IsPrimitive && !type.Namespace.StartsWith("System") && !type.IsEnum)
            {
                openValue = new OpenApiString($"{value}");
            }

            return(openValue);
        }
Пример #17
0
        /// <summary>
        /// Creates a new instance of <see cref="IOpenApiAny"/> based on the OpenAPI document format.
        /// </summary>
        /// <param name="instance">instance.</param>
        /// <param name="settings"><see cref="JsonSerializerSettings"/>settings.</param>
        /// <returns><see cref="IOpenApiAny"/> instance.</returns>
        public static IOpenApiAny CreateInstance <T>(T instance, JsonSerializerSettings settings)
        {
            Type type  = typeof(T);
            var  @enum = Type.GetTypeCode(type);
            var  openApiExampleValue = default(IOpenApiAny);

            switch (@enum)
            {
            case TypeCode.Int16:
                openApiExampleValue = new OpenApiInteger(Convert.ToInt16(instance));
                break;

            case TypeCode.Int32:
                openApiExampleValue = new OpenApiInteger(Convert.ToInt32(instance));
                break;

            case TypeCode.Int64:
                openApiExampleValue = new OpenApiLong(Convert.ToInt64(instance));
                break;

            case TypeCode.UInt16:
                openApiExampleValue = new OpenApiDouble(Convert.ToUInt16(instance));
                break;

            case TypeCode.UInt32:
                openApiExampleValue = new OpenApiDouble(Convert.ToUInt32(instance));
                break;

            case TypeCode.UInt64:
                openApiExampleValue = new OpenApiDouble(Convert.ToUInt64(instance));
                break;

            case TypeCode.Single:
                openApiExampleValue = new OpenApiFloat(Convert.ToSingle(instance));
                break;

            case TypeCode.Double:
                openApiExampleValue = new OpenApiDouble(Convert.ToDouble(instance));
                break;

            case TypeCode.Boolean:
                openApiExampleValue = new OpenApiBoolean(Convert.ToBoolean(instance));
                break;

            case TypeCode.String:
                openApiExampleValue = new OpenApiString(Convert.ToString(instance));
                break;

            case TypeCode.DateTime:
                openApiExampleValue = new OpenApiDateTime(Convert.ToDateTime(instance));
                break;

            case TypeCode.Object when type == typeof(DateTimeOffset):
                openApiExampleValue = new OpenApiDateTime((DateTimeOffset)(Convert.ChangeType(instance, type)));
                break;

            case TypeCode.Object when type == typeof(Guid):
                openApiExampleValue = new OpenApiString(Convert.ToString(instance));
                break;

            case TypeCode.Object when type == typeof(byte[]):
                openApiExampleValue = new OpenApiString(Convert.ToBase64String((byte[])Convert.ChangeType(instance, type)));
                break;

            case TypeCode.Object:
                openApiExampleValue = new OpenApiString(JsonConvert.SerializeObject(instance, settings));
                break;

            default:
                throw new InvalidOperationException("Invalid OpenAPI data Format");
            }

            return(openApiExampleValue);
        }