remove the OpenApi.Net source codes

This commit is contained in:
Sam Xu 2017-11-22 11:53:32 -08:00
parent 82341b6664
commit 265984c888
100 changed files with 0 additions and 9128 deletions

View file

@ -1,36 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using Microsoft.OpenApi.Any;
namespace Microsoft.OpenApi.Any
{
/// <summary>
/// Type of an <see cref="IOpenApiAny"/>
/// </summary>
public enum AnyType
{
/// <summary>
/// Primitive.
/// </summary>
Primitive,
/// <summary>
/// Null.
/// </summary>
Null,
/// <summary>
/// Array.
/// </summary>
Array,
/// <summary>
/// Object.
/// </summary>
Object
}
}

View file

@ -1,20 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using Microsoft.OpenApi.Interfaces;
namespace Microsoft.OpenApi.Any
{
/// <summary>
/// Base interface for all the types that represent Open API Any.
/// </summary>
public interface IOpenApiAny : IOpenApiElement
{
/// <summary>
/// Type of an <see cref="IOpenApiAny"/>.
/// </summary>
AnyType AnyType { get; }
}
}

View file

@ -1,79 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.OpenApi.Any
{
/// <summary>
/// Primitive type.
/// </summary>
public enum PrimitiveType
{
/// <summary>
/// Integer
/// </summary>
Integer,
/// <summary>
/// Long
/// </summary>
Long,
/// <summary>
/// Float
/// </summary>
Float,
/// <summary>
/// Double
/// </summary>
Double,
/// <summary>
/// String
/// </summary>
String,
/// <summary>
/// Byte
/// </summary>
Byte,
/// <summary>
/// Binary
/// </summary>
Binary,
/// <summary>
/// Boolean
/// </summary>
Boolean,
/// <summary>
/// Date
/// </summary>
Date,
/// <summary>
/// DateTime
/// </summary>
DateTime,
/// <summary>
/// Password
/// </summary>
Password
}
/// <summary>
/// Base interface for the Primitive type.
/// </summary>
public interface IOpenApiPrimitive : IOpenApiAny
{
/// <summary>
/// Primitive type.
/// </summary>
PrimitiveType PrimitiveType { get; }
}
}

View file

@ -1,20 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Collections.Generic;
namespace Microsoft.OpenApi.Any
{
/// <summary>
/// Open API array.
/// </summary>
public class OpenApiArray : List<IOpenApiAny>, IOpenApiAny
{
/// <summary>
/// The type of <see cref="IOpenApiAny"/>
/// </summary>
public AnyType AnyType { get; } = AnyType.Array;
}
}

View file

@ -1,27 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.OpenApi.Any
{
/// <summary>
/// Open API binary.
/// </summary>
public class OpenApiBinary : OpenApiPrimitive<byte[]>
{
/// <summary>
/// Initializes the <see cref="OpenApiBinary"/> class.
/// </summary>
/// <param name="value"></param>
public OpenApiBinary(byte[] value)
: base(value)
{
}
/// <summary>
/// Primitive type this object represents.
/// </summary>
public override PrimitiveType PrimitiveType { get; } = PrimitiveType.Binary;
}
}

View file

@ -1,27 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.OpenApi.Any
{
/// <summary>
/// Open API boolean.
/// </summary>
public class OpenApiBoolean : OpenApiPrimitive<bool>
{
/// <summary>
/// Initializes the <see cref="OpenApiBoolean"/> class.
/// </summary>
/// <param name="value"></param>
public OpenApiBoolean(bool value)
: base(value)
{
}
/// <summary>
/// Primitive type this object represents.
/// </summary>
public override PrimitiveType PrimitiveType { get; } = PrimitiveType.Boolean;
}
}

View file

@ -1,26 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.OpenApi.Any
{
/// <summary>
/// Open API Byte
/// </summary>
public class OpenApiByte : OpenApiPrimitive<byte>
{
/// <summary>
/// Initializes the <see cref="OpenApiByte"/> class.
/// </summary>
public OpenApiByte(byte value)
: base(value)
{
}
/// <summary>
/// Primitive type this object represents.
/// </summary>
public override PrimitiveType PrimitiveType { get; } = PrimitiveType.Byte;
}
}

View file

@ -1,28 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
namespace Microsoft.OpenApi.Any
{
/// <summary>
/// Open API Date
/// </summary>
public class OpenApiDate : OpenApiPrimitive<DateTime>
{
/// <summary>
/// Initializes the <see cref="OpenApiDate"/> class.
/// </summary>
public OpenApiDate(DateTime value)
: base(value)
{
}
/// <summary>
/// Primitive type this object represents.
/// </summary>
public override PrimitiveType PrimitiveType { get; } = PrimitiveType.Date;
}
}

View file

@ -1,28 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
namespace Microsoft.OpenApi.Any
{
/// <summary>
/// Open API Datetime
/// </summary>
public class OpenApiDateTime : OpenApiPrimitive<DateTimeOffset>
{
/// <summary>
/// Initializes the <see cref="OpenApiDateTime"/> class.
/// </summary>
public OpenApiDateTime(DateTimeOffset value)
: base(value)
{
}
/// <summary>
/// Primitive type this object represents.
/// </summary>
public override PrimitiveType PrimitiveType { get; } = PrimitiveType.DateTime;
}
}

View file

@ -1,26 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.OpenApi.Any
{
/// <summary>
/// Open API Double
/// </summary>
public class OpenApiDouble : OpenApiPrimitive<double>
{
/// <summary>
/// Initializes the <see cref="OpenApiDouble"/> class.
/// </summary>
public OpenApiDouble(double value)
: base(value)
{
}
/// <summary>
/// Primitive type this object represents.
/// </summary>
public override PrimitiveType PrimitiveType { get; } = PrimitiveType.Double;
}
}

View file

@ -1,26 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.OpenApi.Any
{
/// <summary>
/// Open API Float
/// </summary>
public class OpenApiFloat : OpenApiPrimitive<float>
{
/// <summary>
/// Initializes the <see cref="OpenApiFloat"/> class.
/// </summary>
public OpenApiFloat(float value)
: base(value)
{
}
/// <summary>
/// Primitive type this object represents.
/// </summary>
public override PrimitiveType PrimitiveType { get; } = PrimitiveType.Float;
}
}

View file

@ -1,26 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.OpenApi.Any
{
/// <summary>
/// Open API Integer
/// </summary>
public class OpenApiInteger : OpenApiPrimitive<int>
{
/// <summary>
/// Initializes the <see cref="OpenApiInteger"/> class.
/// </summary>
public OpenApiInteger(int value)
: base(value)
{
}
/// <summary>
/// Primitive type this object represents.
/// </summary>
public override PrimitiveType PrimitiveType { get; } = PrimitiveType.Integer;
}
}

View file

@ -1,26 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.OpenApi.Any
{
/// <summary>
/// Open API long.
/// </summary>
public class OpenApiLong : OpenApiPrimitive<long>
{
/// <summary>
/// Primitive type this object represents.
/// </summary>
public override PrimitiveType PrimitiveType { get; } = PrimitiveType.Long;
/// <summary>
/// Initializes the <see cref="OpenApiLong"/> class.
/// </summary>
public OpenApiLong(long value)
: base(value)
{
}
}
}

View file

@ -1,18 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.OpenApi.Any
{
/// <summary>
/// Open API null.
/// </summary>
public class OpenApiNull : IOpenApiAny
{
/// <summary>
/// The type of <see cref="IOpenApiAny"/>
/// </summary>
public AnyType AnyType { get; } = AnyType.Null;
}
}

View file

@ -1,20 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Collections.Generic;
namespace Microsoft.OpenApi.Any
{
/// <summary>
/// Open API object.
/// </summary>
public class OpenApiObject : Dictionary<string, IOpenApiAny>, IOpenApiAny
{
/// <summary>
/// Type of <see cref="IOpenApiAny"/>.
/// </summary>
public AnyType AnyType { get; } = AnyType.Object;
}
}

View file

@ -1,25 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.OpenApi.Any
{
/// <summary>
/// Open API password.
/// </summary>
public class OpenApiPassword : OpenApiPrimitive<string>
{
/// <summary>
/// The primitive type this object represents.
/// </summary>
public override PrimitiveType PrimitiveType { get; } = PrimitiveType.Password;
/// <summary>
/// Initializes the <see cref="OpenApiPassword"/> class.
/// </summary>
public OpenApiPassword(string value)
: base(value)
{ }
}
}

View file

@ -1,38 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.OpenApi.Any
{
/// <summary>
/// Open API primitive class.
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class OpenApiPrimitive<T> : IOpenApiPrimitive
{
/// <summary>
/// The kind of <see cref="IOpenApiAny"/>.
/// </summary>
public AnyType AnyType { get; } = AnyType.Primitive;
/// <summary>
/// The primitive class this object represents.
/// </summary>
public abstract PrimitiveType PrimitiveType { get; }
/// <summary>
/// Value of this <see cref="IOpenApiPrimitive"/>
/// </summary>
public T Value { get; }
/// <summary>
/// Initializes the <see cref="IOpenApiPrimitive"/> class with the given value.
/// </summary>
/// <param name="value"></param>
public OpenApiPrimitive(T value)
{
Value = value;
}
}
}

View file

@ -1,26 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.OpenApi.Any
{
/// <summary>
/// Open API string type.
/// </summary>
public class OpenApiString : OpenApiPrimitive<string>
{
/// <summary>
/// The primitive class this object represents.
/// </summary>
public override PrimitiveType PrimitiveType { get; } = PrimitiveType.String;
/// <summary>
/// Initializes the <see cref="OpenApiString"/> class.
/// </summary>
/// <param name="value"></param>
public OpenApiString(string value)
: base(value)
{ }
}
}

View file

@ -1,35 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
namespace Microsoft.OpenApi.Attributes
{
/// <summary>
/// Represents the Open Api Data type metadata attribute.
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
internal class DisplayAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="DisplayAttribute"/> class.
/// </summary>
/// <param name="name">The display name.</param>
public DisplayAttribute(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
throw Error.ArgumentNullOrWhiteSpace(nameof(name));
}
Name = name;
}
/// <summary>
/// The display Name.
/// </summary>
public string Name { get; }
}
}

View file

@ -1,94 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
using System.Globalization;
using Microsoft.OpenApi.Properties;
namespace Microsoft.OpenApi
{
/// <summary>
/// Utility class for creating and unwrapping <see cref="Exception"/> instances.
/// </summary>
internal static class Error
{
/// <summary>
/// Formats the specified resource string using <see cref="M:CultureInfo.CurrentCulture"/>.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <returns>The formatted string.</returns>
internal static string Format(string format, params object[] args)
{
return String.Format(CultureInfo.CurrentCulture, format, args);
}
/// <summary>
/// Creates an <see cref="ArgumentException"/> with the provided properties.
/// </summary>
/// <param name="messageFormat">A composite format string explaining the reason for the exception.</param>
/// <param name="messageArgs">An object array that contains zero or more objects to format.</param>
/// <returns>The logged <see cref="Exception"/>.</returns>
internal static ArgumentException Argument(string messageFormat, params object[] messageArgs)
{
return new ArgumentException(Format(messageFormat, messageArgs));
}
/// <summary>
/// Creates an <see cref="ArgumentException"/> with the provided properties.
/// </summary>
/// <param name="parameterName">The name of the parameter that caused the current exception.</param>
/// <param name="messageFormat">A composite format string explaining the reason for the exception.</param>
/// <param name="messageArgs">An object array that contains zero or more objects to format.</param>
/// <returns>The logged <see cref="Exception"/>.</returns>
internal static ArgumentException Argument(string parameterName, string messageFormat, params object[] messageArgs)
{
return new ArgumentException(Format(messageFormat, messageArgs), parameterName);
}
/// <summary>
/// Creates an <see cref="ArgumentNullException"/> with the provided properties.
/// </summary>
/// <param name="parameterName">The name of the parameter that caused the current exception.</param>
/// <returns>The logged <see cref="Exception"/>.</returns>
internal static ArgumentNullException ArgumentNull(string parameterName)
{
return new ArgumentNullException(parameterName);
}
/// <summary>
/// Creates an <see cref="ArgumentNullException"/> with the provided properties.
/// </summary>
/// <param name="parameterName">The name of the parameter that caused the current exception.</param>
/// <param name="messageFormat">A composite format string explaining the reason for the exception.</param>
/// <param name="messageArgs">An object array that contains zero or more objects to format.</param>
/// <returns>The logged <see cref="Exception"/>.</returns>
internal static ArgumentNullException ArgumentNull(string parameterName, string messageFormat, params object[] messageArgs)
{
return new ArgumentNullException(parameterName, Format(messageFormat, messageArgs));
}
/// <summary>
/// Creates an <see cref="ArgumentException"/> with a default message.
/// </summary>
/// <param name="parameterName">The name of the parameter that caused the current exception.</param>
/// <returns>The logged <see cref="Exception"/>.</returns>
internal static ArgumentException ArgumentNullOrWhiteSpace(string parameterName)
{
return Error.Argument(parameterName, SRResource.ArgumentNullOrWhiteSpace, parameterName);
}
/// <summary>
/// Creates an <see cref="NotSupportedException"/>.
/// </summary>
/// <param name="messageFormat">A composite format string explaining the reason for the exception.</param>
/// <param name="messageArgs">An object array that contains zero or more objects to format.</param>
/// <returns>The logged <see cref="Exception"/>.</returns>
internal static NotSupportedException NotSupported(string messageFormat, params object[] messageArgs)
{
return new NotSupportedException(Format(messageFormat, messageArgs));
}
}
}

View file

@ -1,48 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
using Microsoft.OpenApi.Properties;
namespace Microsoft.OpenApi.Exceptions
{
/// <summary>
/// Exception type representing exceptions in the Open API library.
/// </summary>
public class OpenApiException : Exception
{
/// <summary>
/// The reference pointer.
/// </summary>
public string Pointer { get; set; }
/// <summary>
/// Creates a new instance of the <see cref="OpenApiException" /> class with default values.
/// </summary>
public OpenApiException()
: this(SRResource.OpenApiExceptionGenericError)
{
}
/// <summary>
/// Creates a new instance of the <see cref="OpenApiException" /> class with an error message.
/// </summary>
/// <param name="message">The plain text error message for this exception.</param>
public OpenApiException(string message)
: this(message, null)
{
}
/// <summary>
/// Creates a new instance of the <see cref="OpenApiException" /> class with an error message and an inner exception.
/// </summary>
/// <param name="message">The plain text error message for this exception.</param>
/// <param name="innerException">The inner exception that is the cause of this exception to be thrown.</param>
public OpenApiException(string message, Exception innerException)
: base(message, innerException)
{
}
}
}

View file

@ -1,43 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
using Microsoft.OpenApi.Properties;
namespace Microsoft.OpenApi.Exceptions
{
/// <summary>
/// Exception type representing exceptions in the OpenAPI writer.
/// </summary>
public class OpenApiWriterException : OpenApiException
{
/// <summary>
/// Creates a new instance of the <see cref="OpenApiWriterException" /> class with default values.
/// </summary>
public OpenApiWriterException()
: this(SRResource.OpenApiWriterExceptionGenericError)
{
}
/// <summary>
/// Creates a new instance of the <see cref="OpenApiWriterException" /> class with an error message.
/// </summary>
/// <param name="message">The plain text error message for this exception.</param>
public OpenApiWriterException(string message)
: this(message, null)
{
}
/// <summary>
/// Creates a new instance of the <see cref="OpenApiWriterException" /> class with an error message and an inner exception.
/// </summary>
/// <param name="message">The plain text error message for this exception.</param>
/// <param name="innerException">The inner exception that is the cause of this exception to be thrown.</param>
public OpenApiWriterException(string message, Exception innerException)
: base(message, innerException)
{
}
}
}

View file

@ -1,62 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
namespace Microsoft.OpenApi.Expressions
{
/// <summary>
/// Body expression.
/// </summary>
public sealed class BodyExpression : SourceExpression
{
/// <summary>
/// body string
/// </summary>
public const string Body = "body";
/// <summary>
/// Prefix for a pointer
/// </summary>
public const string PointerPrefix = "#";
/// <summary>
/// Gets the expression string.
/// </summary>
public override string Expression
{
get
{
if (String.IsNullOrEmpty(Value))
{
return Body;
}
return Body + PointerPrefix + Value;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="BodyExpression"/> class.
/// </summary>
public BodyExpression()
: base(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BodyExpression"/> class.
/// </summary>
/// <param name="pointer">a JSON Pointer [RFC 6901](https://tools.ietf.org/html/rfc6901).</param>
public BodyExpression(JsonPointer pointer)
: base(pointer?.ToString())
{
if (pointer == null)
{
throw Error.ArgumentNull(nameof(pointer));
}
}
}
}

View file

@ -1,42 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.OpenApi.Expressions
{
/// <summary>
/// Header expression, The token identifier in header is case-insensitive.
/// </summary>
public class HeaderExpression : SourceExpression
{
/// <summary>
/// header. string
/// </summary>
public const string Header = "header.";
/// <summary>
/// Gets the expression string.
/// </summary>
public override string Expression
{
get
{
return Header + Value;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="HeaderExpression"/> class.
/// </summary>
/// <param name="token">The token string, it's case-insensitive.</param>
public HeaderExpression(string token)
: base(token)
{
if (string.IsNullOrWhiteSpace(token))
{
throw Error.ArgumentNullOrWhiteSpace(nameof(token));
}
}
}
}

View file

@ -1,23 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.OpenApi.Expressions
{
/// <summary>
/// Method expression.
/// </summary>
public sealed class MethodExpression : RuntimeExpression
{
/// <summary>
/// $method. string
/// </summary>
public const string Method = "$method";
/// <summary>
/// Gets the expression string.
/// </summary>
public override string Expression { get; } = Method;
}
}

View file

@ -1,42 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.OpenApi.Expressions
{
/// <summary>
/// Path expression, the name in path is case-sensitive.
/// </summary>
public sealed class PathExpression : SourceExpression
{
/// <summary>
/// path. string
/// </summary>
public const string Path = "path.";
/// <summary>
/// Gets the expression string.
/// </summary>
public override string Expression
{
get
{
return Path + Value;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="PathExpression"/> class.
/// </summary>
/// <param name="name">The name string, it's case-insensitive.</param>
public PathExpression(string name)
: base(name)
{
if (string.IsNullOrWhiteSpace(name))
{
throw Error.ArgumentNullOrWhiteSpace(nameof(name));
}
}
}
}

View file

@ -1,42 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.OpenApi.Expressions
{
/// <summary>
/// Query expression, the name in query is case-sensitive.
/// </summary>
public sealed class QueryExpression : SourceExpression
{
/// <summary>
/// query. string
/// </summary>
public const string Query = "query.";
/// <summary>
/// Gets the expression string.
/// </summary>
public override string Expression
{
get
{
return Query + Value;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="QueryExpression"/> class.
/// </summary>
/// <param name="name">The name string, it's case-insensitive.</param>
public QueryExpression(string name)
: base(name)
{
if (string.IsNullOrWhiteSpace(name))
{
throw Error.ArgumentNullOrWhiteSpace(nameof(name));
}
}
}
}

View file

@ -1,37 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.OpenApi.Expressions
{
/// <summary>
/// $request. expression.
/// </summary>
public sealed class RequestExpression : RuntimeExpression
{
/// <summary>
/// $request. string
/// </summary>
public const string Request = "$request.";
/// <summary>
/// Gets the expression string.
/// </summary>
public override string Expression => Request + Source.Expression;
/// <summary>
/// The <see cref="SourceExpression"/> expression.
/// </summary>
public SourceExpression Source { get; }
/// <summary>
/// Initializes a new instance of the <see cref="RequestExpression"/> class.
/// </summary>
/// <param name="source">The source of the request.</param>
public RequestExpression(SourceExpression source)
{
Source = source ?? throw Error.ArgumentNull(nameof(source));
}
}
}

View file

@ -1,37 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.OpenApi.Expressions
{
/// <summary>
/// $response. expression.
/// </summary>
public sealed class ResponseExpression : RuntimeExpression
{
/// <summary>
/// $response. string
/// </summary>
public const string Response = "$response.";
/// <summary>
/// Gets the expression string.
/// </summary>
public override string Expression => Response + Source.Expression;
/// <summary>
/// The <see cref="SourceExpression"/> expression.
/// </summary>
public SourceExpression Source { get; }
/// <summary>
/// Initializes a new instance of the <see cref="ResponseExpression"/> class.
/// </summary>
/// <param name="source">The source of the response.</param>
public ResponseExpression(SourceExpression source)
{
Source = source ?? throw Error.ArgumentNull(nameof(source));
}
}
}

View file

@ -1,81 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
using Microsoft.OpenApi.Exceptions;
using Microsoft.OpenApi.Properties;
namespace Microsoft.OpenApi.Expressions
{
/// <summary>
/// Base class for the Open API runtime expression.
/// </summary>
public abstract class RuntimeExpression
{
/// <summary>
/// The dollar sign prefix for a runtime expression.
/// </summary>
public const string Prefix = "$";
/// <summary>
/// The expression string.
/// </summary>
public abstract string Expression { get; }
/// <summary>
/// Build the runtime expression from input string.
/// </summary>
/// <param name="expression">The runtime expression.</param>
/// <returns>The built runtime expression object.</returns>
public static RuntimeExpression Build(string expression)
{
if (String.IsNullOrWhiteSpace(expression))
{
throw Error.ArgumentNullOrWhiteSpace(nameof(expression));
}
if (!expression.StartsWith(Prefix))
{
throw new OpenApiException(String.Format(SRResource.RuntimeExpressionMustBeginWithDollar, expression));
}
// $url
if (expression == UrlExpression.Url)
{
return new UrlExpression();
}
// $method
if (expression == MethodExpression.Method)
{
return new MethodExpression();
}
// $statusCode
if (expression == StatusCodeExpression.StatusCode)
{
return new StatusCodeExpression();
}
// $request.
if (expression.StartsWith(RequestExpression.Request))
{
string subString = expression.Substring(RequestExpression.Request.Length);
SourceExpression source = SourceExpression.Build(subString);
return new RequestExpression(source);
}
// $response.
if (expression.StartsWith(ResponseExpression.Response))
{
string subString = expression.Substring(ResponseExpression.Response.Length);
SourceExpression source = SourceExpression.Build(subString);
return new ResponseExpression(source);
}
throw new OpenApiException(String.Format(SRResource.RuntimeExpressionHasInvalidFormat, expression));
}
}
}

View file

@ -1,78 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
using Microsoft.OpenApi.Exceptions;
using Microsoft.OpenApi.Properties;
namespace Microsoft.OpenApi.Expressions
{
/// <summary>
/// Source expression.
/// </summary>
public abstract class SourceExpression : RuntimeExpression
{
/// <summary>
/// Gets the expression string.
/// </summary>
protected string Value { get; }
/// <summary>
/// Initializes a new instance of the <see cref="QueryExpression"/> class.
/// </summary>
/// <param name="value">The value string.</param>
protected SourceExpression(string value)
{
Value = value;
}
/// <summary>
/// Build the source expression from input string.
/// </summary>
/// <param name="expression">The source expression.</param>
/// <returns>The built source expression.</returns>
public new static SourceExpression Build(string expression)
{
if (!String.IsNullOrWhiteSpace(expression))
{
var expressions = expression.Split('.');
if (expressions.Length == 2)
{
if (expression.StartsWith(HeaderExpression.Header))
{
// header.
return new HeaderExpression(expressions[1]);
}
else if (expression.StartsWith(QueryExpression.Query))
{
// query.
return new QueryExpression(expressions[1]);
}
else if (expression.StartsWith(PathExpression.Path))
{
// path.
return new PathExpression(expressions[1]);
}
}
// body
if (expression.StartsWith(BodyExpression.Body))
{
string subString = expression.Substring(BodyExpression.Body.Length);
if (String.IsNullOrEmpty(subString))
{
return new BodyExpression();
}
else
{
return new BodyExpression(new JsonPointer(subString));
}
}
}
throw new OpenApiException(String.Format(SRResource.SourceExpressionHasInvalidFormat, expression));
}
}
}

View file

@ -1,23 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.OpenApi.Expressions
{
/// <summary>
/// StatusCode expression.
/// </summary>
public sealed class StatusCodeExpression : RuntimeExpression
{
/// <summary>
/// $statusCode string.
/// </summary>
public const string StatusCode = "$statusCode";
/// <summary>
/// Gets the expression string.
/// </summary>
public override string Expression { get; } = StatusCode;
}
}

View file

@ -1,23 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.OpenApi.Expressions
{
/// <summary>
/// Url expression.
/// </summary>
public sealed class UrlExpression : RuntimeExpression
{
/// <summary>
/// $url string.
/// </summary>
public const string Url = "$url";
/// <summary>
/// Gets the expression string.
/// </summary>
public override string Expression { get; } = Url;
}
}

View file

@ -1,48 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
using System.Linq;
using System.Reflection;
using Microsoft.OpenApi.Attributes;
namespace Microsoft.OpenApi.Extensions
{
/// <summary>
/// Enumeration type extension methods.
/// </summary>
public static class EnumExtensions
{
/// <summary>
/// Gets an attribute on an enum field value.
/// </summary>
/// <typeparam name="T">The type of the attribute to retrieve.</typeparam>
/// <param name="enumValue">The enum value.</param>
/// <returns>
/// The attribute of the specified type or null.
/// </returns>
public static T GetAttributeOfType<T>(this Enum enumValue) where T : Attribute
{
var type = enumValue.GetType();
var memInfo = type.GetMember(enumValue.ToString()).First();
var attributes = memInfo.GetCustomAttributes<T>(false);
return attributes.FirstOrDefault();
}
/// <summary>
/// Gets the enum display name.
/// </summary>
/// <param name="enumValue">The enum value.</param>
/// <returns>
/// Use <see cref="DisplayAttribute"/> if exists.
/// Otherwise, use the standard string representation.
/// </returns>
public static string GetDisplayName(this Enum enumValue)
{
var attribute = enumValue.GetAttributeOfType<DisplayAttribute>();
return attribute == null ? enumValue.ToString() : attribute.Name;
}
}
}

View file

@ -1,252 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
using System.Collections.Generic;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Exceptions;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Models;
using Microsoft.OpenApi.Properties;
namespace Microsoft.OpenApi.Extensions
{
/// <summary>
/// Extension methods to construct or modify Open API elements.
/// </summary>
public static class OpenApiElementExtensions
{
/// <summary>
/// Add a <see cref="OpenApiPathItem"/> into the <see cref="OpenApiDocument"/>.
/// </summary>
/// <param name="document">The Open API document.</param>
/// <param name="name">The path item name.</param>
/// <param name="configure">The path item configuration action.</param>
public static void AddPathItem(this OpenApiDocument document, string name, Action<OpenApiPathItem> configure)
{
if (document == null)
{
throw Error.ArgumentNull(nameof(document));
}
if (string.IsNullOrWhiteSpace(name))
{
throw Error.ArgumentNullOrWhiteSpace(nameof(name));
}
if (configure == null)
{
throw Error.ArgumentNull(nameof(configure));
}
var pathItem = new OpenApiPathItem();
configure(pathItem);
if (document.Paths == null)
{
document.Paths = new OpenApiPaths();
}
document.Paths.Add(name, pathItem);
}
/// <summary>
/// Add a <see cref="OpenApiOperation"/> into the <see cref="OpenApiPathItem"/>.
/// </summary>
/// <param name="pathItem">The Open API path item.</param>
/// <param name="operationType">The operation type kind.</param>
/// <param name="configure">The operation configuration action.</param>
public static void AddOperation(
this OpenApiPathItem pathItem,
OperationType operationType,
Action<OpenApiOperation> configure)
{
if (pathItem == null)
{
throw Error.ArgumentNull(nameof(pathItem));
}
if (configure == null)
{
throw Error.ArgumentNull(nameof(configure));
}
var operation = new OpenApiOperation();
configure(operation);
pathItem.AddOperation(operationType, operation);
}
/// <summary>
/// Add a <see cref="OpenApiHeader"/> into the response.
/// </summary>
/// <param name="response">The response.</param>
/// <param name="name">The header name.</param>
/// <param name="configure">The header configure action.</param>
public static void AddHeader(this OpenApiResponse response, string name, Action<OpenApiHeader> configure)
{
if (response == null)
{
throw Error.ArgumentNull(nameof(response));
}
if (string.IsNullOrWhiteSpace(name))
{
throw Error.ArgumentNullOrWhiteSpace(nameof(name));
}
if (configure == null)
{
throw Error.ArgumentNull(nameof(configure));
}
var header = new OpenApiHeader();
configure(header);
if (response.Headers == null)
{
response.Headers = new Dictionary<string, OpenApiHeader>();
}
response.Headers.Add(name, header);
}
/// <summary>
/// Add a <see cref="OpenApiMediaType"/> into the response.
/// </summary>
/// <param name="response">The response.</param>
/// <param name="name">The content name.</param>
/// <param name="configure">The content configure action.</param>
public static void AddMediaType(this OpenApiResponse response, string name, Action<OpenApiMediaType> configure)
{
if (response == null)
{
throw Error.ArgumentNull(nameof(response));
}
if (string.IsNullOrWhiteSpace(name))
{
throw Error.ArgumentNullOrWhiteSpace(nameof(name));
}
if (configure == null)
{
throw Error.ArgumentNull(nameof(configure));
}
var mediaType = new OpenApiMediaType();
configure(mediaType);
if (response.Content == null)
{
response.Content = new Dictionary<string, OpenApiMediaType>();
}
response.Content.Add(name, mediaType);
}
/// <summary>
/// Add a <see cref="OpenApiLink"/> into the response.
/// </summary>
/// <param name="response">The response.</param>
/// <param name="name">The link name.</param>
/// <param name="configure">The link configure action.</param>
public static void AddLink(this OpenApiResponse response, string name, Action<OpenApiLink> configure)
{
if (response == null)
{
throw Error.ArgumentNull(nameof(response));
}
if (string.IsNullOrWhiteSpace(name))
{
throw Error.ArgumentNullOrWhiteSpace(nameof(name));
}
if (configure == null)
{
throw Error.ArgumentNull(nameof(configure));
}
var link = new OpenApiLink();
configure(link);
if (response.Links == null)
{
response.Links = new Dictionary<string, OpenApiLink>();
}
response.Links.Add(name, link);
}
/// <summary>
/// Add a <see cref="OpenApiResponse"/> into the <see cref="OpenApiOperation"/>.
/// </summary>
/// <param name="operation">The Open API operation.</param>
/// <param name="name">The response name.</param>
/// <param name="configure">The response configuration action.</param>
public static void AddResponse(this OpenApiOperation operation, string name, Action<OpenApiResponse> configure)
{
if (operation == null)
{
throw Error.ArgumentNull(nameof(operation));
}
if (string.IsNullOrWhiteSpace(name))
{
throw Error.ArgumentNullOrWhiteSpace(nameof(name));
}
if (configure == null)
{
throw Error.ArgumentNull(nameof(configure));
}
var response = new OpenApiResponse();
configure(response);
if (operation.Responses == null)
{
operation.Responses = new OpenApiResponses();
}
operation.Responses.Add(name, response);
}
/// <summary>
/// Add extension into the Extensions
/// </summary>
/// <typeparam name="T"><see cref="IOpenApiExtensible"/>.</typeparam>
/// <param name="element">The extensible Open API element. </param>
/// <param name="name">The extension name.</param>
/// <param name="any">The extension value.</param>
public static void AddExtension<T>(this T element, string name, IOpenApiAny any)
where T : IOpenApiExtensible
{
if (element == null)
{
throw Error.ArgumentNull(nameof(element));
}
if (string.IsNullOrWhiteSpace(name))
{
throw Error.ArgumentNullOrWhiteSpace(nameof(name));
}
if (!name.StartsWith(OpenApiConstants.ExtensionFieldNamePrefix))
{
throw new OpenApiException(string.Format(SRResource.ExtensionFieldNameMustBeginWithXDash, name));
}
if (element.Extensions == null)
{
element.Extensions = new Dictionary<string, IOpenApiAny>();
}
element.Extensions[name] = any ?? throw Error.ArgumentNull(nameof(any));
}
}
}

View file

@ -1,177 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.IO;
using Microsoft.OpenApi.Exceptions;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Properties;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Extensions
{
/// <summary>
/// Extension methods for <see cref="IOpenApiSerializable"/> serialization.
/// </summary>
public static class OpenApiSerializableExtensions
{
/// <summary>
/// Serialize the <see cref="IOpenApiSerializable"/> to the Open API document (JSON) using the given stream and specification version.
/// </summary>
/// <typeparam name="T">the <see cref="IOpenApiSerializable"/></typeparam>
/// <param name="element">The Open API element.</param>
/// <param name="stream">The output stream.</param>
/// <param name="specVersion">The Open API specification version.</param>
public static void SerializeAsJson<T>(this T element, Stream stream, OpenApiSpecVersion specVersion)
where T : IOpenApiSerializable
{
element.Serialize(stream, specVersion, OpenApiFormat.Json);
}
/// <summary>
/// Serializes the <see cref="IOpenApiSerializable"/> to the Open API document (YAML) using the given stream and specification version.
/// </summary>
/// <typeparam name="T">the <see cref="IOpenApiSerializable"/></typeparam>
/// <param name="element">The Open API element.</param>
/// <param name="stream">The output stream.</param>
/// <param name="specVersion">The Open API specification version.</param>
public static void SerializeAsYaml<T>(this T element, Stream stream, OpenApiSpecVersion specVersion)
where T : IOpenApiSerializable
{
element.Serialize(stream, specVersion, OpenApiFormat.Yaml);
}
/// <summary>
/// Serializes the <see cref="IOpenApiSerializable"/> to the Open API document using
/// the given stream, specification version and the format.
/// </summary>
/// <typeparam name="T">the <see cref="IOpenApiSerializable"/></typeparam>
/// <param name="element">The Open API element.</param>
/// <param name="stream">The given stream.</param>
/// <param name="specVersion">The Open API specification version.</param>
/// <param name="format">The output format (JSON or YAML).</param>
public static void Serialize<T>(
this T element,
Stream stream,
OpenApiSpecVersion specVersion,
OpenApiFormat format)
where T : IOpenApiSerializable
{
if (stream == null)
{
throw Error.ArgumentNull(nameof(stream));
}
IOpenApiWriter writer;
switch (format)
{
case OpenApiFormat.Json:
writer = new OpenApiJsonWriter(new StreamWriter(stream));
break;
case OpenApiFormat.Yaml:
writer = new OpenApiYamlWriter(new StreamWriter(stream));
break;
default:
throw new OpenApiException(string.Format(SRResource.OpenApiFormatNotSupported, format));
}
element.Serialize(writer, specVersion);
}
/// <summary>
/// Serializes the <see cref="IOpenApiSerializable"/> to Open API document using the given specification version and writer.
/// </summary>
/// <typeparam name="T">the <see cref="IOpenApiSerializable"/></typeparam>
/// <param name="element">The Open API element.</param>
/// <param name="writer">The output writer.</param>
/// <param name="specVersion">The Open API specification version.</param>
public static void Serialize<T>(this T element, IOpenApiWriter writer, OpenApiSpecVersion specVersion)
where T : IOpenApiSerializable
{
if (element == null)
{
throw Error.ArgumentNull(nameof(element));
}
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
switch (specVersion)
{
case OpenApiSpecVersion.OpenApi3_0:
element.SerializeAsV3(writer);
break;
case OpenApiSpecVersion.OpenApi2_0:
element.SerializeAsV2(writer);
break;
default:
throw new OpenApiException(string.Format(SRResource.OpenApiSpecVersionNotSupported, specVersion));
}
writer.Flush();
}
/// <summary>
/// Serializes the <see cref="IOpenApiSerializable"/> to the Open API document as a string in JSON format.
/// </summary>
/// <typeparam name="T">the <see cref="IOpenApiSerializable"/></typeparam>
/// <param name="element">The Open API element.</param>
/// <param name="specVersion">The Open API specification version.</param>
public static string SerializeAsJson<T>(
this T element,
OpenApiSpecVersion specVersion)
where T : IOpenApiSerializable
{
return element.Serialize(specVersion, OpenApiFormat.Json);
}
/// <summary>
/// Serializes the <see cref="IOpenApiSerializable"/> to the Open API document as a string in YAML format.
/// </summary>
/// <typeparam name="T">the <see cref="IOpenApiSerializable"/></typeparam>
/// <param name="element">The Open API element.</param>
/// <param name="specVersion">The Open API specification version.</param>
public static string SerializeAsYaml<T>(
this T element,
OpenApiSpecVersion specVersion)
where T : IOpenApiSerializable
{
return element.Serialize(specVersion, OpenApiFormat.Yaml);
}
/// <summary>
/// Serializes the <see cref="IOpenApiSerializable"/> to the Open API document as a string in the given format.
/// </summary>
/// <typeparam name="T">the <see cref="IOpenApiSerializable"/></typeparam>
/// <param name="element">The Open API element.</param>
/// <param name="specVersion">The Open API specification version.</param>
/// <param name="format">Open API document format.</param>
public static string Serialize<T>(
this T element,
OpenApiSpecVersion specVersion,
OpenApiFormat format)
where T : IOpenApiSerializable
{
if (element == null)
{
throw Error.ArgumentNull(nameof(element));
}
using (var stream = new MemoryStream())
{
element.Serialize(stream, specVersion, format);
stream.Position = 0;
using (var streamReader = new StreamReader(stream))
{
return streamReader.ReadToEnd();
}
}
}
}
}

View file

@ -1,43 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
using System.Reflection;
using Microsoft.OpenApi.Attributes;
namespace Microsoft.OpenApi.Extensions
{
/// <summary>
/// String extension methods.
/// </summary>
public static class StringExtensions
{
/// <summary>
/// Gets the enum value based on the given enum type and display name.
/// </summary>
/// <param name="displayName">The display name.</param>
public static T GetEnumFromDisplayName<T>(this string displayName)
{
var type = typeof(T);
if (!type.IsEnum)
{
return default(T);
}
foreach (var value in Enum.GetValues(type))
{
var field = type.GetField(value.ToString());
var displayAttribute = (DisplayAttribute)field.GetCustomAttribute(typeof(DisplayAttribute));
if (displayAttribute != null && displayAttribute.Name == displayName)
{
return (T)value;
}
}
return default(T);
}
}
}

View file

@ -1,14 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.OpenApi.Interfaces
{
/// <summary>
/// Represents an Open API element.
/// </summary>
public interface IOpenApiElement
{
}
}

View file

@ -1,21 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Collections.Generic;
using Microsoft.OpenApi.Any;
namespace Microsoft.OpenApi.Interfaces
{
/// <summary>
/// Represents an Extensible Open API element.
/// </summary>
public interface IOpenApiExtensible : IOpenApiElement
{
/// <summary>
/// Specification extensions.
/// </summary>
IDictionary<string, IOpenApiAny> Extensions { get; set; }
}
}

View file

@ -1,20 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using Microsoft.OpenApi.Models;
namespace Microsoft.OpenApi.Interfaces
{
/// <summary>
/// Represents an Open API element is referenceable.
/// </summary>
public interface IOpenApiReferenceable : IOpenApiElement
{
/// <summary>
/// Reference object.
/// </summary>
OpenApiReference Reference { get; set; }
}
}

View file

@ -1,27 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Interfaces
{
/// <summary>
/// Represents an Open API element that comes with serialzation functionality.
/// </summary>
public interface IOpenApiSerializable : IOpenApiElement
{
/// <summary>
/// Serialize Open API element to v3.0.
/// </summary>
/// <param name="writer">The writer.</param>
void SerializeAsV3(IOpenApiWriter writer);
/// <summary>
/// Serialize Open API element to v2.0.
/// </summary>
/// <param name="writer">The writer.</param>
void SerializeAsV2(IOpenApiWriter writer);
}
}

View file

@ -1,69 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
using System.Linq;
namespace Microsoft.OpenApi
{
/// <summary>
/// JSON pointer.
/// </summary>
public class JsonPointer
{
private readonly string[] _Tokens;
/// <summary>
/// Tokens.
/// </summary>
public string[] Tokens { get { return _Tokens; } }
/// <summary>
/// Initializes the <see cref="JsonPointer"/> class.
/// </summary>
/// <param name="pointer">Pointer as string.</param>
public JsonPointer(string pointer)
{
_Tokens = pointer.Split('/').Skip(1).Select(Decode).ToArray();
}
/// <summary>
/// Initializes the <see cref="JsonPointer"/> class.
/// </summary>
/// <param name="tokens">Pointer as tokenized string.</param>
private JsonPointer(string[] tokens)
{
_Tokens = tokens;
}
/// <summary>
/// Decode the string.
/// </summary>
private string Decode(string token)
{
return Uri.UnescapeDataString(token).Replace("~1", "/").Replace("~0", "~");
}
/// <summary>
/// Gets the parent pointer.
/// </summary>
public JsonPointer ParentPointer
{
get
{
if (_Tokens.Length == 0) return null;
return new JsonPointer(_Tokens.Take(_Tokens.Length - 1).ToArray());
}
}
/// <summary>
/// Gets the string representation of this JSON pointer.
/// </summary>
public override string ToString()
{
return "/" + String.Join("/", _Tokens);
}
}
}

View file

@ -1,34 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46; netstandard2.0</TargetFrameworks>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Authors></Authors>
<Company>Microsoft</Company>
<Product>Microsoft.OpenApi</Product>
<PackageId>Microsoft.OpenApi</PackageId>
<Version>1.0.0-beta003</Version>
<Description>.NET models and JSON/YAML writers for OpenAPI specification</Description>
<AssemblyName>Microsoft.OpenApi</AssemblyName>
<RootNamespace>Microsoft.OpenApi</RootNamespace>
<SignAssembly>true</SignAssembly>
</PropertyGroup>
<PropertyGroup>
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\Microsoft.OpenApi.xml</DocumentationFile>
</PropertyGroup>
<ItemGroup>
<Compile Update="Properties\SRResource.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SRResource.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\SRResource.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>SRResource.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
</Project>

View file

@ -1,98 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Collections.Generic;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Expressions;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// Callback Object: A map of possible out-of band callbacks related to the parent operation.
/// </summary>
public class OpenApiCallback : IOpenApiSerializable, IOpenApiReferenceable, IOpenApiExtensible
{
/// <summary>
/// A Path Item Object used to define a callback request and expected responses.
/// </summary>
public Dictionary<RuntimeExpression, OpenApiPathItem> PathItems { get; set; }
/// <summary>
/// Reference pointer.
/// </summary>
public OpenApiReference Reference { get; set; }
/// <summary>
/// This object MAY be extended with Specification Extensions.
/// </summary>
public IDictionary<string, IOpenApiAny> Extensions { get; set; }
/// <summary>
/// Add a <see cref="OpenApiPathItem"/> into the <see cref="PathItems"/>.
/// </summary>
/// <param name="expression">The runtime expression.</param>
/// <param name="pathItem">The path item.</param>
public void AddPathItem(RuntimeExpression expression, OpenApiPathItem pathItem)
{
if (expression == null)
{
throw Error.ArgumentNull(nameof(expression));
}
if (pathItem == null)
{
throw Error.ArgumentNull(nameof(pathItem));
}
if (PathItems == null)
{
PathItems = new Dictionary<RuntimeExpression, OpenApiPathItem>();
}
PathItems.Add(expression, pathItem);
}
/// <summary>
/// Serialize <see cref="OpenApiCallback"/> to Open Api v3.0
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
if (Reference != null)
{
Reference.SerializeAsV3(writer);
}
else
{
writer.WriteStartObject();
// path items
foreach (var item in PathItems)
{
writer.WriteRequiredObject(item.Key.Expression, item.Value, (w, p) => p.SerializeAsV3(w));
}
// extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
}
/// <summary>
/// Serialize <see cref="OpenApiCallback"/> to Open Api v2.0
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
// Callback object does not exist in V2.
}
}
}

View file

@ -1,121 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Collections.Generic;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// Components Object.
/// </summary>
public class OpenApiComponents : IOpenApiSerializable, IOpenApiExtensible
{
/// <summary>
/// An object to hold reusable <see cref="OpenApiSchema"/> Objects.
/// </summary>
public IDictionary<string, OpenApiSchema> Schemas { get; set; }
/// <summary>
/// An object to hold reusable <see cref="OpenApiResponse"/> Objects.
/// </summary>
public IDictionary<string, OpenApiResponse> Responses { get; set; }
/// <summary>
/// An object to hold reusable <see cref="OpenApiParameter"/> Objects.
/// </summary>
public IDictionary<string, OpenApiParameter> Parameters { get; set; }
/// <summary>
/// An object to hold reusable <see cref="OpenApiExample"/> Objects.
/// </summary>
public IDictionary<string, OpenApiExample> Examples { get; set; }
/// <summary>
/// An object to hold reusable <see cref="OpenApiRequestBody"/> Objects.
/// </summary>
public IDictionary<string, OpenApiRequestBody> RequestBodies { get; set; }
/// <summary>
/// An object to hold reusable <see cref="OpenApiHeader"/> Objects.
/// </summary>
public IDictionary<string, OpenApiHeader> Headers { get; set; }
/// <summary>
/// An object to hold reusable <see cref="OpenApiSecurityScheme"/> Objects.
/// </summary>
public IDictionary<string, OpenApiSecurityScheme> SecuritySchemes { get; set; }
/// <summary>
/// An object to hold reusable <see cref="OpenApiLink"/> Objects.
/// </summary>
public IDictionary<string, OpenApiLink> Links { get; set; }
/// <summary>
/// An object to hold reusable <see cref="OpenApiCallback"/> Objects.
/// </summary>
public IDictionary<string, OpenApiCallback> Callbacks { get; set; }
/// <summary>
/// This object MAY be extended with Specification Extensions.
/// </summary>
public IDictionary<string, IOpenApiAny> Extensions { get; set; }
/// <summary>
/// Serialize <see cref="OpenApiComponents"/> to Open Api v3.0.
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
writer.WriteStartObject();
// schemas
writer.WriteOptionalMap(OpenApiConstants.Schemas, Schemas, (w, s) => s.SerializeAsV3(w));
// responses
writer.WriteOptionalMap(OpenApiConstants.Responses, Responses, (w, r) => r.SerializeAsV3(w));
// parameters
writer.WriteOptionalMap(OpenApiConstants.Parameters, Parameters, (w, p) => p.SerializeAsV3(w));
// examples
writer.WriteOptionalMap(OpenApiConstants.Examples, Examples, (w, e) => e.SerializeAsV3(w));
// requestBodies
writer.WriteOptionalMap(OpenApiConstants.RequestBodies, RequestBodies, (w, r) => r.WriteAsV3(w));
// headers
writer.WriteOptionalMap(OpenApiConstants.Headers, Headers, (w, h) => h.SerializeAsV3(w));
// securitySchemes
writer.WriteOptionalMap(OpenApiConstants.SecuritySchemes, SecuritySchemes, (w, s) => s.SerializeAsV3(w));
// links
writer.WriteOptionalMap(OpenApiConstants.Links, Links, (w, link) => link.SerializeAsV3(w));
// callbacks
writer.WriteOptionalMap(OpenApiConstants.Callbacks, Callbacks, (w, c) => c.SerializeAsV3(w));
// extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
/// <summary>
/// Serialize <see cref="OpenApiComponents"/> to Open Api v2.0.
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
// Components object does not exist in V2.
}
}
}

View file

@ -1,259 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
namespace Microsoft.OpenApi.Models
{
internal static class OpenApiConstants
{
public const string OpenApi = "openapi";
public const string Info = "info";
public const string Title = "title";
public const string Type = "type";
public const string Format = "format";
public const string Version = "version";
public const string Contact = "contact";
public const string License = "license";
public const string TermsOfService = "termsOfService";
public const string Servers = "servers";
public const string Server = "server";
public const string Paths = "paths";
public const string Components = "components";
public const string Security = "security";
public const string Tags = "tags";
public const string ExternalDocs = "externalDocs";
public const string OperationRef = "operationRef";
public const string OperationId = "operationId";
public const string Parameters = "parameters";
public const string RequestBody = "requestBody";
public const string ExtensionFieldNamePrefix = "x-";
public const string Name = "name";
public const string Namespace = "namespace";
public const string Prefix = "prefix";
public const string Attribute = "attribute";
public const string Wrapped = "wrapped";
public const string In = "in";
public const string Summary = "summary";
public const string Variables = "variables";
public const string Description = "description";
public const string Required = "required";
public const string Deprecated = "deprecated";
public const string Style = "style";
public const string Explode = "explode";
public const string AllowReserved = "allowReserved";
public const string Schema = "schema";
public const string Schemas = "schemas";
public const string Responses = "responses";
public const string Example = "example";
public const string Examples = "examples";
public const string Encoding = "encoding";
public const string RequestBodies = "requestBodies";
public const string AllowEmptyValue = "allowEmptyValue";
public const string Value = "value";
public const string ExternalValue = "externalValue";
public const string DollarRef = "$ref";
public const string Headers = "headers";
public const string SecuritySchemes = "securitySchemes";
public const string Content = "content";
public const string Links = "links";
public const string Callbacks = "callbacks";
public const string Url = "url";
public const string Email = "email";
public const string Default = "default";
public const string Enum = "enum";
public const string MultipleOf = "multipleOf";
public const string Maximum = "maximum";
public const string ExclusiveMaximum = "exclusiveMaximum";
public const string Minimum = "minimum";
public const string ExclusiveMinimum = "exclusiveMinimum";
public const string MaxLength = "maxLength";
public const string MinLength = "minLength";
public const string Pattern = "pattern";
public const string MaxItems = "maxItems";
public const string MinItems = "minItems";
public const string UniqueItems = "uniqueItems";
public const string MaxProperties = "maxProperties";
public const string MinProperties = "minProperties";
public const string AllOf = "allOf";
public const string OneOf = "oneOf";
public const string AnyOf = "anyOf";
public const string Not = "not";
public const string Items = "items";
public const string Properties = "properties";
public const string AdditionalProperties = "additionalProperties";
public const string Nullable = "nullable";
public const string Discriminator = "discriminator";
public const string ReadOnly = "readOnly";
public const string WriteOnly = "writeOnly";
public const string Xml = "xml";
public const string Flow = "flow";
public const string Application = "application";
public const string AccessCode = "accessCode";
public const string Implicit = "implicit";
public const string Password = "password";
public const string ClientCredentials = "clientCredentials";
public const string AuthorizationCode = "authorizationCode";
public const string AuthorizationUrl = "authorizationUrl";
public const string TokenUrl = "tokenUrl";
public const string RefreshUrl = "refreshUrl";
public const string Scopes = "scopes";
public const string ContentType = "contentType";
public const string Get = "get";
public const string Put = "put";
public const string Post = "post";
public const string Delete = "delete";
public const string Options = "options";
public const string Head = "head";
public const string Patch = "patch";
public const string Trace = "trace";
public const string PropertyName = "propertyName";
public const string Mapping = "mapping";
public const string Scheme = "scheme";
public const string BearerFormat = "bearerFormat";
public const string Flows = "flows";
public const string OpenIdConnectUrl = "openIdConnectUrl";
public const string DefaultName = "Default Name";
public const string DefaultDefault = "Default Default";
public const string DefaultTitle = "Default Title";
public static readonly Version DefaultVersion = new Version(3, 0, 0);
public static readonly Uri DefaultUrl = new Uri("http://localhost/");
public const string DefaultDescription = "Default Description";
#region V2
public const string Host = "host";
public const string Swagger = "swagger";
public static readonly Version SwaggerVersion = new Version(2, 0);
public const string BasePath = "basePath";
public const string Schemes = "schemes";
public const string SecurityDefinitions = "securityDefinitions";
public const string Definitions = "definitions";
public const string Basic = "basic";
public const string Consumes = "consumes";
public const string Produces = "produces";
#endregion
}
}

View file

@ -1,80 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
using System.Collections.Generic;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// Contact Object.
/// </summary>
public class OpenApiContact : IOpenApiSerializable, IOpenApiExtensible
{
/// <summary>
/// The identifying name of the contact person/organization.
/// </summary>
public string Name { get; set; }
/// <summary>
/// The URL pointing to the contact information. MUST be in the format of a URL.
/// </summary>
public Uri Url { get; set; }
/// <summary>
/// The email address of the contact person/organization.
/// MUST be in the format of an email address.
/// </summary>
public string Email { get; set; }
/// <summary>
/// This object MAY be extended with Specification Extensions.
/// </summary>
public IDictionary<string, IOpenApiAny> Extensions { get; set; }
/// <summary>
/// Serialize <see cref="OpenApiContact"/> to Open Api v3.0
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
WriteInternal(writer);
}
/// <summary>
/// Serialize <see cref="OpenApiContact"/> to Open Api v2.0
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
WriteInternal(writer);
}
private void WriteInternal(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
writer.WriteStartObject();
// name
writer.WriteProperty(OpenApiConstants.Name, Name);
// url
writer.WriteProperty(OpenApiConstants.Url, Url?.OriginalString);
// email
writer.WriteProperty(OpenApiConstants.Email, Email);
// extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
}
}

View file

@ -1,56 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Collections.Generic;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// Discriminator object.
/// </summary>
public class OpenApiDiscriminator : IOpenApiSerializable, IOpenApiElement
{
/// <summary>
/// REQUIRED. The name of the property in the payload that will hold the discriminator value.
/// </summary>
public string PropertyName { get; set; }
/// <summary>
/// An object to hold mappings between payload values and schema names or references.
/// </summary>
public IDictionary<string, string> Mapping { get; set; }
/// <summary>
/// Serialize <see cref="OpenApiDiscriminator"/> to Open Api v3.0
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
writer.WriteStartObject();
// propertyName
writer.WriteProperty(OpenApiConstants.PropertyName, PropertyName);
// mapping
writer.WriteOptionalMap(OpenApiConstants.Mapping, Mapping, (w, s) => w.WriteValue(s));
writer.WriteEndObject();
}
/// <summary>
/// Serialize <see cref="OpenApiDiscriminator"/> to Open Api v2.0
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
// Discriminator object does not exist in V2.
}
}
}

View file

@ -1,205 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// Describes an Open API Document. See: https://swagger.io/specification
/// </summary>
public class OpenApiDocument : IOpenApiSerializable, IOpenApiExtensible
{
/// <summary>
/// REQUIRED.This string MUST be the semantic version number of the OpenAPI Specification version that the OpenAPI document uses.
/// </summary>
public Version SpecVersion { get; set; } = OpenApiConstants.DefaultVersion;
/// <summary>
/// REQUIRED. Provides metadata about the API. The metadata MAY be used by tooling as required.
/// </summary>
public OpenApiInfo Info { get; set; } = new OpenApiInfo();
/// <summary>
/// An array of Server Objects, which provide connectivity information to a target server.
/// </summary>
public IList<OpenApiServer> Servers { get; set; }
/// <summary>
/// REQUIRED. The available paths and operations for the API.
/// </summary>
public OpenApiPaths Paths { get; set; } = new OpenApiPaths();
/// <summary>
/// An element to hold various schemas for the specification.
/// </summary>
public OpenApiComponents Components { get; set; }
/// <summary>
/// A declaration of which security mechanisms can be used across the API.
/// </summary>
public IList<OpenApiSecurityRequirement> SecurityRequirements { get; set; }
/// <summary>
/// A list of tags used by the specification with additional metadata.
/// </summary>
public IList<OpenApiTag> Tags { get; set; }
/// <summary>
/// Additional external documentation.
/// </summary>
public OpenApiExternalDocs ExternalDocs { get; set; }
/// <summary>
/// This object MAY be extended with Specification Extensions.
/// </summary>
public IDictionary<string, IOpenApiAny> Extensions { get; set; }
/// <summary>
/// Serialize <see cref="OpenApiDocument"/> to Open Api v3.0.
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
writer.WriteStartObject();
// openapi
writer.WriteProperty(OpenApiConstants.OpenApi, SpecVersion.ToString());
// info
writer.WriteRequiredObject(OpenApiConstants.Info, Info, (w, i) => i.SerializeAsV3(w));
// servers
writer.WriteOptionalCollection(OpenApiConstants.Servers, Servers, (w, s) => s.SerializeAsV3(w));
// paths
writer.WriteRequiredObject(OpenApiConstants.Paths, Paths, (w, p) => p.SerializeAsV3(w));
// components
writer.WriteOptionalObject(OpenApiConstants.Components, Components, (w, c) => c.SerializeAsV3(w));
// security
writer.WriteOptionalCollection(OpenApiConstants.Security, SecurityRequirements, (w, s) => s.SerializeAsV3(w));
// tags
writer.WriteOptionalCollection(OpenApiConstants.Tags, Tags, (w, t) => t.SerializeAsV3(w));
// external docs
writer.WriteOptionalObject(OpenApiConstants.ExternalDocs, ExternalDocs, (w, e) => e.SerializeAsV3(w));
// extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
/// <summary>
/// Serialize <see cref="OpenApiDocument"/> to Open Api v2.0.
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
writer.WriteStartObject();
// swagger
writer.WriteProperty(OpenApiConstants.Swagger, SpecVersion.ToString());
// info
writer.WriteRequiredObject(OpenApiConstants.Info, Info, (w, i) => i.SerializeAsV2(w));
// host, basePath, schemes, consumes, produces
WriteHostInfoV2(writer, Servers);
// paths
writer.WriteRequiredObject(OpenApiConstants.Paths, Paths, (w, p) => p.SerializeAsV2(w));
// definitions
writer.WriteOptionalMap(OpenApiConstants.Definitions, Components?.Schemas, (w, s) => s.SerializeAsV2(w));
// parameters
writer.WriteOptionalMap(OpenApiConstants.Parameters, Components?.Parameters, (w, p) => p.SerializeAsV2(w));
// responses
writer.WriteOptionalMap(OpenApiConstants.Responses, Components?.Responses, (w, r) => r.SerializeAsV2(w));
// securityDefinitions
writer.WriteOptionalMap(OpenApiConstants.SecurityDefinitions, Components?.SecuritySchemes, (w, s) => s.SerializeAsV2(w));
// security
writer.WriteOptionalCollection(OpenApiConstants.Security, SecurityRequirements, (w, s) => s.SerializeAsV2(w));
// tags
writer.WriteOptionalCollection(OpenApiConstants.Tags, Tags, (w, t) => t.SerializeAsV2(w));
// externalDocs
writer.WriteOptionalObject(OpenApiConstants.ExternalDocs, ExternalDocs, (w, e) => e.SerializeAsV2(w));
// extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
private static void WriteHostInfoV2(IOpenApiWriter writer, IList<OpenApiServer> servers)
{
if (servers == null || !servers.Any())
{
return;
}
// Arbitrarily choose the first server given that V2 only allows
// one host, port, and base path.
var firstServer = servers.First();
// Divide the URL in the Url property into host and basePath required in OpenAPI V2
// The Url property cannotcontain path templating to be valid for V2 serialization.
var firstServerUrl = new Uri(firstServer.Url);
// host
writer.WriteProperty(
OpenApiConstants.Host,
firstServerUrl.GetComponents(UriComponents.Host | UriComponents.Port, UriFormat.SafeUnescaped));
// basePath
writer.WriteProperty(OpenApiConstants.BasePath, firstServerUrl.AbsolutePath);
// Consider all schemes of the URLs in the server list that have the same
// host, port, and base path as the first server.
var schemes = servers.Select(
s =>
{
Uri.TryCreate(s.Url, UriKind.RelativeOrAbsolute, out var url);
return url;
})
.Where(
u => Uri.Compare(
u,
firstServerUrl,
UriComponents.Host | UriComponents.Port | UriComponents.Path,
UriFormat.SafeUnescaped,
StringComparison.OrdinalIgnoreCase) ==
0)
.Select(u => u.Scheme)
.Distinct()
.ToList();
// schemes
writer.WriteOptionalCollection(OpenApiConstants.Schemes, schemes, (w, s) => w.WriteValue(s));
}
}
}

View file

@ -1,99 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Collections.Generic;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Extensions;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// ExternalDocs object.
/// </summary>
public class OpenApiEncoding : IOpenApiSerializable, IOpenApiExtensible
{
/// <summary>
/// The Content-Type for encoding a specific property.
/// The value can be a specific media type (e.g. application/json),
/// a wildcard media type (e.g. image/*), or a comma-separated list of the two types.
/// </summary>
public string ContentType { get; set; }
/// <summary>
/// A map allowing additional information to be provided as headers.
/// </summary>
public IDictionary<string, OpenApiHeader> Headers { get; set; }
/// <summary>
/// Describes how a specific property value will be serialized depending on its type.
/// </summary>
public ParameterStyle? Style { get; set; }
/// <summary>
/// When this is true, property values of type array or object generate separate parameters
/// for each value of the array, or key-value-pair of the map. For other types of properties
/// this property has no effect. When style is form, the default value is true.
/// For all other styles, the default value is false.
/// This property SHALL be ignored if the request body media type is not application/x-www-form-urlencoded.
/// </summary>
public bool? Explode { get; set; }
/// <summary>
/// Determines whether the parameter value SHOULD allow reserved characters,
/// as defined by RFC3986 :/?#[]@!$&amp;'()*+,;= to be included without percent-encoding.
/// The default value is false. This property SHALL be ignored
/// if the request body media type is not application/x-www-form-urlencoded.
/// </summary>
public bool? AllowReserved { get; set; }
/// <summary>
/// This object MAY be extended with Specification Extensions.
/// </summary>
public IDictionary<string, IOpenApiAny> Extensions { get; set; }
/// <summary>
/// Serialize <see cref="OpenApiExternalDocs"/> to Open Api v3.0.
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull("writer");
}
writer.WriteStartObject();
// contentType
writer.WriteProperty(OpenApiConstants.ContentType, ContentType);
// headers
writer.WriteOptionalMap(OpenApiConstants.Headers, Headers, (w, h) => h.SerializeAsV3(w));
// style
writer.WriteProperty(OpenApiConstants.Style, Style?.GetDisplayName());
// explode
writer.WriteProperty(OpenApiConstants.Explode, Explode, false);
// allowReserved
writer.WriteProperty(OpenApiConstants.AllowReserved, AllowReserved, false);
// extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
/// <summary>
/// Serialize <see cref="OpenApiExternalDocs"/> to Open Api v2.0.
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
// nothing here
}
}
}

View file

@ -1,104 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Collections.Generic;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// Example Object.
/// </summary>
public class OpenApiExample : IOpenApiSerializable, IOpenApiReferenceable, IOpenApiExtensible
{
/// <summary>
/// Short description for the example.
/// </summary>
public string Summary { get; set; }
/// <summary>
/// Long description for the example.
/// CommonMark syntax MAY be used for rich text representation.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Embedded literal example. The value field and externalValue field are mutually
/// exclusive. To represent examples of media types that cannot naturally represented
/// in JSON or YAML, use a string value to contain the example, escaping where necessary.
/// </summary>
public IOpenApiAny Value { get; set; }
/// <summary>
/// A URL that points to the literal example.
/// This provides the capability to reference examples that cannot easily be
/// included in JSON or YAML documents.
/// The value field and externalValue field are mutually exclusive.
/// </summary>
public string ExternalValue { get; set; }
/// <summary>
/// This object MAY be extended with Specification Extensions.
/// </summary>
public IDictionary<string, IOpenApiAny> Extensions { get; set; }
/// <summary>
/// Reference object.
/// </summary>
public OpenApiReference Reference
{
get; set;
}
/// <summary>
/// Serialize <see cref="OpenApiExample"/> to Open Api v3.0
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
if (Reference != null)
{
Reference.SerializeAsV3(writer);
}
else
{
writer.WriteStartObject();
// summary
writer.WriteProperty(OpenApiConstants.Summary, Summary);
// description
writer.WriteProperty(OpenApiConstants.Description, Description);
// value
writer.WriteOptionalObject(OpenApiConstants.Value, Value, (w, v) => w.WriteAny(v));
// externalValue
writer.WriteProperty(OpenApiConstants.ExternalValue, ExternalValue);
// extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
}
/// <summary>
/// Serialize <see cref="OpenApiExample"/> to Open Api v2.0
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
// Example object of this form does not exist in V2.
// V2 Example object requires knowledge of media type and exists only
// in Response object, so it will be serialized as a part of the Response object.
}
}
}

View file

@ -1,69 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Collections.Generic;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// Generic dictionary type for Open API dictionary element.
/// </summary>
/// <typeparam name="T">The Open API element, <see cref="IOpenApiElement"/></typeparam>
public abstract class OpenApiExtensibleDictionary<T> : Dictionary<string, T>, IOpenApiSerializable, IOpenApiExtensible
where T : IOpenApiSerializable
{
/// <summary>
/// This object MAY be extended with Specification Extensions.
/// </summary>
public IDictionary<string, IOpenApiAny> Extensions { get; set; }
/// <summary>
/// Serialize to Open Api v3.0
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
writer.WriteStartObject();
foreach (var item in this)
{
writer.WriteRequiredObject(item.Key, item.Value, (w, p) => p.SerializeAsV3(w));
}
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
/// <summary>
/// Serialize to Open Api v2.0
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
writer.WriteStartObject();
foreach (var item in this)
{
writer.WriteRequiredObject(item.Key, item.Value, (w, p) => p.SerializeAsV2(w));
}
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
}
}

View file

@ -1,71 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
using System.Collections.Generic;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// ExternalDocs object.
/// </summary>
public class OpenApiExternalDocs : IOpenApiSerializable, IOpenApiExtensible
{
/// <summary>
/// A short description of the target documentation.
/// </summary>
public string Description { get; set; }
/// <summary>
/// REQUIRED. The URL for the target documentation. Value MUST be in the format of a URL.
/// </summary>
public Uri Url { get; set; }
/// <summary>
/// This object MAY be extended with Specification Extensions.
/// </summary>
public IDictionary<string, IOpenApiAny> Extensions { get; set; }
/// <summary>
/// Serialize <see cref="OpenApiExternalDocs"/> to Open Api v3.0.
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
WriteInternal(writer);
}
/// <summary>
/// Serialize <see cref="OpenApiExternalDocs"/> to Open Api v2.0.
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
WriteInternal(writer);
}
private void WriteInternal(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
writer.WriteStartObject();
// description
writer.WriteProperty(OpenApiConstants.Description, Description);
// url
writer.WriteProperty(OpenApiConstants.Url, Url?.OriginalString);
// extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
}
}

View file

@ -1,196 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Collections.Generic;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Extensions;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// Header Object.
/// The Header Object follows the structure of the Parameter Object.
/// </summary>
public class OpenApiHeader : IOpenApiSerializable, IOpenApiReferenceable, IOpenApiExtensible
{
/// <summary>
/// Reference pointer.
/// </summary>
public OpenApiReference Reference { get; set; }
/// <summary>
/// A brief description of the header.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Determines whether this header is mandatory.
/// </summary>
public bool Required { get; set; }
/// <summary>
/// Specifies that a header is deprecated and SHOULD be transitioned out of usage.
/// </summary>
public bool Deprecated { get; set; }
/// <summary>
/// Sets the ability to pass empty-valued headers.
/// </summary>
public bool AllowEmptyValue { get; set; }
/// <summary>
/// Describes how the header value will be serialized depending on the type of the header value.
/// </summary>
public ParameterStyle? Style { get; set; }
/// <summary>
/// When this is true, header values of type array or object generate separate parameters
/// for each value of the array or key-value pair of the map.
/// </summary>
public bool Explode { get; set; }
/// <summary>
/// Determines whether the header value SHOULD allow reserved characters, as defined by RFC3986.
/// </summary>
public bool AllowReserved { get; set; }
/// <summary>
/// The schema defining the type used for the header.
/// </summary>
public OpenApiSchema Schema { get; set; }
/// <summary>
/// Example of the media type.
/// </summary>
public IOpenApiAny Example { get; set; }
/// <summary>
/// Examples of the media type.
/// </summary>
public IList<OpenApiExample> Examples { get; set; }
/// <summary>
/// A map containing the representations for the header.
/// </summary>
public IDictionary<string, OpenApiMediaType> Content { get; set; }
/// <summary>
/// This object MAY be extended with Specification Extensions.
/// </summary>
public IDictionary<string, IOpenApiAny> Extensions { get; set; }
/// <summary>
/// Serialize <see cref="OpenApiHeader"/> to Open Api v3.0
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
if (Reference != null)
{
Reference.SerializeAsV3(writer);
}
else
{
writer.WriteStartObject();
// description
writer.WriteProperty(OpenApiConstants.Description, Description);
// required
writer.WriteProperty(OpenApiConstants.Required, Required, false);
// deprecated
writer.WriteProperty(OpenApiConstants.Deprecated, Deprecated, false);
// allowEmptyValue
writer.WriteProperty(OpenApiConstants.AllowEmptyValue, AllowEmptyValue, false);
// style
writer.WriteProperty(OpenApiConstants.Style, Style?.GetDisplayName());
// explode
writer.WriteProperty(OpenApiConstants.Explode, Explode, false);
// allowReserved
writer.WriteProperty(OpenApiConstants.AllowReserved, AllowReserved, false);
// schema
writer.WriteOptionalObject(OpenApiConstants.Schema, Schema, (w, s) => s.SerializeAsV3(w));
// example
writer.WriteOptionalObject(OpenApiConstants.Example, Example, (w, s) => w.WriteAny(s));
// examples
writer.WriteOptionalCollection(OpenApiConstants.Examples, Examples, (w, e) => e.SerializeAsV3(w));
// content
writer.WriteOptionalMap(OpenApiConstants.Content, Content, (w, c) => c.SerializeAsV3(w));
// extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
}
/// <summary>
/// Serialize <see cref="OpenApiHeader"/> to Open Api v2.0
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
if (Reference != null)
{
Reference.SerializeAsV2(writer);
}
else
{
writer.WriteStartObject();
// description
writer.WriteProperty(OpenApiConstants.Description, Description);
// required
writer.WriteProperty(OpenApiConstants.Required, Required, false);
// deprecated
writer.WriteProperty(OpenApiConstants.Deprecated, Deprecated, false);
// allowEmptyValue
writer.WriteProperty(OpenApiConstants.AllowEmptyValue, AllowEmptyValue, false);
// style
writer.WriteProperty(OpenApiConstants.Style, Style?.GetDisplayName());
// explode
writer.WriteProperty(OpenApiConstants.Explode, Explode, false);
// allowReserved
writer.WriteProperty(OpenApiConstants.AllowReserved, AllowReserved, false);
// schema
writer.WriteOptionalObject(OpenApiConstants.Schema, Schema, (w, s) => s.SerializeAsV2(w));
// example
writer.WriteOptionalObject(OpenApiConstants.Example, Example, (w, s) => w.WriteAny(s));
// extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
}
}
}

View file

@ -1,126 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
using System.Collections.Generic;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// Open API Info Object, it provides the metadata about the Open API.
/// </summary>
public class OpenApiInfo : IOpenApiSerializable, IOpenApiExtensible
{
/// <summary>
/// REQUIRED. The title of the application.
/// </summary>
public string Title { get; set; } = OpenApiConstants.DefaultTitle;
/// <summary>
/// A short description of the application.
/// </summary>
public string Description { get; set; }
/// <summary>
/// REQUIRED. The version of the OpenAPI document.
/// </summary>
public string Version { get; set; } = "1.0";
/// <summary>
/// A URL to the Terms of Service for the API. MUST be in the format of a URL.
/// </summary>
public Uri TermsOfService { get; set; }
/// <summary>
/// The contact information for the exposed API.
/// </summary>
public OpenApiContact Contact { get; set; }
/// <summary>
/// The license information for the exposed API.
/// </summary>
public OpenApiLicense License { get; set; }
/// <summary>
/// This object MAY be extended with Specification Extensions.
/// </summary>
public IDictionary<string, IOpenApiAny> Extensions { get; set; }
/// <summary>
/// Serialize <see cref="OpenApiInfo"/> to Open Api v3.0
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
writer.WriteStartObject();
// title
writer.WriteProperty(OpenApiConstants.Title, Title);
// description
writer.WriteProperty(OpenApiConstants.Description, Description);
// termsOfService
writer.WriteProperty(OpenApiConstants.TermsOfService, TermsOfService?.OriginalString);
// contact object
writer.WriteOptionalObject(OpenApiConstants.Contact, Contact, (w, c) => c.SerializeAsV3(w));
// license object
writer.WriteOptionalObject(OpenApiConstants.License, License, (w, l) => l.SerializeAsV3(w));
// version
writer.WriteProperty(OpenApiConstants.Version, Version?.ToString());
// specification extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
/// <summary>
/// Serialize <see cref="OpenApiInfo"/> to Open Api v2.0
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
writer.WriteStartObject();
// title
writer.WriteProperty(OpenApiConstants.Title, Title);
// description
writer.WriteProperty(OpenApiConstants.Description, Description);
// termsOfService
writer.WriteProperty(OpenApiConstants.TermsOfService, TermsOfService?.OriginalString);
// contact object
writer.WriteOptionalObject(OpenApiConstants.Contact, Contact, (w, c) => c.SerializeAsV2(w));
// license object
writer.WriteOptionalObject(OpenApiConstants.License, License, (w, l) => l.SerializeAsV2(w));
// version
writer.WriteProperty(OpenApiConstants.Version, Version?.ToString());
// specification extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
}
}

View file

@ -1,71 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
using System.Collections.Generic;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// License Object.
/// </summary>
public class OpenApiLicense : IOpenApiSerializable, IOpenApiExtensible
{
/// <summary>
/// REQUIRED.The license name used for the API.
/// </summary>
public string Name { get; set; } = OpenApiConstants.DefaultName;
/// <summary>
/// The URL pointing to the contact information. MUST be in the format of a URL.
/// </summary>
public Uri Url { get; set; }
/// <summary>
/// This object MAY be extended with Specification Extensions.
/// </summary>
public IDictionary<string, IOpenApiAny> Extensions { get; set; }
/// <summary>
/// Serialize <see cref="OpenApiLicense"/> to Open Api v3.0
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
WriteInternal(writer);
}
/// <summary>
/// Serialize <see cref="OpenApiLicense"/> to Open Api v2.0
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
WriteInternal(writer);
}
private void WriteInternal(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
writer.WriteStartObject();
// name
writer.WriteProperty(OpenApiConstants.Name, Name);
// url
writer.WriteProperty(OpenApiConstants.Url, Url?.OriginalString);
// specification extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
}
}

View file

@ -1,108 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Collections.Generic;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// Link Object.
/// </summary>
public class OpenApiLink : IOpenApiSerializable, IOpenApiReferenceable, IOpenApiExtensible
{
/// <summary>
/// A relative or absolute reference to an OAS operation.
/// This field is mutually exclusive of the operationId field, and MUST point to an Operation Object.
/// </summary>
public string OperationRef { get; set; }
/// <summary>
/// The name of an existing, resolvable OAS operation, as defined with a unique operationId.
/// This field is mutually exclusive of the operationRef field.
/// </summary>
public string OperationId { get; set; }
/// <summary>
/// A map representing parameters to pass to an operation as specified with operationId or identified via operationRef.
/// </summary>
public Dictionary<string, RuntimeExpressionAnyWrapper> Parameters { get; set; }
/// <summary>
/// A literal value or {expression} to use as a request body when calling the target operation.
/// </summary>
public RuntimeExpressionAnyWrapper RequestBody { get; set; }
/// <summary>
/// A description of the link.
/// </summary>
public string Description { get; set; }
/// <summary>
/// A server object to be used by the target operation.
/// </summary>
public OpenApiServer Server { get; set; }
/// <summary>
/// This object MAY be extended with Specification Extensions.
/// </summary>
public IDictionary<string, IOpenApiAny> Extensions { get; set; }
/// <summary>
/// Reference pointer.
/// </summary>
public OpenApiReference Reference { get; set; }
/// <summary>
/// Serialize <see cref="OpenApiLink"/> to Open Api v3.0
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
if (Reference != null)
{
Reference.SerializeAsV3(writer);
}
else
{
writer.WriteStartObject();
// operationRef
writer.WriteProperty(OpenApiConstants.OperationRef, OperationRef);
// operationId
writer.WriteProperty(OpenApiConstants.OperationId, OperationId);
// parameters
writer.WriteOptionalMap(OpenApiConstants.Parameters, Parameters, (w, p) => p.WriteValue(w));
// requestBody
writer.WriteOptionalObject(OpenApiConstants.RequestBody, RequestBody, (w, r) => r.WriteValue(w));
// description
writer.WriteProperty(OpenApiConstants.Description, Description);
// server
writer.WriteOptionalObject(OpenApiConstants.Server, Server, (w, s) => s.SerializeAsV3(w));
writer.WriteEndObject();
}
}
/// <summary>
/// Serialize <see cref="OpenApiLink"/> to Open Api v2.0
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
// link object does not exist in V2.
}
}
}

View file

@ -1,86 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Collections.Generic;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// Media Type Object.
/// </summary>
public class OpenApiMediaType : IOpenApiSerializable, IOpenApiExtensible
{
/// <summary>
/// The schema defining the type used for the request body.
/// </summary>
public OpenApiSchema Schema { get; set; }
/// <summary>
/// Example of the media type.
/// The example object SHOULD be in the correct format as specified by the media type.
/// </summary>
public IOpenApiAny Example { get; set; }
/// <summary>
/// Examples of the media type.
/// Each example object SHOULD match the media type and specified schema if present.
/// </summary>
public IDictionary<string, OpenApiExample> Examples { get; set; }
/// <summary>
/// A map between a property name and its encoding information.
/// The key, being the property name, MUST exist in the schema as a property.
/// The encoding object SHALL only apply to requestBody objects
/// when the media type is multipart or application/x-www-form-urlencoded.
/// </summary>
public IDictionary<string, OpenApiEncoding> Encoding { get; set; }
/// <summary>
/// Serialize <see cref="OpenApiExternalDocs"/> to Open Api v3.0.
/// </summary>
public IDictionary<string, IOpenApiAny> Extensions { get; set; }
/// <summary>
/// Serialize <see cref="OpenApiMediaType"/> to Open Api v3.0.
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
writer.WriteStartObject();
// schema
writer.WriteOptionalObject(OpenApiConstants.Schema, Schema, (w, s) => s.SerializeAsV3(w));
// example
writer.WriteOptionalObject(OpenApiConstants.Example, Example, (w, e) => w.WriteAny(e));
// examples
writer.WriteOptionalMap(OpenApiConstants.Examples, Examples, (w, e) => e.SerializeAsV3(w));
// encoding
writer.WriteOptionalMap(OpenApiConstants.Encoding, Encoding, (w, e) => e.SerializeAsV3(w));
// extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
/// <summary>
/// Serialize <see cref="OpenApiMediaType"/> to Open Api v2.0.
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
// Media type does not exist in V2.
}
}
}

View file

@ -1,84 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
using System.Collections.Generic;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// OAuth Flow Object.
/// </summary>
public class OpenApiOAuthFlow : IOpenApiSerializable, IOpenApiExtensible
{
/// <summary>
/// REQUIRED. The authorization URL to be used for this flow.
/// Applies to implicit and authorizationCode OAuthFlow.
/// </summary>
public Uri AuthorizationUrl { get; set; }
/// <summary>
/// REQUIRED. The token URL to be used for this flow.
/// Applies to password, clientCredentials, and authorizationCode OAuthFlow.
/// </summary>
public Uri TokenUrl { get; set; }
/// <summary>
/// The URL to be used for obtaining refresh tokens.
/// </summary>
public Uri RefreshUrl { get; set; }
/// <summary>
/// REQUIRED. A map between the scope name and a short description for it.
/// </summary>
public IDictionary<string, string> Scopes { get; set; }
/// <summary>
/// Specification Extensions.
/// </summary>
public IDictionary<string, IOpenApiAny> Extensions { get; set; }
/// <summary>
/// Serialize <see cref="OpenApiOAuthFlow"/> to Open Api v3.0
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
writer.WriteStartObject();
// authorizationUrl
writer.WriteProperty(OpenApiConstants.AuthorizationUrl, AuthorizationUrl?.ToString());
// tokenUrl
writer.WriteProperty(OpenApiConstants.TokenUrl, TokenUrl?.ToString());
// refreshUrl
writer.WriteProperty(OpenApiConstants.RefreshUrl, RefreshUrl?.ToString());
// scopes
writer.WriteRequiredMap(OpenApiConstants.Scopes, Scopes, (w, s) => w.WriteValue(s));
// extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
/// <summary>
/// Serialize <see cref="OpenApiOAuthFlow"/> to Open Api v2.0
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
// OAuthFlow object does not exist in V2.
}
}
}

View file

@ -1,81 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Collections.Generic;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// OAuth Flows Object.
/// </summary>
public class OpenApiOAuthFlows : IOpenApiSerializable, IOpenApiExtensible
{
/// <summary>
/// Configuration for the OAuth Implicit flow
/// </summary>
public OpenApiOAuthFlow Implicit { get; set; }
/// <summary>
/// Configuration for the OAuth Resource Owner Password flow.
/// </summary>
public OpenApiOAuthFlow Password { get; set; }
/// <summary>
/// Configuration for the OAuth Client Credentials flow.
/// </summary>
public OpenApiOAuthFlow ClientCredentials { get; set; }
/// <summary>
/// Configuration for the OAuth Authorization Code flow.
/// </summary>
public OpenApiOAuthFlow AuthorizationCode { get; set; }
/// <summary>
/// Specification Extensions.
/// </summary>
public IDictionary<string, IOpenApiAny> Extensions { get; set; }
/// <summary>
/// Serialize <see cref="OpenApiOAuthFlows"/> to Open Api v3.0
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
writer.WriteStartObject();
// implicit
writer.WriteOptionalObject(OpenApiConstants.Implicit, Implicit, (w, o) => o.SerializeAsV3(w));
// password
writer.WriteOptionalObject(OpenApiConstants.Password, Password, (w, o) => o.SerializeAsV3(w));
// clientCredentials
writer.WriteOptionalObject(OpenApiConstants.ClientCredentials, ClientCredentials, (w, o) => o.SerializeAsV3(w));
// authorizationCode
writer.WriteOptionalObject(OpenApiConstants.AuthorizationCode, AuthorizationCode, (w, o) => o.SerializeAsV3(w));
// extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
/// <summary>
/// Serialize <see cref="OpenApiOAuthFlows"/> to Open Api v2.0
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
// OAuthFlows object does not exist in V2.
}
}
}

View file

@ -1,285 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// Operation Object.
/// </summary>
public class OpenApiOperation : IOpenApiSerializable, IOpenApiExtensible
{
/// <summary>
/// Default value for <see cref="Deprecated"/>.
/// </summary>
public const bool DeprecatedDefault = false;
/// <summary>
/// A list of tags for API documentation control.
/// Tags can be used for logical grouping of operations by resources or any other qualifier.
/// </summary>
public IList<OpenApiTag> Tags { get; set; } = new List<OpenApiTag>();
/// <summary>
/// A short summary of what the operation does.
/// </summary>
public string Summary { get; set; }
/// <summary>
/// A verbose explanation of the operation behavior.
/// CommonMark syntax MAY be used for rich text representation.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Additional external documentation for this operation.
/// </summary>
public OpenApiExternalDocs ExternalDocs { get; set; }
/// <summary>
/// Unique string used to identify the operation. The id MUST be unique among all operations described in the API.
/// Tools and libraries MAY use the operationId to uniquely identify an operation, therefore,
/// it is RECOMMENDED to follow common programming naming conventions.
/// </summary>
public string OperationId { get; set; }
/// <summary>
/// A list of parameters that are applicable for this operation.
/// If a parameter is already defined at the Path Item, the new definition will override it but can never remove it.
/// The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location.
/// The list can use the Reference Object to link to parameters that are defined at the OpenAPI Object's components/parameters.
/// </summary>
public IList<OpenApiParameter> Parameters { get; set; } = new List<OpenApiParameter>();
/// <summary>
/// The request body applicable for this operation.
/// The requestBody is only supported in HTTP methods where the HTTP 1.1 specification RFC7231
/// has explicitly defined semantics for request bodies.
/// In other cases where the HTTP spec is vague, requestBody SHALL be ignored by consumers.
/// </summary>
public OpenApiRequestBody RequestBody { get; set; }
/// <summary>
/// REQUIRED. The list of possible responses as they are returned from executing this operation.
/// </summary>
public OpenApiResponses Responses { get; set; }
/// <summary>
/// A map of possible out-of band callbacks related to the parent operation.
/// The key is a unique identifier for the Callback Object.
/// Each value in the map is a Callback Object that describes a request
/// that may be initiated by the API provider and the expected responses.
/// The key value used to identify the callback object is an expression, evaluated at runtime,
/// that identifies a URL to use for the callback operation.
/// </summary>
public IDictionary<string, OpenApiCallback> Callbacks { get; set; }
/// <summary>
/// Declares this operation to be deprecated. Consumers SHOULD refrain from usage of the declared operation.
/// </summary>
public bool Deprecated { get; set; } = DeprecatedDefault;
/// <summary>
/// A declaration of which security mechanisms can be used for this operation.
/// The list of values includes alternative security requirement objects that can be used.
/// Only one of the security requirement objects need to be satisfied to authorize a request.
/// This definition overrides any declared top-level security.
/// To remove a top-level security declaration, an empty array can be used.
/// </summary>
public IList<OpenApiSecurityRequirement> Security { get; set; } = new List<OpenApiSecurityRequirement>();
/// <summary>
/// An alternative server array to service this operation.
/// If an alternative server object is specified at the Path Item Object or Root level,
/// it will be overridden by this value.
/// </summary>
public IList<OpenApiServer> Servers { get; set; } = new List<OpenApiServer>();
/// <summary>
/// This object MAY be extended with Specification Extensions.
/// </summary>
public IDictionary<string, IOpenApiAny> Extensions { get; set; }
/// <summary>
/// Serialize <see cref="OpenApiOperation"/> to Open Api v3.0.
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
writer.WriteStartObject();
// tags
writer.WriteOptionalCollection(OpenApiConstants.Tags, Tags, (w, t) =>
{
// Handle tag writing here instead of in OpenApiTag since we also need to ensure
// that tag is written as string regardless of whether reference exists.
w.WriteValue(t.Reference != null ? t.Reference.Id : t.Name);
});
// summary
writer.WriteProperty(OpenApiConstants.Summary, Summary);
// description
writer.WriteProperty(OpenApiConstants.Description, Description);
// externalDocs
writer.WriteOptionalObject(OpenApiConstants.ExternalDocs, ExternalDocs, (w, e) => e.SerializeAsV3(w));
// operationId
writer.WriteProperty(OpenApiConstants.OperationId, OperationId);
// parameters
writer.WriteOptionalCollection(OpenApiConstants.Parameters, Parameters, (w, p) => p.SerializeAsV3(w));
// requestBody
writer.WriteOptionalObject(OpenApiConstants.RequestBody, RequestBody, (w, r) => r.WriteAsV3(w));
// responses
writer.WriteOptionalObject(OpenApiConstants.Responses, Responses, (w, r) => r.SerializeAsV3(w));
// callbacks
writer.WriteOptionalMap(OpenApiConstants.Callbacks, Callbacks, (w, c) => c.SerializeAsV3(w));
// deprecated
writer.WriteProperty(OpenApiConstants.Deprecated, Deprecated, false);
// security
writer.WriteOptionalCollection(OpenApiConstants.Security, Security, (w, s) => s.SerializeAsV3(w));
// servers
writer.WriteOptionalCollection(OpenApiConstants.Servers, Servers, (w, s) => s.SerializeAsV3(w));
// specification extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
/// <summary>
/// Serialize <see cref="OpenApiOperation"/> to Open Api v2.0.
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
writer.WriteStartObject();
// tags
writer.WriteOptionalCollection(OpenApiConstants.Tags, Tags, (w, t) =>
{
// Handle tag writing here instead of in OpenApiTag since we also need to ensure
// that tag is written as string regardless of whether reference exists.
w.WriteValue(t.Reference != null ? t.Reference.Id : t.Name);
});
// summary
writer.WriteProperty(OpenApiConstants.Summary, Summary);
// description
writer.WriteProperty(OpenApiConstants.Description, Description);
// externalDocs
writer.WriteOptionalObject(OpenApiConstants.ExternalDocs, ExternalDocs, (w, e) => e.SerializeAsV2(w));
// operationId
writer.WriteProperty(OpenApiConstants.OperationId, OperationId);
var parameters = new List<OpenApiParameter>(Parameters);
if (RequestBody != null)
{
// consumes
writer.WritePropertyName(OpenApiConstants.Consumes);
writer.WriteStartArray();
var consumes = RequestBody.Content.Keys.Distinct().ToList();
foreach (var mediaType in consumes)
{
writer.WriteValue(mediaType);
}
writer.WriteEndArray();
// Create a parameter as BodyParameter type and add to Parameters.
// This type will be used to populate the In property as "body" when Parameters is serialized.
var bodyParameter = new BodyParameter
{
Description = RequestBody.Description,
Schema = RequestBody.Content.First().Value.Schema,
Format = new List<string>(consumes)
};
parameters.Add(bodyParameter);
}
if (Responses != null)
{
var produces = Responses.Where(r => r.Value.Content != null)
.SelectMany(r => r.Value.Content?.Keys)
.Distinct()
.ToList();
if (produces.Any())
{
// produces
writer.WritePropertyName(OpenApiConstants.Produces);
writer.WriteStartArray();
foreach (var mediaType in produces)
{
writer.WriteValue(mediaType);
}
writer.WriteEndArray();
}
}
// parameters
// Use the parameters created locally to include request body if exists.
writer.WriteOptionalCollection(OpenApiConstants.Parameters, parameters, (w, p) => p.SerializeAsV2(w));
// responses
writer.WriteOptionalMap(OpenApiConstants.Responses, Responses, (w, r) => r.SerializeAsV2(w));
// schemes
// All schemes in the Servers are extracted, regardless of whether the host matches
// the host defined in the outermost Swagger object. This is due to the
// inaccessibility of information for that host in the context of an inner object like this Operation.
var schemes = Servers.Select(
s =>
{
Uri.TryCreate(s.Url, UriKind.RelativeOrAbsolute, out var url);
return url?.Scheme;
})
.Where(s => s != null)
.Distinct()
.ToList();
writer.WriteOptionalCollection(OpenApiConstants.Schemes, schemes, (w, s) => w.WriteValue(s));
// deprecated
writer.WriteProperty(OpenApiConstants.Deprecated, Deprecated, false);
// security
writer.WriteOptionalCollection(OpenApiConstants.Security, Security, (w, s) => s.SerializeAsV2(w));
// specification extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
}
}

View file

@ -1,312 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Collections.Generic;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Extensions;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// Parameter Object.
/// </summary>
public class OpenApiParameter : IOpenApiSerializable, IOpenApiReferenceable, IOpenApiExtensible
{
/// <summary>
/// Reference object.
/// </summary>
public OpenApiReference Reference { get; set; }
/// <summary>
/// REQUIRED. The name of the parameter. Parameter names are case sensitive.
/// If in is "path", the name field MUST correspond to the associated path segment from the path field in the Paths Object.
/// If in is "header" and the name field is "Accept", "Content-Type" or "Authorization", the parameter definition SHALL be ignored.
/// For all other cases, the name corresponds to the parameter name used by the in property.
/// </summary>
public string Name { get; set; }
/// <summary>
/// REQUIRED. The location of the parameter.
/// Possible values are "query", "header", "path" or "cookie".
/// </summary>
public ParameterLocation In { get; set; }
/// <summary>
/// A brief description of the parameter. This could contain examples of use.
/// CommonMark syntax MAY be used for rich text representation.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Determines whether this parameter is mandatory.
/// If the parameter location is "path", this property is REQUIRED and its value MUST be true.
/// Otherwise, the property MAY be included and its default value is false.
/// </summary>
public bool Required { get; set; }
/// <summary>
/// Specifies that a parameter is deprecated and SHOULD be transitioned out of usage.
/// </summary>
public bool Deprecated { get; set; } = false;
/// <summary>
/// Sets the ability to pass empty-valued parameters.
/// This is valid only for query parameters and allows sending a parameter with an empty value.
/// Default value is false.
/// If style is used, and if behavior is n/a (cannot be serialized),
/// the value of allowEmptyValue SHALL be ignored.
/// </summary>
public bool AllowEmptyValue { get; set; } = false;
/// <summary>
/// Describes how the parameter value will be serialized depending on the type of the parameter value.
/// Default values (based on value of in): for query - form; for path - simple; for header - simple;
/// for cookie - form.
/// </summary>
public ParameterStyle? Style { get; set; }
/// <summary>
/// When this is true, parameter values of type array or object generate separate parameters
/// for each value of the array or key-value pair of the map.
/// For other types of parameters this property has no effect.
/// When style is form, the default value is true.
/// For all other styles, the default value is false.
/// </summary>
public bool Explode { get; set; }
/// <summary>
/// Determines whether the parameter value SHOULD allow reserved characters,
/// as defined by RFC3986 :/?#[]@!$&amp;'()*+,;= to be included without percent-encoding.
/// This property only applies to parameters with an in value of query.
/// The default value is false.
/// </summary>
public bool AllowReserved { get; set; }
/// <summary>
/// The schema defining the type used for the parameter.
/// </summary>
public OpenApiSchema Schema { get; set; }
/// <summary>
/// Examples of the media type. Each example SHOULD contain a value
/// in the correct format as specified in the parameter encoding.
/// The examples object is mutually exclusive of the example object.
/// Furthermore, if referencing a schema which contains an example,
/// the examples value SHALL override the example provided by the schema.
/// </summary>
public IList<OpenApiExample> Examples { get; set; }
/// <summary>
/// Example of the media type. The example SHOULD match the specified schema and encoding properties
/// if present. The example object is mutually exclusive of the examples object.
/// Furthermore, if referencing a schema which contains an example,
/// the example value SHALL override the example provided by the schema.
/// To represent examples of media types that cannot naturally be represented in JSON or YAML,
/// a string value can contain the example with escaping where necessary.
/// </summary>
public IOpenApiAny Example { get; set; }
/// <summary>
/// A map containing the representations for the parameter.
/// The key is the media type and the value describes it.
/// The map MUST only contain one entry.
/// For more complex scenarios, the content property can define the media type and schema of the parameter.
/// A parameter MUST contain either a schema property, or a content property, but not both.
/// When example or examples are provided in conjunction with the schema object,
/// the example MUST follow the prescribed serialization strategy for the parameter.
/// </summary>
public IDictionary<string, OpenApiMediaType> Content { get; set; }
/// <summary>
/// This object MAY be extended with Specification Extensions.
/// </summary>
public IDictionary<string, IOpenApiAny> Extensions { get; set; }
/// <summary>
/// Serialize <see cref="OpenApiParameter"/> to Open Api v3.0
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
if (Reference != null)
{
Reference.SerializeAsV3(writer);
return;
}
writer.WriteStartObject();
// name
writer.WriteProperty(OpenApiConstants.Name, Name);
// in
writer.WriteProperty(OpenApiConstants.In, In.GetDisplayName());
// description
writer.WriteProperty(OpenApiConstants.Description, Description);
// required
writer.WriteProperty(OpenApiConstants.Required, Required, false);
// deprecated
writer.WriteProperty(OpenApiConstants.Deprecated, Deprecated, false);
// allowEmptyValue
writer.WriteProperty(OpenApiConstants.AllowEmptyValue, AllowEmptyValue, false);
// style
writer.WriteProperty(OpenApiConstants.Style, Style?.GetDisplayName());
// explode
writer.WriteProperty(OpenApiConstants.Explode, Explode, false);
// allowReserved
writer.WriteProperty(OpenApiConstants.AllowReserved, AllowReserved, false);
// schema
writer.WriteOptionalObject(OpenApiConstants.Schema, Schema, (w, s) => s.SerializeAsV3(w));
// example
writer.WriteOptionalObject(OpenApiConstants.Example, Example, (w, s) => w.WriteAny(s));
// examples
writer.WriteOptionalCollection(OpenApiConstants.Examples, Examples, (w, e) => e.SerializeAsV3(w));
// content
writer.WriteOptionalMap(OpenApiConstants.Content, Content, (w, c) => c.SerializeAsV3(w));
// extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
/// <summary>
/// Serialize <see cref="OpenApiParameter"/> to Open Api v2.0
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
if (Reference != null)
{
Reference.SerializeAsV2(writer);
return;
}
writer.WriteStartObject();
// name
// in
if (IsFormDataParameter())
{
writer.WriteProperty(OpenApiConstants.Name, "formData");
writer.WriteProperty(OpenApiConstants.In, "formData");
}
else if (IsBodyParameter())
{
writer.WriteProperty(OpenApiConstants.Name, "body");
writer.WriteProperty(OpenApiConstants.In, "body");
}
else
{
writer.WriteProperty(OpenApiConstants.Name, Name);
writer.WriteProperty(OpenApiConstants.In, In.ToString());
}
// description
writer.WriteProperty(OpenApiConstants.Description, Description);
// required
writer.WriteProperty(OpenApiConstants.Required, Required, false);
// deprecated
writer.WriteProperty(OpenApiConstants.Deprecated, Deprecated, false);
// schema
if (IsBodyParameter())
{
writer.WriteOptionalObject(OpenApiConstants.Schema, Schema, (w, s) => s.SerializeAsV2(w));
}
else
{
// type
// format
// items
// collectionFormat
// default
// maximum
// exclusiveMaximum
// minimum
// exclusiveMinimum
// maxLength
// minLength
// pattern
// maxItems
// minItems
// uniqueItems
// enum
// multipleOf
Schema?.WriteAsItemsProperties(writer);
// allowEmptyValue
writer.WriteProperty(OpenApiConstants.AllowEmptyValue, AllowEmptyValue, false);
}
// extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
private bool IsBodyParameter()
{
if (this is BodyParameter)
{
var parameter = (BodyParameter)this;
return !(
parameter.Format.Contains("application/x-www-form-urlencoded") ||
parameter.Format.Contains("multipart/form-data"));
}
return false;
}
private bool IsFormDataParameter()
{
if (this is BodyParameter)
{
var parameter = (BodyParameter)this;
return
parameter.Format.Contains("application/x-www-form-urlencoded") ||
parameter.Format.Contains("multipart/form-data");
}
return false;
}
}
/// <summary>
/// Body parameter class to propagate information needed for <see cref="OpenApiParameter.SerializeAsV2"/>
/// </summary>
internal class BodyParameter : OpenApiParameter
{
/// <summary>
/// Format of the parameter. This should be the same as the "consumes" property in Operation.
/// </summary>
public IList<string> Format { get; set; }
}
}

View file

@ -1,138 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Collections.Generic;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Extensions;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// Path Item Object: to describe the operations available on a single path.
/// </summary>
public class OpenApiPathItem : IOpenApiSerializable, IOpenApiExtensible
{
/// <summary>
/// An optional, string summary, intended to apply to all operations in this path.
/// </summary>
public string Summary { get; set; }
/// <summary>
/// An optional, string description, intended to apply to all operations in this path.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Gets the definition of operations on this path.
/// </summary>
public IDictionary<OperationType, OpenApiOperation> Operations { get; set; }
= new Dictionary<OperationType, OpenApiOperation>();
/// <summary>
/// An alternative server array to service all operations in this path.
/// </summary>
public IList<OpenApiServer> Servers { get; set; } = new List<OpenApiServer>();
/// <summary>
/// A list of parameters that are applicable for all the operations described under this path.
/// These parameters can be overridden at the operation level, but cannot be removed there.
/// </summary>
public IList<OpenApiParameter> Parameters { get; set; } = new List<OpenApiParameter>();
/// <summary>
/// This object MAY be extended with Specification Extensions.
/// </summary>
public IDictionary<string, IOpenApiAny> Extensions { get; set; }
/// <summary>
/// Add one operation into this path item.
/// </summary>
/// <param name="operationType">The operation type kind.</param>
/// <param name="operation">The operation item.</param>
public void AddOperation(OperationType operationType, OpenApiOperation operation)
{
Operations[operationType] = operation;
}
/// <summary>
/// Serialize <see cref="OpenApiPathItem"/> to Open Api v3.0
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
writer.WriteStartObject();
// summary
writer.WriteProperty(OpenApiConstants.Summary, Summary);
// description
writer.WriteProperty(OpenApiConstants.Description, Description);
// operations
foreach (var operation in Operations)
{
writer.WriteOptionalObject(operation.Key.GetDisplayName(), operation.Value, (w, o) => o.SerializeAsV3(w));
}
// servers
writer.WriteOptionalCollection(OpenApiConstants.Servers, Servers, (w, s) => s.SerializeAsV3(w));
// parameters
writer.WriteOptionalCollection(OpenApiConstants.Parameters, Parameters, (w, p) => p.SerializeAsV3(w));
// specification extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
/// <summary>
/// Serialize <see cref="OpenApiPathItem"/> to Open Api v2.0
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
writer.WriteStartObject();
// operations except "trace"
foreach (var operation in Operations)
{
if (operation.Key != OperationType.Trace)
{
writer.WriteOptionalObject(
operation.Key.GetDisplayName(),
operation.Value,
(w, o) => o.SerializeAsV2(w));
}
}
// parameters
writer.WriteOptionalCollection(OpenApiConstants.Parameters, Parameters, (w, p) => p.SerializeAsV2(w));
// write "summary" as extensions
writer.WriteProperty(OpenApiConstants.ExtensionFieldNamePrefix + OpenApiConstants.Summary, Summary);
// write "description" as extensions
writer.WriteProperty(
OpenApiConstants.ExtensionFieldNamePrefix + OpenApiConstants.Description,
Description);
// specification extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
}
}

View file

@ -1,14 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// Paths object.
/// </summary>
public class OpenApiPaths : OpenApiExtensibleDictionary<OpenApiPathItem>
{
}
}

View file

@ -1,216 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
using Microsoft.OpenApi.Exceptions;
using Microsoft.OpenApi.Extensions;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Properties;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// A simple object to allow referencing other components in the specification, internally and externally.
/// </summary>
public class OpenApiReference : IOpenApiSerializable
{
/// <summary>
/// External resource in the reference.
/// It maybe:
/// 1. a absolute/relative file path, for example: ../commons/pet.json
/// 2. a Url, for example: http://localhost/pet.json
/// </summary>
public string ExternalResource { get; set; }
/// <summary>
/// The element type referenced.
/// </summary>
/// <remarks>This must be present if <see cref="ExternalResource"/> is not present.</remarks>
public ReferenceType? Type { get; set; }
/// <summary>
/// The identifier of the reusable component of one particular ReferenceType.
/// If ExternalResource is present, this is the path to the component after the '#/'.
/// For example, if the reference is 'example.json#/path/to/component', the Id is 'path/to/component'.
/// If ExternalResource is not present, this is the name of the component without the reference type name.
/// For example, if the reference is '#/components/schemas/componentName', the Id is 'componentName'.
/// </summary>
public string Id { get; set; }
/// <summary>
/// Gets a flag indicating whether this reference is an external reference.
/// </summary>
public bool IsExternal => ExternalResource != null;
/// <summary>
/// Gets a flag indicating whether this reference is a local reference.
/// </summary>
public bool IsLocal => ExternalResource == null;
/// <summary>
/// Gets the full reference string for v3.0.
/// </summary>
public string ReferenceV3
{
get
{
if (IsExternal)
{
return GetExternalReference();
}
if (!Type.HasValue)
{
throw Error.ArgumentNull(nameof(Type));
}
if (Type == ReferenceType.Tag)
{
return Id;
}
if (Type == ReferenceType.SecurityScheme)
{
return Id;
}
return "#/components/" + Type.GetDisplayName() + "/" + this.Id;
}
}
/// <summary>
/// Gets the full reference string for V2.0
/// </summary>
public string ReferenceV2
{
get
{
if (IsExternal)
{
return GetExternalReference();
}
if (!Type.HasValue)
{
throw Error.ArgumentNull(nameof(Type));
}
if (Type == ReferenceType.Tag)
{
return Id;
}
if (Type == ReferenceType.SecurityScheme)
{
return Id;
}
return "#/" + GetReferenceTypeNameAsV2(Type.Value) + "/" + this.Id;
}
}
/// <summary>
/// Serialize <see cref="OpenApiReference"/> to Open Api v3.0.
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
if (Type == ReferenceType.Tag)
{
// Write the string value only
writer.WriteValue(ReferenceV3);
return;
}
if (Type == ReferenceType.SecurityScheme)
{
// Write the string as property name
writer.WritePropertyName(ReferenceV3);
return;
}
writer.WriteStartObject();
// $ref
writer.WriteProperty(OpenApiConstants.DollarRef, ReferenceV3);
writer.WriteEndObject();
}
/// <summary>
/// Serialize <see cref="OpenApiReference"/> to Open Api v2.0.
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
if (Type == ReferenceType.Tag)
{
// Write the string value only
writer.WriteValue(ReferenceV2);
return;
}
if (Type == ReferenceType.SecurityScheme)
{
// Write the string as property name
writer.WritePropertyName(ReferenceV2);
return;
}
writer.WriteStartObject();
// $ref
writer.WriteProperty(OpenApiConstants.DollarRef, ReferenceV2);
writer.WriteEndObject();
}
private string GetExternalReference()
{
if (Id != null)
{
return ExternalResource + "#/" + Id;
}
return ExternalResource;
}
private string GetReferenceTypeNameAsV2(ReferenceType type)
{
switch (type)
{
case ReferenceType.Schema:
return OpenApiConstants.Definitions;
case ReferenceType.Parameter:
return OpenApiConstants.Parameters;
case ReferenceType.Response:
return OpenApiConstants.Responses;
case ReferenceType.Header:
return OpenApiConstants.Headers;
case ReferenceType.Tag:
return OpenApiConstants.Tags;
case ReferenceType.SecurityScheme:
return OpenApiConstants.SecurityDefinitions;
default:
throw new OpenApiException(string.Format(SRResource.ReferenceTypeNotSupportedV2, type));
}
}
}
}

View file

@ -1,88 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Collections.Generic;
using System.Linq;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// Request Body Object
/// </summary>
public class OpenApiRequestBody : IOpenApiReferenceable, IOpenApiExtensible
{
/// <summary>
/// Reference object.
/// </summary>
public OpenApiReference Reference { get; set; }
/// <summary>
/// A brief description of the request body. This could contain examples of use.
/// CommonMark syntax MAY be used for rich text representation.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Determines if the request body is required in the request. Defaults to false.
/// </summary>
public bool Required { get; set; }
/// <summary>
/// REQUIRED. The content of the request body. The key is a media type or media type range and the value describes it.
/// For requests that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/*
/// </summary>
public IDictionary<string, OpenApiMediaType> Content { get; set; }
/// <summary>
/// This object MAY be extended with Specification Extensions.
/// </summary>
public IDictionary<string, IOpenApiAny> Extensions { get; set; }
/// <summary>
/// Serialize <see cref="OpenApiRequestBody"/> to Open Api v3.0
/// </summary>
public void WriteAsV3(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
if (Reference != null)
{
Reference.SerializeAsV3(writer);
}
else
{
writer.WriteStartObject();
// description
writer.WriteProperty(OpenApiConstants.Description, Description);
// content
writer.WriteRequiredMap(OpenApiConstants.Content, Content, (w, c) => c.SerializeAsV3(w));
// required
writer.WriteProperty(OpenApiConstants.Required, Required, false);
// extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
}
/// <summary>
/// Serialize <see cref="OpenApiRequestBody"/> to Open Api v2.0
/// </summary>
public void WriteAsV2(IOpenApiWriter writer)
{
// RequestBody object does not exist in V2.
}
}
}

View file

@ -1,142 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Linq;
using System.Collections.Generic;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// Response object.
/// </summary>
public class OpenApiResponse : IOpenApiSerializable, IOpenApiReferenceable, IOpenApiExtensible
{
/// <summary>
/// REQUIRED. A short description of the response.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Maps a header name to its definition.
/// </summary>
public IDictionary<string, OpenApiHeader> Headers { get; set; }
/// <summary>
/// A map containing descriptions of potential response payloads.
/// The key is a media type or media type range and the value describes it.
/// </summary>
public IDictionary<string, OpenApiMediaType> Content { get; set; }
/// <summary>
/// A map of operations links that can be followed from the response.
/// The key of the map is a short name for the link,
/// following the naming constraints of the names for Component Objects.
/// </summary>
public IDictionary<string, OpenApiLink> Links { get; set; }
/// <summary>
/// This object MAY be extended with Specification Extensions.
/// </summary>
public IDictionary<string, IOpenApiAny> Extensions { get; set; }
/// <summary>
/// Reference pointer.
/// </summary>
public OpenApiReference Reference
{
get; set;
}
/// <summary>
/// Serialize <see cref="OpenApiResponse"/> to Open Api v3.0.
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
if (Reference != null)
{
Reference.SerializeAsV3(writer);
}
else
{
writer.WriteStartObject();
// description
writer.WriteProperty(OpenApiConstants.Description, Description);
// headers
writer.WriteOptionalMap(OpenApiConstants.Headers, Headers, (w, h) => h.SerializeAsV3(w));
// content
writer.WriteOptionalMap(OpenApiConstants.Content, Content, (w, c) => c.SerializeAsV3(w));
// links
writer.WriteOptionalMap(OpenApiConstants.Links, Links, (w, l) => l.SerializeAsV3(w));
// extension
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
}
/// <summary>
/// Serialize <see cref="OpenApiResponse"/> to Open Api v2.0.
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
if (Reference != null)
{
Reference.SerializeAsV2(writer);
}
else
{
writer.WriteStartObject();
// description
writer.WriteProperty(OpenApiConstants.Description, Description);
if (Content != null)
{
var mediatype = Content.FirstOrDefault();
if (mediatype.Value != null)
{
// schema
writer.WriteOptionalObject(OpenApiConstants.Schema, mediatype.Value.Schema, (w, s) => s.SerializeAsV2(w));
// examples
if (mediatype.Value.Example != null)
{
writer.WritePropertyName(OpenApiConstants.Examples);
writer.WriteStartObject();
writer.WritePropertyName(mediatype.Key);
writer.WriteValue(mediatype.Value.Example);
writer.WriteEndObject();
}
}
}
// headers
writer.WriteOptionalMap(OpenApiConstants.Headers, Headers, (w, h) => h.SerializeAsV2(w));
// extension
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
}
}
}

View file

@ -1,14 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// Responses object.
/// </summary>
public class OpenApiResponses : OpenApiExtensibleDictionary<OpenApiResponse>
{
}
}

View file

@ -1,547 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Collections.Generic;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// Schema Object.
/// </summary>
public class OpenApiSchema : IOpenApiSerializable, IOpenApiReferenceable, IOpenApiExtensible
{
/// <summary>
/// Follow JSON Schema definition. Short text providing information about the data.
/// </summary>
public string Title { get; set; }
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// Value MUST be a string. Multiple types via an array are not supported.
/// </summary>
public string Type { get; set; }
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// While relying on JSON Schema's defined formats,
/// the OAS offers a few additional predefined formats.
/// </summary>
public string Format { get; set; }
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// CommonMark syntax MAY be used for rich text representation.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// </summary>
public decimal? Maximum { get; set; }
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// </summary>
public bool? ExclusiveMaximum { get; set; }
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// </summary>
public decimal? Minimum { get; set; }
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// </summary>
public bool? ExclusiveMinimum { get; set; }
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// </summary>
public int? MaxLength { get; set; }
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// </summary>
public int? MinLength { get; set; }
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// This string SHOULD be a valid regular expression, according to the ECMA 262 regular expression dialect
/// </summary>
public string Pattern { get; set; }
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// </summary>
public decimal? MultipleOf { get; set; }
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// The default value represents what would be assumed by the consumer of the input as the value of the schema if one is not provided.
/// Unlike JSON Schema, the value MUST conform to the defined type for the Schema Object defined at the same level.
/// For example, if type is string, then default can be "foo" but cannot be 1.
/// </summary>
public IOpenApiAny Default { get; set; }
/// <summary>
/// Relevant only for Schema "properties" definitions. Declares the property as "read only".
/// This means that it MAY be sent as part of a response but SHOULD NOT be sent as part of the request.
/// If the property is marked as readOnly being true and is in the required list,
/// the required will take effect on the response only.
/// A property MUST NOT be marked as both readOnly and writeOnly being true.
/// Default value is false.
/// </summary>
public bool ReadOnly { get; set; }
/// <summary>
/// Relevant only for Schema "properties" definitions. Declares the property as "write only".
/// Therefore, it MAY be sent as part of a request but SHOULD NOT be sent as part of the response.
/// If the property is marked as writeOnly being true and is in the required list,
/// the required will take effect on the request only.
/// A property MUST NOT be marked as both readOnly and writeOnly being true.
/// Default value is false.
/// </summary>
public bool WriteOnly { get; set; }
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
/// </summary>
public IList<OpenApiSchema> AllOf { get; set; }
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
/// </summary>
public IList<OpenApiSchema> OneOf { get; set; }
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
/// </summary>
public IList<OpenApiSchema> AnyOf { get; set; }
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
/// </summary>
public OpenApiSchema Not { get; set; }
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// </summary>
public IList<string> Required { get; set; }
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// Value MUST be an object and not an array. Inline or referenced schema MUST be of a Schema Object
/// and not a standard JSON Schema. items MUST be present if the type is array.
/// </summary>
public OpenApiSchema Items { get; set; }
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// </summary>
public int? MaxItems { get; set; }
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// </summary>
public int? MinItems { get; set; }
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// </summary>
public bool? UniqueItems { get; set; }
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// Property definitions MUST be a Schema Object and not a standard JSON Schema (inline or referenced).
/// </summary>
public IDictionary<string, OpenApiSchema> Properties { get; set; }
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// </summary>
public int? MaxProperties { get; set; }
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// </summary>
public int? MinProperties { get; set; }
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// Value can be boolean or object. Inline or referenced schema
/// MUST be of a Schema Object and not a standard JSON Schema.
/// </summary>
public OpenApiSchema AdditionalProperties { get; set; }
/// <summary>
/// Adds support for polymorphism. The discriminator is an object name that is used to differentiate
/// between other schemas which may satisfy the payload description.
/// </summary>
public OpenApiDiscriminator Discriminator { get; set; }
/// <summary>
/// A free-form property to include an example of an instance for this schema.
/// To represent examples that cannot be naturally represented in JSON or YAML,
/// a string value can be used to contain the example with escaping where necessary.
/// </summary>
public IOpenApiAny Example { get; set; }
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// </summary>
public IList<IOpenApiAny> Enum { get; set; } = new List<IOpenApiAny>();
/// <summary>
/// Allows sending a null value for the defined schema. Default value is false.
/// </summary>
public bool Nullable { get; set; }
/// <summary>
/// Additional external documentation for this schema.
/// </summary>
public OpenApiExternalDocs ExternalDocs { get; set; }
/// <summary>
/// Specifies that a schema is deprecated and SHOULD be transitioned out of usage.
/// Default value is false.
/// </summary>
public bool Deprecated { get; set; }
/// <summary>
/// This MAY be used only on properties schemas. It has no effect on root schemas.
/// Adds additional metadata to describe the XML representation of this property.
/// </summary>
public OpenApiXml Xml { get; set; }
/// <summary>
/// This object MAY be extended with Specification Extensions.
/// </summary>
public IDictionary<string, IOpenApiAny> Extensions { get; set; }
/// <summary>
/// Reference object.
/// </summary>
public OpenApiReference Reference { get; set; }
/// <summary>
/// Serialize <see cref="OpenApiSchema"/> to Open Api v3.0
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
if (Reference != null)
{
Reference.SerializeAsV3(writer);
return;
}
writer.WriteStartObject();
// title
writer.WriteProperty(OpenApiConstants.Title, Title);
// multipleOf
writer.WriteProperty(OpenApiConstants.MultipleOf, MultipleOf);
// maximum
writer.WriteProperty(OpenApiConstants.Maximum, Maximum);
// exclusiveMaximum
writer.WriteProperty(OpenApiConstants.ExclusiveMaximum, ExclusiveMaximum);
// minimum
writer.WriteProperty(OpenApiConstants.Minimum, Minimum);
// exclusiveMinimum
writer.WriteProperty(OpenApiConstants.ExclusiveMinimum, ExclusiveMinimum);
// maxLength
writer.WriteProperty(OpenApiConstants.MaxLength, MaxLength);
// minLength
writer.WriteProperty(OpenApiConstants.MinLength, MinLength);
// pattern
writer.WriteProperty(OpenApiConstants.Pattern, Pattern);
// maxItems
writer.WriteProperty(OpenApiConstants.MaxItems, MaxItems);
// minItems
writer.WriteProperty(OpenApiConstants.MinItems, MinItems);
// uniqueItems
writer.WriteProperty(OpenApiConstants.UniqueItems, UniqueItems);
// maxProperties
writer.WriteProperty(OpenApiConstants.MaxProperties, MaxProperties);
// minProperties
writer.WriteProperty(OpenApiConstants.MinProperties, MinProperties);
// required
writer.WriteOptionalCollection(OpenApiConstants.Required, Required, (w, s) => w.WriteValue(s));
// enum
writer.WriteOptionalCollection(OpenApiConstants.Enum, Enum, (nodeWriter, s) => nodeWriter.WriteAny(s));
// type
writer.WriteProperty(OpenApiConstants.Type, Type);
// allOf
writer.WriteOptionalCollection(OpenApiConstants.AllOf, AllOf, (w, s) => s.SerializeAsV3(w));
// anyOf
writer.WriteOptionalCollection(OpenApiConstants.AnyOf, AnyOf, (w, s) => s.SerializeAsV3(w));
// oneOf
writer.WriteOptionalCollection(OpenApiConstants.OneOf, OneOf, (w, s) => s.SerializeAsV3(w));
// not
writer.WriteOptionalObject(OpenApiConstants.Not, Not, (w, s) => s.SerializeAsV3(w));
// items
writer.WriteOptionalObject(OpenApiConstants.Items, Items, (w, s) => s.SerializeAsV3(w));
// properties
writer.WriteOptionalMap(OpenApiConstants.Properties, Properties, (w, s) => s.SerializeAsV3(w));
// additionalProperties
writer.WriteOptionalObject(OpenApiConstants.AdditionalProperties, AdditionalProperties, (w, s) => s.SerializeAsV3(w));
// description
writer.WriteProperty(OpenApiConstants.Description, Description);
// format
writer.WriteProperty(OpenApiConstants.Format, Format);
// default
writer.WriteOptionalObject(OpenApiConstants.Default, Default, (w, d) => w.WriteAny(d));
// nullable
writer.WriteProperty(OpenApiConstants.Nullable, Nullable, false);
// discriminator
writer.WriteOptionalObject(OpenApiConstants.Discriminator, Discriminator, (w, s) => s.SerializeAsV3(w));
// readOnly
writer.WriteProperty(OpenApiConstants.ReadOnly, ReadOnly, false);
// writeOnly
writer.WriteProperty(OpenApiConstants.WriteOnly, WriteOnly, false);
// xml
writer.WriteOptionalObject(OpenApiConstants.Xml, Xml, (w, s) => s.SerializeAsV2(w));
// externalDocs
writer.WriteOptionalObject(OpenApiConstants.ExternalDocs, ExternalDocs, (w, s) => s.SerializeAsV3(w));
// example
writer.WriteOptionalObject(OpenApiConstants.Example, Example, (w, e) => w.WriteAny(e));
// deprecated
writer.WriteProperty(OpenApiConstants.Deprecated, Deprecated, false);
// extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
/// <summary>
/// Serialize <see cref="OpenApiSchema"/> to Open Api v2.0
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
if (Reference != null)
{
Reference.SerializeAsV2(writer);
return;
}
writer.WriteStartObject();
WriteAsSchemaProperties(writer);
writer.WriteEndObject();
}
internal void WriteAsItemsProperties(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
// type
writer.WriteProperty(OpenApiConstants.Type, Type);
// format
writer.WriteProperty(OpenApiConstants.Format, Format);
// items
writer.WriteOptionalObject(OpenApiConstants.Items, Items, (w, s) => s.SerializeAsV2(w));
// collectionFormat
// We need information from style in parameter to populate this.
// The best effort we can make is to pull this information from the first parameter
// that leverages this schema. However, that in itself may not be as simple
// as the schema directly under parameter might be referencing one in the Components,
// so we will need to do a full scan of the object before we can write the value for
// this property. This is not supported yet, so we will skip this property at the moment.
// default
writer.WriteOptionalObject(OpenApiConstants.Default, Default, (w, d) => w.WriteAny(d));
// maximum
writer.WriteProperty(OpenApiConstants.Maximum, Maximum);
// exclusiveMaximum
writer.WriteProperty(OpenApiConstants.ExclusiveMaximum, ExclusiveMaximum);
// minimum
writer.WriteProperty(OpenApiConstants.Minimum, Minimum);
// exclusiveMinimum
writer.WriteProperty(OpenApiConstants.ExclusiveMinimum, ExclusiveMinimum);
// maxLength
writer.WriteProperty(OpenApiConstants.MaxLength, MaxLength);
// minLength
writer.WriteProperty(OpenApiConstants.MinLength, MinLength);
// pattern
writer.WriteProperty(OpenApiConstants.Pattern, Pattern);
// maxItems
writer.WriteProperty(OpenApiConstants.MaxItems, MaxItems);
// minItems
writer.WriteProperty(OpenApiConstants.MinItems, MinItems);
// enum
writer.WriteOptionalCollection(OpenApiConstants.Enum, Enum, (w, s) => w.WriteAny(s));
// multipleOf
writer.WriteProperty(OpenApiConstants.MultipleOf, MultipleOf);
// extensions
writer.WriteExtensions(Extensions);
}
internal void WriteAsSchemaProperties(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
// format
writer.WriteProperty(OpenApiConstants.Format, Format);
// title
writer.WriteProperty(OpenApiConstants.Title, Title);
// description
writer.WriteProperty(OpenApiConstants.Description, Description);
// default
writer.WriteOptionalObject(OpenApiConstants.Default, Default, (w, d) => w.WriteAny(d));
// multipleOf
writer.WriteProperty(OpenApiConstants.MultipleOf, MultipleOf);
// maximum
writer.WriteProperty(OpenApiConstants.Maximum, Maximum);
// exclusiveMaximum
writer.WriteProperty(OpenApiConstants.ExclusiveMaximum, ExclusiveMaximum);
// minimum
writer.WriteProperty(OpenApiConstants.Minimum, Minimum);
// exclusiveMinimum
writer.WriteProperty(OpenApiConstants.ExclusiveMinimum, ExclusiveMinimum);
// maxLength
writer.WriteProperty(OpenApiConstants.MaxLength, MaxLength);
// minLength
writer.WriteProperty(OpenApiConstants.MinLength, MinLength);
// pattern
writer.WriteProperty(OpenApiConstants.Pattern, Pattern);
// maxItems
writer.WriteProperty(OpenApiConstants.MaxItems, MaxItems);
// minItems
writer.WriteProperty(OpenApiConstants.MinItems, MinItems);
// uniqueItems
writer.WriteProperty(OpenApiConstants.UniqueItems, UniqueItems);
// maxProperties
writer.WriteProperty(OpenApiConstants.MaxProperties, MaxProperties);
// minProperties
writer.WriteProperty(OpenApiConstants.MinProperties, MinProperties);
// required
writer.WriteOptionalCollection(OpenApiConstants.Required, Required, (w, s) => w.WriteValue(s));
// enum
writer.WriteOptionalCollection(OpenApiConstants.Enum, Enum, (w, s) => w.WriteAny(s));
// type
writer.WriteProperty(OpenApiConstants.Type, Type);
// items
writer.WriteOptionalObject(OpenApiConstants.Items, Items, (w, s) => s.SerializeAsV2(w));
// allOf
writer.WriteOptionalCollection(OpenApiConstants.AllOf, AllOf, (w, s) => s.SerializeAsV2(w));
// properties
writer.WriteOptionalMap(OpenApiConstants.Properties, Properties, (w, s) => s.SerializeAsV2(w));
// additionalProperties
writer.WriteOptionalObject(OpenApiConstants.AdditionalProperties, AdditionalProperties, (w, s) => s.SerializeAsV2(w));
// discriminator
writer.WriteProperty(OpenApiConstants.Discriminator, Discriminator?.PropertyName);
// readOnly
writer.WriteProperty(OpenApiConstants.ReadOnly, ReadOnly, false);
// xml
writer.WriteOptionalObject(OpenApiConstants.Xml, Xml, (w, s) => s.SerializeAsV2(w));
// externalDocs
writer.WriteOptionalObject(OpenApiConstants.ExternalDocs, ExternalDocs, (w, s) => s.SerializeAsV2(w));
// example
writer.WriteOptionalObject(OpenApiConstants.Example, Example, (w, e) => w.WriteAny(e));
// extensions
writer.WriteExtensions(Extensions);
}
}
}

View file

@ -1,135 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Collections.Generic;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// Security Requirement Object.
/// Each name MUST correspond to a security scheme which is declared in
/// the Security Schemes under the Components Object.
/// If the security scheme is of type "oauth2" or "openIdConnect",
/// then the value is a list of scope names required for the execution.
/// For other security scheme types, the array MUST be empty.
/// </summary>
public class OpenApiSecurityRequirement : Dictionary<OpenApiSecurityScheme, IList<string>>,
IOpenApiSerializable
{
/// <summary>
/// Initializes the <see cref="OpenApiSecurityRequirement"/> class.
/// This constructor ensures that only Reference.Id is considered when two dictionary keys
/// of type <see cref="OpenApiSecurityScheme"/> are compared.
/// </summary>
public OpenApiSecurityRequirement()
: base(new OpenApiSecuritySchemeReferenceEqualityComparer())
{
}
/// <summary>
/// Serialize <see cref="OpenApiSecurityRequirement"/> to Open Api v3.0
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
writer.WriteStartObject();
foreach (var securitySchemeAndScopesValuePair in this)
{
var securityScheme = securitySchemeAndScopesValuePair.Key;
var scopes = securitySchemeAndScopesValuePair.Value;
securityScheme.SerializeAsV3(writer);
writer.WriteStartArray();
foreach (var scope in scopes)
{
writer.WriteValue(scope);
}
writer.WriteEndArray();
}
writer.WriteEndObject();
}
/// <summary>
/// Serialize <see cref="OpenApiSecurityRequirement"/> to Open Api v2.0
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
writer.WriteStartObject();
foreach (var securitySchemeAndScopesValuePair in this)
{
var securityScheme = securitySchemeAndScopesValuePair.Key;
var scopes = securitySchemeAndScopesValuePair.Value;
securityScheme.SerializeAsV2(writer);
writer.WriteStartArray();
foreach (var scope in scopes)
{
writer.WriteValue(scope);
}
writer.WriteEndArray();
}
writer.WriteEndObject();
}
/// <summary>
/// Comparer for OpenApiSecurityScheme that only considers the Id in the Reference
/// (i.e. the string that will actually be displayed in the written document)
/// </summary>
private class OpenApiSecuritySchemeReferenceEqualityComparer : IEqualityComparer<OpenApiSecurityScheme>
{
/// <summary>
/// Determines whether the specified objects are equal.
/// </summary>
public bool Equals(OpenApiSecurityScheme x, OpenApiSecurityScheme y)
{
if (x == null && y == null)
{
return true;
}
if (x == null || y == null)
{
return false;
}
if (x.Reference == null || y.Reference == null)
{
return false;
}
return x.Reference.Id == y.Reference.Id;
}
/// <summary>
/// Returns a hash code for the specified object.
/// </summary>
public int GetHashCode(OpenApiSecurityScheme obj)
{
return obj?.Reference?.Id == null ? 0 : obj.Reference.Id.GetHashCode();
}
}
}
}

View file

@ -1,243 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
using System.Collections.Generic;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Extensions;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// Security Scheme Object.
/// </summary>
public class OpenApiSecurityScheme : IOpenApiSerializable, IOpenApiReferenceable, IOpenApiExtensible
{
/// <summary>
/// REQUIRED. The type of the security scheme. Valid values are "apiKey", "http", "oauth2", "openIdConnect".
/// </summary>
public SecuritySchemeType Type { get; set; }
/// <summary>
/// A short description for security scheme. CommonMark syntax MAY be used for rich text representation.
/// </summary>
public string Description { get; set; }
/// <summary>
/// REQUIRED. The name of the header, query or cookie parameter to be used.
/// </summary>
public string Name { get; set; }
/// <summary>
/// REQUIRED. The location of the API key. Valid values are "query", "header" or "cookie".
/// </summary>
public ParameterLocation In { get; set; }
/// <summary>
/// REQUIRED. The name of the HTTP Authorization scheme to be used
/// in the Authorization header as defined in RFC7235.
/// </summary>
public string Scheme { get; set; }
/// <summary>
/// A hint to the client to identify how the bearer token is formatted.
/// Bearer tokens are usually generated by an authorization server,
/// so this information is primarily for documentation purposes.
/// </summary>
public string BearerFormat { get; set; }
/// <summary>
/// REQUIRED. An object containing configuration information for the flow types supported.
/// </summary>
public OpenApiOAuthFlows Flows { get; set; }
/// <summary>
/// REQUIRED. OpenId Connect URL to discover OAuth2 configuration values.
/// </summary>
public Uri OpenIdConnectUrl { get; set; }
/// <summary>
/// Specification Extensions.
/// </summary>
public IDictionary<string, IOpenApiAny> Extensions { get; set; }
/// <summary>
/// Reference object.
/// </summary>
public OpenApiReference Reference { get; set; }
/// <summary>
/// Serialize <see cref="OpenApiSecurityScheme"/> to Open Api v3.0
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
if (Reference != null)
{
Reference.SerializeAsV3(writer);
return;
}
writer.WriteStartObject();
// type
writer.WriteProperty(OpenApiConstants.Type, Type.GetDisplayName());
// description
writer.WriteProperty(OpenApiConstants.Description, Description);
switch (Type)
{
case SecuritySchemeType.ApiKey:
// These properties apply to apiKey type only.
// name
// in
writer.WriteProperty(OpenApiConstants.Name, Name);
writer.WriteProperty(OpenApiConstants.In, In.GetDisplayName());
break;
case SecuritySchemeType.Http:
// These properties apply to http type only.
// scheme
// bearerFormat
writer.WriteProperty(OpenApiConstants.Scheme, Scheme);
writer.WriteProperty(OpenApiConstants.BearerFormat, BearerFormat);
break;
case SecuritySchemeType.OAuth2:
// This property apply to oauth2 type only.
// flows
writer.WriteOptionalObject(OpenApiConstants.Flows, Flows, (w, o) => o.SerializeAsV3(w));
break;
case SecuritySchemeType.OpenIdConnect:
// This property apply to openIdConnect only.
// openIdConnectUrl
writer.WriteProperty(OpenApiConstants.OpenIdConnectUrl, OpenIdConnectUrl?.ToString());
break;
}
// extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
/// <summary>
/// Serialize <see cref="OpenApiSecurityScheme"/> to Open Api v2.0
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
if (Reference != null)
{
Reference.SerializeAsV2(writer);
return;
}
if (Type == SecuritySchemeType.Http && Scheme != OpenApiConstants.Basic)
{
// Bail because V2 does not support non-basic HTTP scheme
writer.WriteStartObject();
writer.WriteEndObject();
return;
}
if (Type == SecuritySchemeType.OpenIdConnect)
{
// Bail because V2 does not support OpenIdConnect
writer.WriteStartObject();
writer.WriteEndObject();
return;
}
writer.WriteStartObject();
// type
switch (Type)
{
case SecuritySchemeType.Http:
writer.WriteProperty(OpenApiConstants.Type, OpenApiConstants.Basic);
break;
case SecuritySchemeType.OAuth2:
// These properties apply to ouauth2 type only.
// flow
// authorizationUrl
// tokenUrl
// scopes
writer.WriteProperty(OpenApiConstants.Type, Type.ToString());
WriteOAuthFlowForV2(writer, Flows);
break;
case SecuritySchemeType.ApiKey:
// These properties apply to apiKey type only.
// name
// in
writer.WriteProperty(OpenApiConstants.Type, Type.ToString());
writer.WriteProperty(OpenApiConstants.Name, Name);
writer.WriteProperty(OpenApiConstants.In, In.ToString());
break;
}
// description
writer.WriteProperty(OpenApiConstants.Description, Description);
// extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
/// <summary>
/// Arbitrarily chooses one <see cref="OpenApiOAuthFlow"/> object from the <see cref="OpenApiOAuthFlows"/>
/// to populate in V2 security scheme.
/// </summary>
private static void WriteOAuthFlowForV2(IOpenApiWriter writer, OpenApiOAuthFlows flows)
{
if (flows != null)
{
if (flows.Implicit != null)
{
WriteOAuthFlowForV2(writer, OpenApiConstants.Implicit, flows.Implicit);
}
else if (flows.Password != null)
{
WriteOAuthFlowForV2(writer, OpenApiConstants.Password, flows.Password);
}
else if (flows.ClientCredentials != null)
{
WriteOAuthFlowForV2(writer, OpenApiConstants.Application, flows.ClientCredentials);
}
else if (flows.AuthorizationCode != null)
{
WriteOAuthFlowForV2(writer, OpenApiConstants.AccessCode, flows.AuthorizationCode);
}
}
}
private static void WriteOAuthFlowForV2(IOpenApiWriter writer, string flowValue, OpenApiOAuthFlow flow)
{
// flow
writer.WriteProperty(OpenApiConstants.Flow, flowValue);
// authorizationUrl
writer.WriteProperty(OpenApiConstants.AuthorizationUrl, flow.AuthorizationUrl?.ToString());
// tokenUrl
writer.WriteProperty(OpenApiConstants.TokenUrl, flow.TokenUrl?.ToString());
// scopes
writer.WriteOptionalMap(OpenApiConstants.Scopes, flow.Scopes, (w, s) => w.WriteValue(s));
}
}
}

View file

@ -1,75 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Collections.Generic;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// Server Object: an object representing a Server.
/// </summary>
public class OpenApiServer : IOpenApiSerializable, IOpenApiExtensible
{
/// <summary>
/// An optional string describing the host designated by the URL. CommonMark syntax MAY be used for rich text representation.
/// </summary>
public string Description { get; set; }
/// <summary>
/// REQUIRED. A URL to the target host. This URL supports Server Variables and MAY be relative,
/// to indicate that the host location is relative to the location where the OpenAPI document is being served.
/// Variable substitutions will be made when a variable is named in {brackets}.
/// </summary>
public string Url { get; set; }
/// <summary>
/// A map between a variable name and its value. The value is used for substitution in the server's URL template.
/// </summary>
public IDictionary<string, OpenApiServerVariable> Variables { get; set; }
/// <summary>
/// This object MAY be extended with Specification Extensions.
/// </summary>
public IDictionary<string, IOpenApiAny> Extensions { get; set; }
/// <summary>
/// Serialize <see cref="OpenApiServer"/> to Open Api v3.0
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
writer.WriteStartObject();
// url
writer.WriteProperty(OpenApiConstants.Url, Url);
// description
writer.WriteProperty(OpenApiConstants.Description, Description);
// variables
writer.WriteOptionalMap(OpenApiConstants.Variables, Variables, (w, v) => v.SerializeAsV3(w));
// specification extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
/// <summary>
/// Serialize <see cref="OpenApiServer"/> to Open Api v2.0
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
// Server object does not exist in V2.
}
}
}

View file

@ -1,74 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Collections.Generic;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// Server Variable Object.
/// </summary>
public class OpenApiServerVariable : IOpenApiSerializable, IOpenApiExtensible
{
/// <summary>
/// An optional description for the server variable. CommonMark syntax MAY be used for rich text representation.
/// </summary>
public string Description { get; set; }
/// <summary>
/// REQUIRED. The default value to use for substitution, and to send, if an alternate value is not supplied.
/// Unlike the Schema Object's default, this value MUST be provided by the consumer.
/// </summary>
public string Default { get; set; }
/// <summary>
/// An enumeration of string values to be used if the substitution options are from a limited set.
/// </summary>
public List<string> Enum { get; set; }
/// <summary>
/// This object MAY be extended with Specification Extensions.
/// </summary>
public IDictionary<string, IOpenApiAny> Extensions { get; set; }
/// <summary>
/// Serialize <see cref="OpenApiServerVariable"/> to Open Api v3.0
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
writer.WriteStartObject();
// default
writer.WriteProperty(OpenApiConstants.Default, Default);
// description
writer.WriteProperty(OpenApiConstants.Description, Description);
// enums
writer.WriteOptionalCollection(OpenApiConstants.Enum, Enum, (w, s) => w.WriteValue(s));
// specification extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
/// <summary>
/// Serialize <see cref="OpenApiServerVariable"/> to Open Api v2.0
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
// ServerVariable does not exist in V2.
}
}
}

View file

@ -1,106 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Collections.Generic;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// Tag Object.
/// </summary>
public class OpenApiTag : IOpenApiSerializable, IOpenApiReferenceable, IOpenApiExtensible
{
/// <summary>
/// The name of the tag.
/// </summary>
public string Name { get; set; }
/// <summary>
/// A short description for the tag.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Additional external documentation for this tag.
/// </summary>
public OpenApiExternalDocs ExternalDocs { get; set; }
/// <summary>
/// This object MAY be extended with Specification Extensions.
/// </summary>
public IDictionary<string, IOpenApiAny> Extensions { get; set; }
/// <summary>
/// Reference.
/// </summary>
public OpenApiReference Reference { get; set; }
/// <summary>
/// Serialize <see cref="OpenApiTag"/> to Open Api v3.0
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
// Writing tag as reference should be handled in the caller given that
// tag should always be written as string (except at the time of definition).
// regardless of whether Pointer exists. In the context of this model,
// we have no information on whether this is the time of definition.
writer.WriteStartObject();
// name
writer.WriteProperty(OpenApiConstants.Name, Name);
// description
writer.WriteProperty(OpenApiConstants.Description, Description);
// external docs
writer.WriteOptionalObject(OpenApiConstants.ExternalDocs, ExternalDocs, (w, e) => e.SerializeAsV3(w));
// extensions.
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
/// <summary>
/// Serialize <see cref="OpenApiTag"/> to Open Api v2.0
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
// Writing tag as reference should be handled in the caller given that
// tag should always be written as string (except at the time of definition).
// regardless of whether Pointer exists. In the context of this model,
// we have no information on whether this is the time of definition.
writer.WriteStartObject();
// name
writer.WriteProperty(OpenApiConstants.Name, Name);
// description
writer.WriteProperty(OpenApiConstants.Description, Description);
// external docs
writer.WriteOptionalObject(OpenApiConstants.ExternalDocs, ExternalDocs, (w, e) => e.SerializeAsV2(w));
// extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
}
}

View file

@ -1,97 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
using System.Collections.Generic;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// XML Object.
/// </summary>
public class OpenApiXml : IOpenApiSerializable, IOpenApiExtensible
{
/// <summary>
/// Replaces the name of the element/attribute used for the described schema property.
/// </summary>
public string Name { get; set; }
/// <summary>
/// The URI of the namespace definition.
/// </summary>
public Uri Namespace { get; set; }
/// <summary>
/// The prefix to be used for the name
/// </summary>
public string Prefix { get; set; }
/// <summary>
/// Declares whether the property definition translates to an attribute instead of an element.
/// Default value is false.
/// </summary>
public bool Attribute { get; set; }
/// <summary>
/// Signifies whether the array is wrapped.
/// Default value is false.
/// </summary>
public bool Wrapped { get; set; }
/// <summary>
/// Specification Extensions.
/// </summary>
public IDictionary<string, IOpenApiAny> Extensions { get; set; }
/// <summary>
/// Serialize <see cref="OpenApiXml"/> to Open Api v3.0
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
Write(writer);
}
/// <summary>
/// Serialize <see cref="OpenApiXml"/> to Open Api v2.0
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
Write(writer);
}
private void Write(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
writer.WriteStartObject();
// name
writer.WriteProperty(OpenApiConstants.Name, Name);
// namespace
writer.WriteProperty(OpenApiConstants.Namespace, Namespace?.AbsoluteUri);
// prefix
writer.WriteProperty(OpenApiConstants.Prefix, Prefix);
// attribute
writer.WriteProperty(OpenApiConstants.Attribute, Attribute, false);
// wrapped
writer.WriteProperty(OpenApiConstants.Wrapped, Wrapped, false);
// extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
}
}

View file

@ -1,63 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using Microsoft.OpenApi.Attributes;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// Operation type.
/// </summary>
public enum OperationType
{
/// <summary>
/// A definition of a GET operation on this path.
/// </summary>
[Display("get")]
Get,
/// <summary>
/// A definition of a PUT operation on this path.
/// </summary>
[Display("put")]
Put,
/// <summary>
/// A definition of a POST operation on this path.
/// </summary>
[Display("post")]
Post,
/// <summary>
/// A definition of a DELETE operation on this path.
/// </summary>
[Display("delete")]
Delete,
/// <summary>
/// A definition of a OPTIONS operation on this path.
/// </summary>
[Display("options")]
Options,
/// <summary>
/// A definition of a HEAD operation on this path.
/// </summary>
[Display("head")]
Head,
/// <summary>
/// A definition of a PATCH operation on this path.
/// </summary>
[Display("patch")]
Patch,
/// <summary>
/// A definition of a TRACE operation on this path.
/// </summary>
[Display("trace")]
Trace
}
}

View file

@ -1,40 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using Microsoft.OpenApi.Attributes;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// The location of the parameter.
/// </summary>
public enum ParameterLocation
{
/// <summary>
/// Parameters that are appended to the URL.
/// </summary>
[Display("query")]
Query,
/// <summary>
/// Custom headers that are expected as part of the request.
/// </summary>
[Display("header")]
Header,
/// <summary>
/// Used together with Path Templating,
/// where the parameter value is actually part of the operation's URL
/// </summary>
[Display("path")]
Path,
/// <summary>
/// Used to pass a specific cookie value to the API.
/// </summary>
[Display("cookie")]
Cookie
}
}

View file

@ -1,57 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using Microsoft.OpenApi.Attributes;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// The style of the parameter.
/// </summary>
public enum ParameterStyle
{
/// <summary>
/// Path-style parameters.
/// </summary>
[Display("matrix")]
Matrix,
/// <summary>
/// Label style parameters.
/// </summary>
[Display("label")]
Label,
/// <summary>
/// Form style parameters.
/// </summary>
[Display("form")]
Form,
/// <summary>
/// Simple style parameters.
/// </summary>
[Display("simple")]
Simple,
/// <summary>
/// Space separated array values.
/// </summary>
[Display("spaceDelimited")]
SpaceDelimited,
/// <summary>
/// Pipe separated array values.
/// </summary>
[Display("pipeDelimited")]
PipeDelimited,
/// <summary>
/// Provides a simple way of rendering nested objects using form parameters.
/// </summary>
[Display("deepObject")]
DeepObject
}
}

View file

@ -1,75 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using Microsoft.OpenApi.Attributes;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// The reference type.
/// </summary>
public enum ReferenceType
{
/// <summary>
/// Schema item.
/// </summary>
[Display("schemas")]
Schema,
/// <summary>
/// Responses item.
/// </summary>
[Display("responses")]
Response,
/// <summary>
/// Parameters item.
/// </summary>
[Display("parameters")]
Parameter,
/// <summary>
/// Examples item.
/// </summary>
[Display("examples")]
Example,
/// <summary>
/// RequestBodies item.
/// </summary>
[Display("requestBodies")]
RequestBody,
/// <summary>
/// Headers item.
/// </summary>
[Display("headers")]
Header,
/// <summary>
/// SecuritySchemes item.
/// </summary>
[Display("securitySchemes")]
SecurityScheme,
/// <summary>
/// Links item.
/// </summary>
[Display("links")]
Link,
/// <summary>
/// Callbacks item.
/// </summary>
[Display("callbacks")]
Callback,
/// <summary>
/// Tags item.
/// </summary>
[Display("tags")]
Tag
}
}

View file

@ -1,73 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Expressions;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// The wrapper either for <see cref="IOpenApiAny"/> or <see cref="RuntimeExpression"/>
/// </summary>
public class RuntimeExpressionAnyWrapper : IOpenApiElement
{
private IOpenApiAny _any;
private RuntimeExpression _expression;
/// <summary>
/// Gets/Sets the <see cref="IOpenApiAny"/>
/// </summary>
public IOpenApiAny Any
{
get
{
return _any;
}
set
{
_expression = null;
_any = value;
}
}
/// <summary>
/// Gets/Set the <see cref="RuntimeExpression"/>
/// </summary>
public RuntimeExpression Expression
{
get
{
return _expression;
}
set
{
_any = null;
_expression = value;
}
}
/// <summary>
/// Write <see cref="RuntimeExpressionAnyWrapper"/>
/// </summary>
public void WriteValue(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
if (_any != null)
{
writer.WriteAny(_any);
}
else if (_expression != null)
{
writer.WriteValue(_expression.Expression);
}
}
}
}

View file

@ -1,39 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using Microsoft.OpenApi.Attributes;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// The type of the security scheme
/// </summary>
public enum SecuritySchemeType
{
/// <summary>
/// Use API key
/// </summary>
[Display("apiKey")]
ApiKey,
/// <summary>
/// Use basic or bearer token authorization header.
/// </summary>
[Display("http")]
Http,
/// <summary>
/// Use OAuth2
/// </summary>
[Display("oauth2")]
OAuth2,
/// <summary>
/// Use OAuth2 with OpenId Connect URL to discover OAuth2 configuration value.
/// </summary>
[Display("openIdConnect")]
OpenIdConnect
}
}

View file

@ -1,23 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.OpenApi
{
/// <summary>
/// Represents the Open Api document format.
/// </summary>
public enum OpenApiFormat
{
/// <summary>
/// JSON format.
/// </summary>
Json,
/// <summary>
/// Yaml format.
/// </summary>
Yaml
}
}

View file

@ -1,25 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
namespace Microsoft.OpenApi
{
/// <summary>
/// Configuration settings for Open API writers.
/// </summary>
public sealed class OpenApiSerializerSettings
{
/// <summary>
/// Open Api specification version
/// </summary>
public OpenApiSpecVersion SpecVersion { get; set; } = OpenApiSpecVersion.OpenApi3_0;
/// <summary>
/// Open Api document format.
/// </summary>
public OpenApiFormat Format { get; set; } = OpenApiFormat.Json;
}
}

View file

@ -1,23 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.OpenApi
{
/// <summary>
/// Represents the Open Api specification version.
/// </summary>
public enum OpenApiSpecVersion
{
/// <summary>
/// Open Api v2.0
/// </summary>
OpenApi2_0,
/// <summary>
/// Open Api v3.0
/// </summary>
OpenApi3_0
}
}

View file

@ -1,10 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Microsoft.OpenApi.Tests")]
[assembly: InternalsVisibleTo("Microsoft.OpenApi.Readers.Tests")]

View file

@ -1,252 +0,0 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Microsoft.OpenApi.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class SRResource {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal SRResource() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.OpenApi.Properties.SRResource", typeof(SRResource).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to There must be an active scope for name &apos;{0}&apos; to be written..
/// </summary>
internal static string ActiveScopeNeededForPropertyNameWriting {
get {
return ResourceManager.GetString("ActiveScopeNeededForPropertyNameWriting", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The argument &apos;{0}&apos; is null, empty or consists only of white-space..
/// </summary>
internal static string ArgumentNullOrWhiteSpace {
get {
return ResourceManager.GetString("ArgumentNullOrWhiteSpace", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The filed name &apos;{0}&apos; of extension doesn&apos;t begin with x-..
/// </summary>
internal static string ExtensionFieldNameMustBeginWithXDash {
get {
return ResourceManager.GetString("ExtensionFieldNameMustBeginWithXDash", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Indentation level cannot be lower than 0..
/// </summary>
internal static string IndentationLevelInvalid {
get {
return ResourceManager.GetString("IndentationLevelInvalid", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The active scope must be an object scope for property name &apos;{0}&apos; to be written..
/// </summary>
internal static string ObjectScopeNeededForPropertyNameWriting {
get {
return ResourceManager.GetString("ObjectScopeNeededForPropertyNameWriting", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred while processing the Open API document..
/// </summary>
internal static string OpenApiExceptionGenericError {
get {
return ResourceManager.GetString("OpenApiExceptionGenericError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The given OpenAPI format &apos;{0}&apos; is not supported..
/// </summary>
internal static string OpenApiFormatNotSupported {
get {
return ResourceManager.GetString("OpenApiFormatNotSupported", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The object element name &apos;{0}&apos; is required..
/// </summary>
internal static string OpenApiObjectElementIsRequired {
get {
return ResourceManager.GetString("OpenApiObjectElementIsRequired", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The OpenApi element &apos;{0}&apos; is already marked as reference object..
/// </summary>
internal static string OpenApiObjectMarkAsReference {
get {
return ResourceManager.GetString("OpenApiObjectMarkAsReference", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to If the parameter location is &quot;path&quot;, this property is REQUIRED and its value MUST be true.
/// </summary>
internal static string OpenApiParameterRequiredPropertyMandatory {
get {
return ResourceManager.GetString("OpenApiParameterRequiredPropertyMandatory", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The given OpenAPI specification version &apos;{0}&apos; is not supported..
/// </summary>
internal static string OpenApiSpecVersionNotSupported {
get {
return ResourceManager.GetString("OpenApiSpecVersionNotSupported", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The type &apos;{0}&apos; is not supported in Open API document..
/// </summary>
internal static string OpenApiUnsupportedValueType {
get {
return ResourceManager.GetString("OpenApiUnsupportedValueType", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred while writing the Open API document..
/// </summary>
internal static string OpenApiWriterExceptionGenericError {
get {
return ResourceManager.GetString("OpenApiWriterExceptionGenericError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The given primitive type &apos;{0}&apos; is not supported..
/// </summary>
internal static string PrimitiveTypeNotSupported {
get {
return ResourceManager.GetString("PrimitiveTypeNotSupported", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The reference string &apos;{0}&apos; has invalid format..
/// </summary>
internal static string ReferenceHasInvalidFormat {
get {
return ResourceManager.GetString("ReferenceHasInvalidFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The reference type &apos;{0}&apos; does not suppoted in Open API v2.0..
/// </summary>
internal static string ReferenceTypeNotSupportedV2 {
get {
return ResourceManager.GetString("ReferenceTypeNotSupportedV2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The runtime expression &apos;{0}&apos; has invalid format..
/// </summary>
internal static string RuntimeExpressionHasInvalidFormat {
get {
return ResourceManager.GetString("RuntimeExpressionHasInvalidFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The runtime expression &apos;{0}&apos; should start with &apos;$&apos;.
/// </summary>
internal static string RuntimeExpressionMustBeginWithDollar {
get {
return ResourceManager.GetString("RuntimeExpressionMustBeginWithDollar", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Scope must be present to end..
/// </summary>
internal static string ScopeMustBePresentToEnd {
get {
return ResourceManager.GetString("ScopeMustBePresentToEnd", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The scope to end is expected to be of type &apos;{0}&apos; but it is of type &apos;{0}&apos;..
/// </summary>
internal static string ScopeToEndHasIncorrectType {
get {
return ResourceManager.GetString("ScopeToEndHasIncorrectType", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The source expression &apos;{0}&apos; has invalid format..
/// </summary>
internal static string SourceExpressionHasInvalidFormat {
get {
return ResourceManager.GetString("SourceExpressionHasInvalidFormat", resourceCulture);
}
}
}
}

View file

@ -1,183 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="ActiveScopeNeededForPropertyNameWriting" xml:space="preserve">
<value>There must be an active scope for name '{0}' to be written.</value>
</data>
<data name="ArgumentNullOrWhiteSpace" xml:space="preserve">
<value>The argument '{0}' is null, empty or consists only of white-space.</value>
</data>
<data name="ExtensionFieldNameMustBeginWithXDash" xml:space="preserve">
<value>The filed name '{0}' of extension doesn't begin with x-.</value>
</data>
<data name="IndentationLevelInvalid" xml:space="preserve">
<value>Indentation level cannot be lower than 0.</value>
</data>
<data name="ObjectScopeNeededForPropertyNameWriting" xml:space="preserve">
<value>The active scope must be an object scope for property name '{0}' to be written.</value>
</data>
<data name="OpenApiExceptionGenericError" xml:space="preserve">
<value>An error occurred while processing the Open API document.</value>
</data>
<data name="OpenApiFormatNotSupported" xml:space="preserve">
<value>The given OpenAPI format '{0}' is not supported.</value>
</data>
<data name="OpenApiObjectElementIsRequired" xml:space="preserve">
<value>The object element name '{0}' is required.</value>
</data>
<data name="OpenApiObjectMarkAsReference" xml:space="preserve">
<value>The OpenApi element '{0}' is already marked as reference object.</value>
</data>
<data name="OpenApiParameterRequiredPropertyMandatory" xml:space="preserve">
<value>If the parameter location is "path", this property is REQUIRED and its value MUST be true</value>
</data>
<data name="OpenApiSpecVersionNotSupported" xml:space="preserve">
<value>The given OpenAPI specification version '{0}' is not supported.</value>
</data>
<data name="OpenApiUnsupportedValueType" xml:space="preserve">
<value>The type '{0}' is not supported in Open API document.</value>
</data>
<data name="OpenApiWriterExceptionGenericError" xml:space="preserve">
<value>An error occurred while writing the Open API document.</value>
</data>
<data name="PrimitiveTypeNotSupported" xml:space="preserve">
<value>The given primitive type '{0}' is not supported.</value>
</data>
<data name="ReferenceHasInvalidFormat" xml:space="preserve">
<value>The reference string '{0}' has invalid format.</value>
</data>
<data name="ReferenceTypeNotSupportedV2" xml:space="preserve">
<value>The reference type '{0}' does not suppoted in Open API v2.0.</value>
</data>
<data name="RuntimeExpressionHasInvalidFormat" xml:space="preserve">
<value>The runtime expression '{0}' has invalid format.</value>
</data>
<data name="RuntimeExpressionMustBeginWithDollar" xml:space="preserve">
<value>The runtime expression '{0}' should start with '$'</value>
</data>
<data name="ScopeMustBePresentToEnd" xml:space="preserve">
<value>Scope must be present to end.</value>
</data>
<data name="ScopeToEndHasIncorrectType" xml:space="preserve">
<value>The scope to end is expected to be of type '{0}' but it is of type '{0}'.</value>
</data>
<data name="SourceExpressionHasInvalidFormat" xml:space="preserve">
<value>The source expression '{0}' has invalid format.</value>
</data>
</root>

View file

@ -1,25 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Collections.Generic;
using Microsoft.OpenApi.Models;
namespace Microsoft.OpenApi.Services
{
/// <summary>
/// Class containing logic to get differences between two <see cref="OpenApiDocument"/>s.
/// </summary>
public static class OpenApiComparer
{
/// <summary>
/// Compares two <see cref="OpenApiDocument"/>s and returns a list of differences.
/// </summary>
public static List<OpenApiDifference> Compare(OpenApiDocument source, OpenApiDocument target)
{
var diffs = new List<OpenApiDifference>();
return diffs;
}
}
}

View file

@ -1,16 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using Microsoft.OpenApi.Models;
namespace Microsoft.OpenApi.Services
{
/// <summary>
/// Difference point between two <see cref="OpenApiDocument"/>
/// </summary>
public class OpenApiDifference
{
}
}

View file

@ -1,34 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Collections.Generic;
using Microsoft.OpenApi.Exceptions;
using Microsoft.OpenApi.Models;
namespace Microsoft.OpenApi.Services
{
/// <summary>
/// Class containing logic to validate an Open API document object.
/// </summary>
public class OpenApiValidator : OpenApiVisitorBase
{
/// <summary>
/// Exceptions related to this validation.
/// </summary>
public List<OpenApiException> Exceptions { get; } = new List<OpenApiException>();
/// <summary>
/// Visit Open API Response element.
/// </summary>
/// <param name="response">Response element.</param>
public override void Visit(OpenApiResponse response)
{
if (string.IsNullOrEmpty(response.Description))
{
Exceptions.Add(new OpenApiException("Response must have a description"));
}
}
}
}

View file

@ -1,117 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Collections.Generic;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Models;
namespace Microsoft.OpenApi.Services
{
/// <summary>
/// Open API visitor base providing base validation logic for each <see cref="IOpenApiElement"/>
/// </summary>
public abstract class OpenApiVisitorBase
{
/// <summary>
/// Validates <see cref="OpenApiDocument"/>
/// </summary>
public virtual void Visit(OpenApiDocument doc) { }
/// <summary>
/// Validates <see cref="OpenApiInfo"/>
/// </summary>
public virtual void Visit(OpenApiInfo info) { }
/// <summary>
/// Validates list of <see cref="OpenApiServer"/>
/// </summary>
public virtual void Visit(IList<OpenApiServer> servers) { }
/// <summary>
/// Validates <see cref="OpenApiServer"/>
/// </summary>
public virtual void Visit(OpenApiServer server) { }
/// <summary>
/// Validates <see cref="OpenApiPaths"/>
/// </summary>
public virtual void Visit(OpenApiPaths paths) { }
/// <summary>
/// Validates <see cref="OpenApiPathItem"/>
/// </summary>
public virtual void Visit(OpenApiPathItem pathItem) { }
/// <summary>
/// Validates <see cref="OpenApiServerVariable"/>
/// </summary>
public virtual void Visit(OpenApiServerVariable serverVariable) { }
/// <summary>
/// Validates the operations.
/// </summary>
public virtual void Visit(IDictionary<OperationType,OpenApiOperation> operations) { }
/// <summary>
/// Validates <see cref="OpenApiOperation"/>
/// </summary>
public virtual void Visit(OpenApiOperation operation) { }
/// <summary>
/// Validates list of <see cref="OpenApiParameter"/>
/// </summary>
public virtual void Visit(IList<OpenApiParameter> parameters) { }
/// <summary>
/// Validates <see cref="OpenApiParameter"/>
/// </summary>
public virtual void Visit(OpenApiParameter parameter) { }
/// <summary>
/// Validates <see cref="OpenApiRequestBody"/>
/// </summary>
public virtual void Visit(OpenApiRequestBody requestBody) { }
/// <summary>
/// Validates responses.
/// </summary>
public virtual void Visit(IDictionary<string, OpenApiResponse> responses) { }
/// <summary>
/// Validates <see cref="OpenApiResponse"/>
/// </summary>
public virtual void Visit(OpenApiResponse response) { }
/// <summary>
/// Validates media type content.
/// </summary>
public virtual void Visit(IDictionary<string,OpenApiMediaType> content) { }
/// <summary>
/// Validates <see cref="OpenApiMediaType"/>
/// </summary>
public virtual void Visit(OpenApiMediaType mediaType) { }
/// <summary>
/// Validates the examples.
/// </summary>
public virtual void Visit(IDictionary<string, OpenApiExample> examples) { }
/// <summary>
/// Validates <see cref="OpenApiSchema"/>
/// </summary>
public virtual void Visit(OpenApiSchema schema) { }
/// <summary>
/// Validates the links.
/// </summary>
public virtual void Visit(IDictionary<string, OpenApiLink> links) { }
/// <summary>
/// Validates <see cref="OpenApiLink"/>
/// </summary>
public virtual void Visit(OpenApiLink link) { }
}
}

View file

@ -1,114 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Collections.Generic;
using Microsoft.OpenApi.Models;
namespace Microsoft.OpenApi.Services
{
/// <summary>
/// The walker to visit multiple Open API elements.
/// </summary>
public class OpenApiWalker
{
readonly OpenApiVisitorBase _visitor;
/// <summary>
/// Initializes the <see cref="OpenApiWalker"/> class.
/// </summary>
public OpenApiWalker(OpenApiVisitorBase visitor)
{
this._visitor = visitor;
}
/// <summary>
/// Walks through the <see cref="OpenApiDocument"/> and validates each element.
/// </summary>
/// <param name="doc"></param>
public void Walk(OpenApiDocument doc)
{
this._visitor.Visit(doc);
this._visitor.Visit(doc.Info);
this._visitor.Visit(doc.Servers);
if (doc.Servers != null)
{
foreach (var server in doc.Servers)
{
this._visitor.Visit(server);
foreach (var variable in server.Variables.Values)
{
this._visitor.Visit(variable);
}
}
}
this._visitor.Visit(doc.Paths);
foreach (var pathItem in doc.Paths.Values)
{
this._visitor.Visit(pathItem);
this._visitor.Visit(pathItem.Operations);
foreach (var operation in pathItem.Operations.Values)
{
this._visitor.Visit(operation);
if (operation.Parameters != null)
{
this._visitor.Visit(operation.Parameters);
foreach (var parameter in operation.Parameters)
{
this._visitor.Visit(parameter);
}
}
if (operation.RequestBody != null)
{
this._visitor.Visit(operation.RequestBody);
if (operation.RequestBody.Content != null)
{
WalkContent(operation.RequestBody.Content);
}
}
if (operation.Responses != null)
{
this._visitor.Visit(operation.Responses);
foreach (var response in operation.Responses.Values)
{
this._visitor.Visit(response);
WalkContent(response.Content);
if (response.Links != null)
{
this._visitor.Visit(response.Links);
foreach (var link in response.Links.Values)
{
this._visitor.Visit(link);
}
}
}
}
}
}
}
/// <summary>
/// Walks through each media type in content and validates.
/// </summary>
private void WalkContent(IDictionary<string, OpenApiMediaType> content)
{
if (content == null) return;
this._visitor.Visit(content);
foreach (var mediaType in content.Values)
{
this._visitor.Visit(mediaType);
this._visitor.Visit(mediaType.Examples);
this._visitor.Visit(mediaType.Schema);
}
}
}
}

View file

@ -1,79 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.OpenApi.Writers
{
/// <summary>
/// Interface for writing Open API documentation.
/// </summary>
public interface IOpenApiWriter
{
/// <summary>
/// Write the start object.
/// </summary>
void WriteStartObject();
/// <summary>
/// Write the end object.
/// </summary>
void WriteEndObject();
/// <summary>
/// Write the start array.
/// </summary>
void WriteStartArray();
/// <summary>
/// Write the end array.
/// </summary>
void WriteEndArray();
/// <summary>
/// Write the property name.
/// </summary>
void WritePropertyName(string name);
/// <summary>
/// Write the string value.
/// </summary>
void WriteValue(string value);
/// <summary>
/// Write the decimal value.
/// </summary>
void WriteValue(decimal value);
/// <summary>
/// Write the int value.
/// </summary>
void WriteValue(int value);
/// <summary>
/// Write the boolean value.
/// </summary>
void WriteValue(bool value);
/// <summary>
/// Write the null value.
/// </summary>
void WriteNull();
/// <summary>
/// Write the raw content value.
/// </summary>
void WriteRaw(string value);
/// <summary>
/// Write the object value.
/// </summary>
void WriteValue(object value);
/// <summary>
/// Flush the writer.
/// </summary>
void Flush();
}
}

View file

@ -1,219 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.IO;
namespace Microsoft.OpenApi.Writers
{
/// <summary>
/// JSON Writer.
/// </summary>
public class OpenApiJsonWriter : OpenApiWriterBase
{
/// <summary>
/// Initializes a new instance of the <see cref="OpenApiJsonWriter"/> class.
/// </summary>
/// <param name="textWriter">The text writer.</param>
public OpenApiJsonWriter(TextWriter textWriter)
: this(textWriter, new OpenApiSerializerSettings())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="OpenApiJsonWriter"/> class.
/// </summary>
/// <param name="textWriter">The text writer.</param>
/// <param name="settings">The writer settings.</param>
public OpenApiJsonWriter(TextWriter textWriter, OpenApiSerializerSettings settings)
: base(textWriter, settings)
{
}
/// <summary>
/// Base Indentation Level.
/// This denotes how many indentations are needed for the property in the base object.
/// </summary>
protected override int BaseIndentation => 1;
/// <summary>
/// Write JSON start object.
/// </summary>
public override void WriteStartObject()
{
var previousScope = CurrentScope();
var currentScope = StartScope(ScopeType.Object);
if (previousScope != null && previousScope.Type == ScopeType.Array)
{
currentScope.IsInArray = true;
if (previousScope.ObjectCount != 1)
{
Writer.Write(WriterConstants.ArrayElementSeparator);
}
Writer.WriteLine();
WriteIndentation();
}
Writer.Write(WriterConstants.StartObjectScope);
IncreaseIndentation();
}
/// <summary>
/// Write JSON end object.
/// </summary>
public override void WriteEndObject()
{
var currentScope = EndScope(ScopeType.Object);
if (currentScope.ObjectCount != 0)
{
Writer.WriteLine();
DecreaseIndentation();
WriteIndentation();
}
else
{
Writer.Write(WriterConstants.WhiteSpaceForEmptyObject);
DecreaseIndentation();
}
Writer.Write(WriterConstants.EndObjectScope);
}
/// <summary>
/// Write JSON start array.
/// </summary>
public override void WriteStartArray()
{
var previousScope = CurrentScope();
var currentScope = StartScope(ScopeType.Array);
if (previousScope != null && previousScope.Type == ScopeType.Array)
{
currentScope.IsInArray = true;
if (previousScope.ObjectCount != 1)
{
Writer.Write(WriterConstants.ArrayElementSeparator);
}
Writer.WriteLine();
WriteIndentation();
}
Writer.Write(WriterConstants.StartArrayScope);
IncreaseIndentation();
}
/// <summary>
/// Write JSON end array.
/// </summary>
public override void WriteEndArray()
{
var current = EndScope(ScopeType.Array);
if (current.ObjectCount != 0)
{
Writer.WriteLine();
DecreaseIndentation();
WriteIndentation();
}
else
{
Writer.Write(WriterConstants.WhiteSpaceForEmptyArray);
DecreaseIndentation();
}
Writer.Write(WriterConstants.EndArrayScope);
}
/// <summary>
/// Write property name.
/// </summary>
/// <param name="name">The property name.</param>
/// public override void WritePropertyName(string name)
public override void WritePropertyName(string name)
{
VerifyCanWritePropertyName(name);
var currentScope = CurrentScope();
if (currentScope.ObjectCount != 0)
{
Writer.Write(WriterConstants.ObjectMemberSeparator);
}
Writer.WriteLine();
currentScope.ObjectCount++;
WriteIndentation();
Writer.Write(WriterConstants.QuoteCharacter);
Writer.Write(name);
Writer.Write(WriterConstants.QuoteCharacter);
Writer.Write(WriterConstants.NameValueSeparator);
}
/// <summary>
/// Write string value.
/// </summary>
/// <param name="value">The string value.</param>
public override void WriteValue(string value)
{
WriteValueSeparator();
value = value.Replace("\n", "\\n");
Writer.Write(WriterConstants.QuoteCharacter);
Writer.Write(value);
Writer.Write(WriterConstants.QuoteCharacter);
}
/// <summary>
/// Write null value.
/// </summary>
public override void WriteNull()
{
Writer.Write("null");
}
/// <summary>
/// Writes a separator of a value if it's needed for the next value to be written.
/// </summary>
protected override void WriteValueSeparator()
{
if (scopes.Count == 0)
{
return;
}
var currentScope = scopes.Peek();
if (currentScope.Type == ScopeType.Array)
{
if (currentScope.ObjectCount != 0)
{
Writer.Write(WriterConstants.ArrayElementSeparator);
}
Writer.WriteLine();
WriteIndentation();
currentScope.ObjectCount++;
}
}
/// <summary>
/// Writes the content raw value.
/// </summary>
public override void WriteRaw(string value)
{
WriteValueSeparator();
Writer.Write(value);
}
}
}

View file

@ -1,204 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Collections.Generic;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Exceptions;
using Microsoft.OpenApi.Properties;
namespace Microsoft.OpenApi.Writers
{
/// <summary>
/// Extensions methods for writing the <see cref="IOpenApiAny"/>
/// </summary>
public static class OpenApiWriterAnyExtensions
{
/// <summary>
/// Write the specification extensions
/// </summary>
/// <param name="writer">The Open API writer.</param>
/// <param name="extensions">The specification extensions.</param>
public static void WriteExtensions(this IOpenApiWriter writer, IDictionary<string, IOpenApiAny> extensions)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
if (extensions != null)
{
foreach (var item in extensions)
{
writer.WritePropertyName(item.Key);
writer.WriteAny(item.Value);
}
}
}
/// <summary>
/// Write the <see cref="IOpenApiAny"/> value.
/// </summary>
/// <typeparam name="T">The Open API Any type.</typeparam>
/// <param name="writer">The Open API writer.</param>
/// <param name="any">The Any value</param>
public static void WriteAny<T>(this IOpenApiWriter writer, T any) where T : IOpenApiAny
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
if (any == null)
{
writer.WriteNull();
return;
}
switch (any.AnyType)
{
case AnyType.Array: // Array
writer.WriteArray(any as OpenApiArray);
break;
case AnyType.Object: // Object
writer.WriteObject(any as OpenApiObject);
break;
case AnyType.Primitive: // Primitive
writer.WritePrimitive(any as IOpenApiPrimitive);
break;
case AnyType.Null: // null
writer.WriteNull();
break;
default:
break;
}
}
private static void WriteArray(this IOpenApiWriter writer, OpenApiArray array)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
if (array == null)
{
throw Error.ArgumentNull(nameof(array));
}
writer.WriteStartArray();
foreach (var item in array)
{
writer.WriteAny(item);
}
writer.WriteEndArray();
}
private static void WriteObject(this IOpenApiWriter writer, OpenApiObject entity)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
if (entity == null)
{
throw Error.ArgumentNull(nameof(entity));
}
writer.WriteStartObject();
foreach (var item in entity)
{
writer.WritePropertyName(item.Key);
writer.WriteAny(item.Value);
}
writer.WriteEndObject();
}
private static void WritePrimitive(this IOpenApiWriter writer, IOpenApiPrimitive primitive)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
if (primitive == null)
{
throw Error.ArgumentNull(nameof(primitive));
}
switch (primitive.PrimitiveType)
{
case PrimitiveType.Integer:
var intValue = (OpenApiInteger)primitive;
writer.WriteValue(intValue.Value);
break;
case PrimitiveType.Long:
var longValue = (OpenApiLong)primitive;
writer.WriteValue(longValue.Value);
break;
case PrimitiveType.Float:
var floatValue = (OpenApiFloat)primitive;
writer.WriteValue(floatValue.Value);
break;
case PrimitiveType.Double:
var doubleValue = (OpenApiDouble)primitive;
writer.WriteValue(doubleValue.Value);
break;
case PrimitiveType.String:
var stringValue = (OpenApiString)primitive;
writer.WriteValue(stringValue.Value);
break;
case PrimitiveType.Byte:
var byteValue = (OpenApiByte)primitive;
writer.WriteValue(byteValue.Value);
break;
case PrimitiveType.Binary:
var binaryValue = (OpenApiBinary)primitive;
writer.WriteValue(binaryValue.Value);
break;
case PrimitiveType.Boolean:
var boolValue = (OpenApiBoolean)primitive;
writer.WriteValue(boolValue.Value);
break;
case PrimitiveType.Date:
var dateValue = (OpenApiDate)primitive;
writer.WriteValue(dateValue.Value);
break;
case PrimitiveType.DateTime:
var dateTimeValue = (OpenApiDateTime)primitive;
writer.WriteValue(dateTimeValue.Value);
break;
case PrimitiveType.Password:
var passwordValue = (OpenApiPassword)primitive;
writer.WriteValue(passwordValue.Value);
break;
default:
throw new OpenApiWriterException(
string.Format(
SRResource.PrimitiveTypeNotSupported,
primitive.PrimitiveType));
}
}
}
}

View file

@ -1,331 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.Collections.Generic;
using System.IO;
using Microsoft.OpenApi.Exceptions;
using Microsoft.OpenApi.Properties;
namespace Microsoft.OpenApi.Writers
{
/// <summary>
/// Base class for Open API writer.
/// </summary>
public abstract class OpenApiWriterBase : IOpenApiWriter
{
/// <summary>
/// The indentation string to prepand to each line for each indentation level.
/// </summary>
private const string IndentationString = " ";
/// <summary>
/// Scope of the Open API element - object, array, property.
/// </summary>
protected readonly Stack<Scope> scopes;
/// <summary>
/// Number which specifies the level of indentation.
/// </summary>
private int _indentLevel;
/// <summary>
/// Settings controlling the format and the version of the serialization.
/// </summary>
private OpenApiSerializerSettings settings;
/// <summary>
/// Initializes a new instance of the <see cref="OpenApiWriterBase"/> class.
/// </summary>
/// <param name="textWriter">The text writer.</param>
/// <param name="settings">The writer settings.</param>
public OpenApiWriterBase(TextWriter textWriter, OpenApiSerializerSettings settings)
{
Writer = textWriter;
Writer.NewLine = "\n";
scopes = new Stack<Scope>();
this.settings = settings;
}
/// <summary>
/// Base Indentation Level.
/// This denotes how many indentations are needed for the property in the base object.
/// </summary>
protected abstract int BaseIndentation { get; }
/// <summary>
/// The text writer.
/// </summary>
protected TextWriter Writer { get; }
/// <summary>
/// Write start object.
/// </summary>
public abstract void WriteStartObject();
/// <summary>
/// Write end object.
/// </summary>
public abstract void WriteEndObject();
/// <summary>
/// Write start array.
/// </summary>
public abstract void WriteStartArray();
/// <summary>
/// Write end array.
/// </summary>
public abstract void WriteEndArray();
/// <summary>
/// Write the start property.
/// </summary>
public abstract void WritePropertyName(string name);
/// <summary>
/// Writes a separator of a value if it's needed for the next value to be written.
/// </summary>
protected abstract void WriteValueSeparator();
/// <summary>
/// Write null value.
/// </summary>
public abstract void WriteNull();
/// <summary>
/// Write content raw value.
/// </summary>
public abstract void WriteRaw(string value);
/// <summary>
/// Flush the writer.
/// </summary>
public void Flush()
{
Writer.Flush();
}
/// <summary>
/// Write string value.
/// </summary>
/// <param name="value">The string value.</param>
public abstract void WriteValue(string value);
/// <summary>
/// Write decimal value.
/// </summary>
/// <param name="value">The decimal value.</param>
public virtual void WriteValue(decimal value)
{
WriteValueSeparator();
Writer.Write(value);
}
/// <summary>
/// Write integer value.
/// </summary>
/// <param name="value">The integer value.</param>
public virtual void WriteValue(int value)
{
WriteValueSeparator();
Writer.Write(value);
}
/// <summary>
/// Write boolean value.
/// </summary>
/// <param name="value">The boolean value.</param>
public virtual void WriteValue(bool value)
{
WriteValueSeparator();
Writer.Write(value.ToString().ToLower());
}
/// <summary>
/// Write object value.
/// </summary>
/// <param name="value">The object value.</param>
public virtual void WriteValue(object value)
{
if (value == null)
{
WriteNull();
return;
}
var type = value.GetType();
if (type == typeof(string))
{
WriteValue((string)(value));
}
else if (type == typeof(int) || type == typeof(int?))
{
WriteValue((int)value);
}
else if (type == typeof(bool) || type == typeof(bool?))
{
WriteValue((bool)value);
}
else if (type == typeof(decimal) || type == typeof(decimal?))
{
WriteValue((decimal)value);
}
else
{
throw new OpenApiWriterException(string.Format(SRResource.OpenApiUnsupportedValueType, type.FullName));
}
}
/// <summary>
/// Increases the level of indentation applied to the output.
/// </summary>
public virtual void IncreaseIndentation()
{
_indentLevel++;
}
/// <summary>
/// Decreases the level of indentation applied to the output.
/// </summary>
public virtual void DecreaseIndentation()
{
if (_indentLevel == 0)
{
throw new OpenApiWriterException(SRResource.IndentationLevelInvalid);
}
if (_indentLevel < 1)
{
_indentLevel = 0;
}
else
{
_indentLevel--;
}
}
/// <summary>
/// Write the indentation.
/// </summary>
public virtual void WriteIndentation()
{
for (var i = 0; i < (BaseIndentation + _indentLevel - 1); i++)
{
Writer.Write(IndentationString);
}
}
/// <summary>
/// Get current scope.
/// </summary>
/// <returns></returns>
protected Scope CurrentScope()
{
return scopes.Count == 0 ? null : scopes.Peek();
}
/// <summary>
/// Start the scope given the scope type.
/// </summary>
/// <param name="type">The scope type to start.</param>
protected Scope StartScope(ScopeType type)
{
if (scopes.Count != 0)
{
var currentScope = scopes.Peek();
currentScope.ObjectCount++;
}
var scope = new Scope(type);
scopes.Push(scope);
return scope;
}
/// <summary>
/// End the scope of the given scope type.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
protected Scope EndScope(ScopeType type)
{
if (scopes.Count == 0)
{
throw new OpenApiWriterException(SRResource.ScopeMustBePresentToEnd);
}
if (scopes.Peek().Type != type)
{
throw new OpenApiWriterException(
string.Format(
SRResource.ScopeToEndHasIncorrectType,
type,
scopes.Peek().Type));
}
return scopes.Pop();
}
/// <summary>
/// Whether the current scope is the top level (outermost) scope.
/// </summary>
protected bool IsTopLevelScope()
{
return scopes.Count == 1;
}
/// <summary>
/// Whether the current scope is an object scope.
/// </summary>
protected bool IsObjectScope()
{
return IsScopeType(ScopeType.Object);
}
/// <summary>
/// Whether the current scope is an array scope.
/// </summary>
/// <returns></returns>
protected bool IsArrayScope()
{
return IsScopeType(ScopeType.Array);
}
private bool IsScopeType(ScopeType type)
{
if (scopes.Count == 0)
{
return false;
}
return scopes.Peek().Type == type;
}
/// <summary>
/// Verifies whether a property name can be written based on whether
/// the property name is a valid string and whether the current scope is an object scope.
/// </summary>
/// <param name="name">property name</param>
protected void VerifyCanWritePropertyName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
throw Error.ArgumentNullOrWhiteSpace(nameof(name));
}
if (scopes.Count == 0)
{
throw new OpenApiWriterException(string.Format(SRResource.ActiveScopeNeededForPropertyNameWriting, name));
}
if (scopes.Peek().Type != ScopeType.Object)
{
throw new OpenApiWriterException(string.Format(SRResource.ObjectScopeNeededForPropertyNameWriting, name));
}
}
}
}

View file

@ -1,353 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.OpenApi.Interfaces;
namespace Microsoft.OpenApi.Writers
{
/// <summary>
/// Extension methods for writing Open API documentation.
/// </summary>
public static class OpenApiWriterExtensions
{
/// <summary>
/// Write a string property.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="name">The property name.</param>
/// <param name="value">The property value.</param>
public static void WriteProperty(this IOpenApiWriter writer, string name, string value)
{
if (string.IsNullOrEmpty(value))
{
return;
}
CheckArguments(writer, name);
writer.WritePropertyName(name);
writer.WriteValue(value);
}
/// <summary>
/// Write a boolean property.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="name">The property name.</param>
/// <param name="value">The property value.</param>
/// <param name="defaultValue">The default boolean value.</param>
public static void WriteProperty(this IOpenApiWriter writer, string name, bool value, bool defaultValue = false)
{
if (value == defaultValue)
{
return;
}
CheckArguments(writer, name);
writer.WritePropertyName(name);
writer.WriteValue(value);
}
/// <summary>
/// Write a boolean property.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="name">The property name.</param>
/// <param name="value">The property value.</param>
/// <param name="defaultValue">The default boolean value.</param>
public static void WriteProperty(
this IOpenApiWriter writer,
string name,
bool? value,
bool defaultValue = false)
{
if (value == null || value.Value == defaultValue)
{
return;
}
CheckArguments(writer, name);
writer.WritePropertyName(name);
writer.WriteValue(value.Value);
}
/// <summary>
/// Write a primitive property.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="name">The property name.</param>
/// <param name="value">The property value.</param>
public static void WriteProperty<T>(this IOpenApiWriter writer, string name, T? value)
where T : struct
{
if (value == null)
{
return;
}
writer.WriteProperty(name, value.Value);
}
/// <summary>
/// Write a string/number property.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="name">The property name.</param>
/// <param name="value">The property value.</param>
public static void WriteProperty<T>(this IOpenApiWriter writer, string name, T value)
where T : struct
{
CheckArguments(writer, name);
writer.WritePropertyName(name);
writer.WriteValue(value);
}
/// <summary>
/// Write the optional Open API object/element.
/// </summary>
/// <typeparam name="T">The Open API element type. <see cref="IOpenApiElement"/></typeparam>
/// <param name="writer">The Open API writer.</param>
/// <param name="name">The property name.</param>
/// <param name="value">The property value.</param>
/// <param name="action">The proprety value writer action.</param>
public static void WriteOptionalObject<T>(
this IOpenApiWriter writer,
string name,
T value,
Action<IOpenApiWriter, T> action)
where T : IOpenApiElement
{
if (value != null)
{
writer.WriteRequiredObject(name, value, action);
}
}
/// <summary>
/// Write the required Open API object/element.
/// </summary>
/// <typeparam name="T">The Open API element type. <see cref="IOpenApiElement"/></typeparam>
/// <param name="writer">The Open API writer.</param>
/// <param name="name">The property name.</param>
/// <param name="value">The property value.</param>
/// <param name="action">The proprety value writer action.</param>
public static void WriteRequiredObject<T>(
this IOpenApiWriter writer,
string name,
T value,
Action<IOpenApiWriter, T> action)
where T : IOpenApiElement
{
CheckArguments(writer, name, action);
writer.WritePropertyName(name);
if (value != null)
{
action(writer, value);
}
}
/// <summary>
/// Write the optional of collection string.
/// </summary>
/// <param name="writer">The Open API writer.</param>
/// <param name="name">The property name.</param>
/// <param name="elements">The collection values.</param>
/// <param name="action">The collection string writer action.</param>
public static void WriteOptionalCollection(
this IOpenApiWriter writer,
string name,
IEnumerable<string> elements,
Action<IOpenApiWriter, string> action)
{
if (elements != null && elements.Any())
{
writer.WriteCollectionInternal(name, elements, action);
}
}
/// <summary>
/// Write the optional Open API object/element collection.
/// </summary>
/// <typeparam name="T">The Open API element type. <see cref="IOpenApiElement"/></typeparam>
/// <param name="writer">The Open API writer.</param>
/// <param name="name">The property name.</param>
/// <param name="elements">The collection values.</param>
/// <param name="action">The collection element writer action.</param>
public static void WriteOptionalCollection<T>(
this IOpenApiWriter writer,
string name,
IEnumerable<T> elements,
Action<IOpenApiWriter, T> action)
where T : IOpenApiElement
{
if (elements != null && elements.Any())
{
writer.WriteCollectionInternal(name, elements, action);
}
}
/// <summary>
/// Write the required Open API object/element collection.
/// </summary>
/// <typeparam name="T">The Open API element type. <see cref="IOpenApiElement"/></typeparam>
/// <param name="writer">The Open API writer.</param>
/// <param name="name">The property name.</param>
/// <param name="elements">The collection values.</param>
/// <param name="action">The collection element writer action.</param>
public static void WriteRequiredCollection<T>(
this IOpenApiWriter writer,
string name,
IEnumerable<T> elements,
Action<IOpenApiWriter, T> action)
where T : IOpenApiElement
{
writer.WriteCollectionInternal(name, elements, action);
}
/// <summary>
/// Write the optional Open API element map (string to string mapping).
/// </summary>
/// <param name="writer">The Open API writer.</param>
/// <param name="name">The property name.</param>
/// <param name="elements">The map values.</param>
/// <param name="action">The map element writer action.</param>
public static void WriteOptionalMap(
this IOpenApiWriter writer,
string name,
IDictionary<string, string> elements,
Action<IOpenApiWriter, string> action)
{
if (elements != null)
{
writer.WriteMapInternal(name, elements, action);
}
}
/// <summary>
/// Write the required Open API element map (string to string mapping).
/// </summary>
/// <param name="writer">The Open API writer.</param>
/// <param name="name">The property name.</param>
/// <param name="elements">The map values.</param>
/// <param name="action">The map element writer action.</param>
public static void WriteRequiredMap(
this IOpenApiWriter writer,
string name,
IDictionary<string, string> elements,
Action<IOpenApiWriter, string> action)
{
writer.WriteMapInternal(name, elements, action);
}
/// <summary>
/// Write the optional Open API element map.
/// </summary>
/// <typeparam name="T">The Open API element type. <see cref="IOpenApiElement"/></typeparam>
/// <param name="writer">The Open API writer.</param>
/// <param name="name">The property name.</param>
/// <param name="elements">The map values.</param>
/// <param name="action">The map element writer action.</param>
public static void WriteOptionalMap<T>(
this IOpenApiWriter writer,
string name,
IDictionary<string, T> elements,
Action<IOpenApiWriter, T> action)
where T : IOpenApiElement
{
if (elements != null)
{
writer.WriteMapInternal(name, elements, action);
}
}
/// <summary>
/// Write the required Open API element map.
/// </summary>
/// <typeparam name="T">The Open API element type. <see cref="IOpenApiElement"/></typeparam>
/// <param name="writer">The Open API writer.</param>
/// <param name="name">The property name.</param>
/// <param name="elements">The map values.</param>
/// <param name="action">The map element writer action.</param>
public static void WriteRequiredMap<T>(
this IOpenApiWriter writer,
string name,
IDictionary<string, T> elements,
Action<IOpenApiWriter, T> action)
where T : IOpenApiElement
{
writer.WriteMapInternal(name, elements, action);
}
private static void WriteCollectionInternal<T>(
this IOpenApiWriter writer,
string name,
IEnumerable<T> elements,
Action<IOpenApiWriter, T> action)
{
CheckArguments(writer, name, action);
writer.WritePropertyName(name);
writer.WriteStartArray();
if (elements != null)
{
foreach (var item in elements)
{
action(writer, item);
}
}
writer.WriteEndArray();
}
private static void WriteMapInternal<T>(
this IOpenApiWriter writer,
string name,
IDictionary<string, T> elements,
Action<IOpenApiWriter, T> action)
{
CheckArguments(writer, name, action);
writer.WritePropertyName(name);
writer.WriteStartObject();
if (elements != null)
{
foreach (var item in elements)
{
writer.WritePropertyName(item.Key);
action(writer, item.Value);
}
}
writer.WriteEndObject();
}
private static void CheckArguments<T>(IOpenApiWriter writer, string name, Action<IOpenApiWriter, T> action)
{
CheckArguments(writer, name);
if (action == null)
{
throw Error.ArgumentNull(nameof(action));
}
}
private static void CheckArguments(IOpenApiWriter writer, string name)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
if (string.IsNullOrWhiteSpace(name))
{
throw Error.ArgumentNullOrWhiteSpace(nameof(name));
}
}
}
}

View file

@ -1,243 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System.IO;
namespace Microsoft.OpenApi.Writers
{
/// <summary>
/// YAML writer.
/// </summary>
public class OpenApiYamlWriter : OpenApiWriterBase
{
/// <summary>
/// Initializes a new instance of the <see cref="OpenApiYamlWriter"/> class.
/// </summary>
/// <param name="textWriter">The text writer.</param>
public OpenApiYamlWriter(TextWriter textWriter)
: this(textWriter, new OpenApiSerializerSettings())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="OpenApiYamlWriter"/> class.
/// </summary>
/// <param name="textWriter">The text writer.</param>
/// <param name="settings">The writer settings.</param>
public OpenApiYamlWriter(TextWriter textWriter, OpenApiSerializerSettings settings)
: base(textWriter, settings)
{
}
/// <summary>
/// Base Indentation Level.
/// This denotes how many indentations are needed for the property in the base object.
/// </summary>
protected override int BaseIndentation => 0;
/// <summary>
/// Write YAML start object.
/// </summary>
public override void WriteStartObject()
{
var previousScope = CurrentScope();
var currentScope = StartScope(ScopeType.Object);
if (previousScope != null && previousScope.Type == ScopeType.Array)
{
currentScope.IsInArray = true;
Writer.WriteLine();
WriteIndentation();
Writer.Write(WriterConstants.PrefixOfArrayItem);
}
IncreaseIndentation();
}
/// <summary>
/// Write YAML end object.
/// </summary>
public override void WriteEndObject()
{
var previousScope = EndScope(ScopeType.Object);
DecreaseIndentation();
var currentScope = CurrentScope();
// If the object is empty, indicate it by writing { }
if (previousScope.ObjectCount == 0)
{
// If we are in an object, write a white space preceding the braces.
if (currentScope != null && currentScope.Type == ScopeType.Object)
{
Writer.Write(" ");
}
Writer.Write(WriterConstants.EmptyObject);
}
}
/// <summary>
/// Write YAML start array.
/// </summary>
public override void WriteStartArray()
{
var previousScope = CurrentScope();
var currentScope = StartScope(ScopeType.Array);
if (previousScope != null && previousScope.Type == ScopeType.Array)
{
currentScope.IsInArray = true;
Writer.WriteLine();
WriteIndentation();
Writer.Write(WriterConstants.PrefixOfArrayItem);
}
IncreaseIndentation();
}
/// <summary>
/// Write YAML end array.
/// </summary>
public override void WriteEndArray()
{
var previousScope = EndScope(ScopeType.Array);
DecreaseIndentation();
var currentScope = CurrentScope();
// If the array is empty, indicate it by writing [ ]
if (previousScope.ObjectCount == 0)
{
// If we are in an object, write a white space preceding the braces.
if (currentScope != null && currentScope.Type == ScopeType.Object)
{
Writer.Write(" ");
}
Writer.Write(WriterConstants.EmptyArray);
}
}
/// <summary>
/// Write the property name and the delimiter.
/// </summary>
public override void WritePropertyName(string name)
{
VerifyCanWritePropertyName(name);
var currentScope = CurrentScope();
// If this is NOT the first property in the object, always start a new line and add indentation.
if (currentScope.ObjectCount != 0)
{
Writer.WriteLine();
WriteIndentation();
}
// Only add newline and indentation when this object is not in the top level scope and not in an array.
// The top level scope should have no indentation and it is already in its own line.
// The first property of an object inside array can go after the array prefix (-) directly.
else if (! IsTopLevelScope() && !currentScope.IsInArray )
{
Writer.WriteLine();
WriteIndentation();
}
Writer.Write(name);
Writer.Write(":");
currentScope.ObjectCount++;
}
/// <summary>
/// Write string value.
/// </summary>
/// <param name="value">The string value.</param>
public override void WriteValue(string value)
{
WriteValueSeparator();
value = value.Replace("\n", "\\n");
// If string is an empty string, wrap it in quote to ensure it is not recognized as null.
if (value == "")
{
value = "''";
}
// If string is the word null, wrap it in quote to ensure it is not recognized as empty scalar null.
if (value == "null")
{
value = "'null'";
}
// If string includes special character, wrap it in quote to avoid conflicts.
if (value.StartsWith("#"))
{
value = $"'{value}'";
}
// If string can be mistaken as a number or a boolean, wrap it in quote to indicate that this is
// indeed a string, not a number of a boolean.
if (decimal.TryParse(value, out var _) || bool.TryParse(value, out var _))
{
value = $"'{value}'";
}
Writer.Write(value);
}
/// <summary>
/// Write null value.
/// </summary>
public override void WriteNull()
{
// YAML allows null value to be represented by either nothing or the word null.
// We will write nothing here.
WriteValueSeparator();
}
/// <summary>
/// Write value separator.
/// </summary>
protected override void WriteValueSeparator()
{
if (IsArrayScope())
{
// If array is the outermost scope and this is the first item, there is no need to insert a newline.
if (!IsTopLevelScope() || CurrentScope().ObjectCount != 0)
{
Writer.WriteLine();
}
WriteIndentation();
Writer.Write(WriterConstants.PrefixOfArrayItem);
CurrentScope().ObjectCount++;
}
else
{
Writer.Write(" ");
}
}
/// <summary>
/// Writes the content raw value.
/// </summary>
public override void WriteRaw(string value)
{
WriteValueSeparator();
Writer.Write(value);
}
}
}

View file

@ -1,68 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.OpenApi.Writers
{
/// <summary>
/// Various scope types for Open API writer.
/// </summary>
public enum ScopeType
{
/// <summary>
/// Object scope.
/// </summary>
Object = 0,
/// <summary>
/// Array scope.
/// </summary>
Array = 1,
}
/// <summary>
/// Class representing scope information.
/// </summary>
public sealed class Scope
{
/// <summary>
/// The type of the scope.
/// </summary>
private readonly ScopeType type;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="type">The type of the scope.</param>
public Scope(ScopeType type)
{
this.type = type;
}
/// <summary>
/// Get/Set the object count for this scope.
/// </summary>
public int ObjectCount
{
get;
set;
}
/// <summary>
/// Gets the scope type for this scope.
/// </summary>
public ScopeType Type
{
get
{
return this.type;
}
}
/// <summary>
/// Get/Set the whether it is in previous array scope.
/// </summary>
public bool IsInArray { get; set; } = false;
}
}

View file

@ -1,125 +0,0 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.OpenApi.Writers
{
/// <summary>
/// Constants for the writer.
/// </summary>
internal static class WriterConstants
{
/// <summary>
/// JSON datetime format.
/// </summary>
internal const string ODataDateTimeFormat = @"\/Date({0})\/";
/// <summary>
/// JSON datetime offset format.
/// </summary>
internal const string ODataDateTimeOffsetFormat = @"\/Date({0}{1}{2:D4})\/";
/// <summary>
/// A plus sign for the date time offset format.
/// </summary>
internal const string ODataDateTimeOffsetPlusSign = "+";
/// <summary>
/// The true value literal.
/// </summary>
internal const string JsonTrueLiteral = "true";
/// <summary>
/// The false value literal.
/// </summary>
internal const string JsonFalseLiteral = "false";
/// <summary>
/// The null value literal.
/// </summary>
internal const string JsonNullLiteral = "null";
/// <summary>
/// Character which starts the object scope.
/// </summary>
internal const string StartObjectScope = "{";
/// <summary>
/// Character which ends the object scope.
/// </summary>
internal const string EndObjectScope = "}";
/// <summary>
/// Character which starts the array scope.
/// </summary>
internal const string StartArrayScope = "[";
/// <summary>
/// Character which ends the array scope.
/// </summary>
internal const string EndArrayScope = "]";
/// <summary>
/// "(" Json Padding Function scope open parens.
/// </summary>
internal const string StartPaddingFunctionScope = "(";
/// <summary>
/// ")" Json Padding Function scope close parens.
/// </summary>
internal const string EndPaddingFunctionScope = ")";
/// <summary>
/// The separator between object members.
/// </summary>
internal const string ObjectMemberSeparator = ",";
/// <summary>
/// The separator between array elements.
/// </summary>
internal const string ArrayElementSeparator = ",";
/// <summary>
/// The separator between the name and the value.
/// </summary>
internal const string NameValueSeparator = ": ";
/// <summary>
/// The quote character.
/// </summary>
internal const char QuoteCharacter = '"';
/// <summary>
/// The white space for empty object
/// </summary>
internal const string WhiteSpaceForEmptyObject = " ";
/// <summary>
/// The white space for empty array
/// </summary>
internal const string WhiteSpaceForEmptyArray = " ";
/// <summary>
/// The prefix of array item
/// </summary>
internal const string PrefixOfArrayItem = "- ";
/// <summary>
/// The white space for indent
/// </summary>
internal const string WhiteSpaceForIndent = " ";
/// <summary>
/// Empty object
/// </summary>
/// <remarks>To indicate empty object in YAML.</remarks>
internal const string EmptyObject = "{ }";
/// <summary>
/// Empty array
/// </summary>
/// <remarks>To indicate empty array in YAML.</remarks>
internal const string EmptyArray = "[ ]";
}
}