コード例 #1
0
        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);
        }
コード例 #2
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!");
            }
        }
コード例 #3
0
        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);
        }
コード例 #4
0
        public void WriteOpenApiIntegerAsJsonWorks(int input, bool produceTerseOutput)
        {
            // Arrange
            var intValue = new OpenApiInteger(input);

            var json = WriteAsJson(intValue, produceTerseOutput);

            // Assert
            json.Should().Be(input.ToString());
        }
コード例 #5
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 }
            });
        }
コード例 #6
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);
        }
コード例 #7
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);
        }
コード例 #8
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);
        }
コード例 #9
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);
        }
コード例 #10
0
 public QueryStringParameterAttribute(string name, string description, int example)
 {
     Initialise(name, description);
     DataType = typeof(int);
     Example  = new OpenApiInteger(example);
 }