private static IOpenApiAny GetTypeNameForExample(IEdmTypeReference edmTypeReference) { switch (edmTypeReference.TypeKind()) { case EdmTypeKind.Primitive: if (edmTypeReference.IsBoolean()) { return(new OpenApiBoolean(true)); } else { return(new OpenApiString(edmTypeReference.AsPrimitive().PrimitiveDefinition().Name)); } case EdmTypeKind.Entity: case EdmTypeKind.Complex: case EdmTypeKind.Enum: OpenApiObject obj = new OpenApiObject(); obj["@odata.type"] = new OpenApiString(edmTypeReference.FullName()); return(obj); case EdmTypeKind.Collection: OpenApiArray array = new OpenApiArray(); IEdmTypeReference elementType = edmTypeReference.AsCollection().ElementType(); array.Add(GetTypeNameForExample(elementType)); return(array); case EdmTypeKind.Untyped: case EdmTypeKind.TypeDefinition: case EdmTypeKind.EntityReference: default: throw new OpenApiException("Not support for the type kind " + edmTypeReference.TypeKind()); } }
public override void Parse(OpenApiObject data, IEndpointParser parser) { base.Parse(data, parser); Schema = data.GetSchema("schema"); Separator = data.GetString("separator"); }
public override void Patch(OpenApiSchema schema, OpenApiObject xProps, OpenApiObject templateOptions, LinkGenerator linkGenerator, List <ValidatorModel> validators) { base.Patch(schema, xProps, templateOptions, linkGenerator, validators); templateOptions["requiredFromList"] = new OpenApiBoolean(true); }
public override void Patch(OpenApiSchema schema, OpenApiObject xProps, OpenApiObject templateOptions, LinkGenerator linkGenerator, List <ValidatorModel> validators) { base.Patch(schema, xProps, templateOptions, linkGenerator, validators); var customConfig = templateOptions.GetOrSetDefault <OpenApiObject, IOpenApiAny>("customFieldConfig"); customConfig["labelProp"] = new OpenApiString(LabelProp); customConfig["valueProp"] = new OpenApiString(ValueProp); var optionsUrl = OptionsControllerType != null ? linkGenerator.GetAbsolutePathByAction(OptionsActionName, TypeHelpers.GetControllerName(OptionsControllerType)) : OptionsUrl; customConfig["loadOptionsFromUrl"] = new OpenApiBoolean(true); customConfig["optionsUrl"] = new OpenApiString(optionsUrl); customConfig["reloadOptionsOnInit"] = new OpenApiBoolean(ReloadOptionsOnInit); customConfig["showReloadButton"] = new OpenApiBoolean(ShowReloadButton); var fieldGroupFill = customConfig.GetOrSetDefault <OpenApiObject, IOpenApiAny>("fieldGroupFill"); fieldGroupFill["enabled"] = new OpenApiBoolean(true); fieldGroupFill["keepValueProp"] = new OpenApiBoolean(KeepValueProp); fieldGroupFill["selectorFieldType"] = new OpenApiString(SelectorFieldType ?? "autocomplete"); }
public void Apply(OpenApiSchema model, SchemaFilterContext context) { // Patch only root level schemas, and not the members(properties) schemas of other schemas if (!context.Type.IsEnum || context.MemberInfo != null) { return; } model.Enum = Enum.GetValues(context.Type).Cast <Enum>() .Select(value => (IOpenApiAny) new OpenApiString(value.GetCustomValue().ToString())) .ToList(); var templateOptions = model.Extensions.GetOrSetDefault("x-templateOptions", new OpenApiObject()); var optionsArray = templateOptions.GetOrSetDefault("options", new OpenApiArray()); optionsArray.AddRange(Enum.GetValues(context.Type).Cast <Enum>() .Select(enumValue => { var option = new OpenApiObject { ["value"] = OpenApiExtensions.ToOpenApi(enumValue.GetCustomValue()), ["label"] = new OpenApiString(enumValue.GetDisplayName()), }; if (enumValue.GetDisplayDescription() is { } s&& !string.IsNullOrEmpty(s)) { option["description"] = new OpenApiString(s); } return(option); })); }
public static IEnumerable <EnumMember> ApplyEnumExtensions(this Type type, IDictionary <string, IOpenApiExtension> extensions, ISchemaGenerator schemaGenerator, SchemaRepository schemaRepository) { type = type.UnwrapIfNullable(); if (!type.IsEnum || extensions == null) { return(null); } var underlyingType = type.GetEnumUnderlyingType(); var members = type.GetEnumMembers(); var memberDictionary = new OpenApiObject(); foreach (var member in members) { memberDictionary[member.Name] = new OpenApiLong(long.Parse(member.Value.ToString())); // Will never be wider than a long. } var obsoleteDictionary = new OpenApiObject(); foreach (var field in members.Where(f => f.IsObsolete)) { obsoleteDictionary[field.Name] = new OpenApiString(field.ObsoleteMessage ?? string.Empty); } var dictionary = new OpenApiObject { ["id"] = new OpenApiString(type.FullName), ["fields"] = memberDictionary, }; if (obsoleteDictionary.Count > 0) { dictionary["deprecated"] = obsoleteDictionary; } if (type.GetCustomAttribute <FlagsAttribute>() != null) { dictionary["flags"] = new OpenApiBoolean(true); } var enumSchema = schemaGenerator.GenerateSchema(underlyingType, schemaRepository); foreach (var extension in enumSchema.Extensions) { dictionary[extension.Key] = (IOpenApiAny)extension.Value; } var obsoleteAttribute = type.GetCustomAttribute <ObsoleteAttribute>(); if (obsoleteAttribute != null) { dictionary["x-costar-deprecated"] = new OpenApiString(obsoleteAttribute.Message); } extensions[VendorExtensions.Enum] = dictionary; return(members); }
public static OpenApiObject ToOpenApiObject(this object model) { // Get all properties on the object var properties = model.GetType().GetProperties() .Where(x => x.CanRead) .ToDictionary(x => x.Name, x => x.GetValue(model, null)); var opi = new OpenApiObject(); foreach (var prop in properties) { object value = null; value = prop.Value switch { null => new OpenApiNull(), int as_int => new OpenApiInteger(as_int), bool as_bool => new OpenApiBoolean(as_bool), byte as_byte => new OpenApiByte(as_byte), float as_float => new OpenApiFloat(as_float), _ => new OpenApiString($"{prop.Value}"), }; opi.Add(prop.Key, value as IOpenApiAny); } return(opi); }
public void Apply(OpenApiSchema schema, SchemaFilterContext context) { var type = context.Type; if (type.IsEnum) { var values = Enum.GetValues(type); var valueArr = new OpenApiArray(); foreach (var value in values) { var item = new OpenApiObject { ["name"] = new OpenApiString(Enum.GetName(type, value)), ["value"] = new OpenApiString(value.ToString()) }; valueArr.Add(item); } schema.Extensions.Add( "x-ms-enum", new OpenApiObject { ["name"] = new OpenApiString(type.Name), ["modelAsString"] = new OpenApiBoolean(true), ["values"] = valueArr } ); } }
private static IOpenApiAny CreateStructuredTypePropertiesExample(ODataContext context, IEdmStructuredType structuredType) { OpenApiObject example = new OpenApiObject(); IEdmEntityType entityType = structuredType as IEdmEntityType; // properties foreach (var property in structuredType.Properties()) { // IOpenApiAny item; IEdmTypeReference propertyType = property.Type; IOpenApiAny item = GetTypeNameForExample(context, propertyType); EdmTypeKind typeKind = propertyType.TypeKind(); if (typeKind == EdmTypeKind.Primitive && item is OpenApiString) { OpenApiString stringAny = item as OpenApiString; string value = stringAny.Value; if (entityType != null && entityType.Key().Any(k => k.Name == property.Name)) { value += " (identifier)"; } if (propertyType.IsDateTimeOffset() || propertyType.IsDate() || propertyType.IsTimeOfDay()) { value += " (timestamp)"; } item = new OpenApiString(value); } example.Add(property.Name, item); } return(example); }
protected virtual void AttachBasicProps(OpenApiSchema schema, OpenApiObject xProps, OpenApiObject templateOptions, LinkGenerator linkGenerator) { if (ClassName != null) { xProps["className"] = OpenApiExtensions.ToOpenApi(ClassName); } if (DefaultValue != null) { xProps["defaultValue"] = OpenApiExtensions.ToOpenApi(DefaultValue); } if (Wrappers != null) { var arr = new OpenApiArray(); arr.AddRange(from object o in Wrappers select OpenApiExtensions.ToOpenApi(o)); xProps["wrappers"] = arr; } if (Disabled) { templateOptions["disabled"] = OpenApiExtensions.ToOpenApi(true); } }
internal override IDictionary <string, IOpenApiAny> ToDictionary() { var responseObject = new OpenApiObject { [StatusCodeKey] = new OpenApiString(StatusCode) }; if (ResponseTemplates != null && ResponseTemplates.Any()) { var templatesContainer = new OpenApiObject(); foreach (var template in ResponseTemplates) { templatesContainer[template.Key] = new OpenApiString(template.Value); } responseObject[ResponseTemplatesKey] = templatesContainer; } if (ResponseParameters != null && ResponseParameters.Any()) { var parametersContainer = new OpenApiObject(); foreach (var parameter in ResponseParameters) { parametersContainer[parameter.Key] = new OpenApiString(parameter.Value); } responseObject[ResponseParametersKey] = parametersContainer; } return(responseObject); }
public override OpenApiObject GetCustomOpenApiConfig(LinkGenerator linkGenerator) { var obj = new OpenApiObject(); if (RemoveDisabled) { obj["removeDisabled"] = new OpenApiBoolean(true); } if (AddDisabled) { obj["addDisabled"] = new OpenApiBoolean(true); } if (!string.IsNullOrEmpty(AddButtonContent)) { obj["addButtonContent"] = new OpenApiString(AddButtonContent); } if (!string.IsNullOrEmpty(RemoveButtonContent)) { obj["removeButtonContent"] = new OpenApiString(RemoveButtonContent); } return(obj); }
public async Task WriteOpenApiArrayAsJsonWorks(bool produceTerseOutput) { // Arrange var openApiObject = new OpenApiObject { { "stringProp", new OpenApiString("stringValue1") }, { "objProp", new OpenApiObject() }, { "arrayProp", new OpenApiArray { new OpenApiBoolean(false) } } }; var array = new OpenApiArray { new OpenApiBoolean(false), openApiObject, new OpenApiString("stringValue2") }; var actualJson = WriteAsJson(array, produceTerseOutput); // Assert await Verifier.Verify(actualJson).UseParameters(produceTerseOutput); }
internal override IDictionary <string, IOpenApiAny> ToDictionary() { var children = new OpenApiObject(); if (Types != null && Types.Any()) { var types = new OpenApiArray(); types.AddRange(Types.Select(x => new OpenApiString(x))); children[TypesKey] = types; } if (VpcEndpointIds != null && VpcEndpointIds.Any()) { var vpcIds = new OpenApiArray(); vpcIds.AddRange(VpcEndpointIds.Select(x => new OpenApiString(x))); children[VpcEndpointIdsKey] = vpcIds; } return(new Dictionary <string, IOpenApiAny>() { { EndpointConfigurationRootKey, children } }); }
private void CreateArrayOrListObject(string name, object value, Type type, Type nestedType, OpenApiObject openApiObject) { if (value == null) { openApiObject.Add(name, new OpenApiNull()); return; } var arrayObject = new OpenApiArray(); foreach (var item in value as IEnumerable) { if (nestedType.IsSimpleType()) { var node = CreateOpenApiObject(nestedType, item); arrayObject.Add(node); } else { var arrayItemObject = new OpenApiObject(); var properties = nestedType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var property in properties) { var nodeValue = property.GetValue(item); ConvertRec(GetName(property.Name), nodeValue, property.PropertyType, arrayItemObject); } arrayObject.Add(arrayItemObject); } } openApiObject.Add(GetName(name), arrayObject); }
public async Task GetSwaggerDocs_ReturnsDocsWithHealthEndpointResponseExample() { // Arrange var options = new WebApiProjectOptions(); using (var project = await WebApiProject.StartNewAsync(options, _outputWriter)) // Act using (HttpResponseMessage response = await project.Swagger.GetSwaggerDocsAsync()) { // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); string json = await response.Content.ReadAsStringAsync(); OpenApiDocument document = LoadOpenApiDocument(json); OpenApiOperation healthOperation = SelectGetHealthEndpoint(document); OpenApiResponse okResponse = healthOperation.Responses .Single(r => r.Key == "200").Value; OpenApiObject example = SelectHealthPointOkExample(okResponse); Assert.Contains("entries", example.Keys); var entriesCollection = (OpenApiObject)example["entries"]; Assert.Contains("api", entriesCollection.Keys); Assert.Contains("database", entriesCollection.Keys); } }
public void WriteOpenApiObjectAsJsonWorks() { // Arrange var openApiObject = new OpenApiObject { { "stringProp", new OpenApiString("stringValue1") }, { "objProp", new OpenApiObject() }, { "arrayProp", new OpenApiArray { new OpenApiBoolean(false) } } }; var actualJson = WriteAsJson(openApiObject); // Assert var expectedJson = @"{ ""stringProp"": ""stringValue1"", ""objProp"": { }, ""arrayProp"": [ false ] }"; expectedJson = expectedJson.MakeLineBreaksEnvironmentNeutral(); actualJson.Should().Be(expectedJson); }
public void Apply(OpenApiSchema schema, SchemaFilterContext context) { var type = context.Type; var genericTypes = type.GetGenericTypes(); var dictionaryType = genericTypes.FirstOrDefault(t => t.GetGenericTypeDefinition() == typeof(IDictionary <,>)) ?? genericTypes.FirstOrDefault(t => t.GetGenericTypeDefinition() == typeof(IReadOnlyDictionary <,>)); if (dictionaryType == null) { return; } var keyType = dictionaryType.GetGenericArguments()[0]; var keySchema = context.SchemaGenerator.GenerateSchema(keyType, context.SchemaRepository); var valueType = dictionaryType.GetGenericArguments()[1]; valueType.ApplyPrimitiveExtensions(schema.AdditionalProperties?.Extensions); valueType.ApplyEnumExtensions(schema.AdditionalProperties?.Extensions, context.SchemaGenerator, context.SchemaRepository); var dictionary = new OpenApiObject(); if (keySchema.Reference != null) { dictionary["$ref"] = new OpenApiString(keySchema.Reference.ReferenceV2); } else { dictionary["type"] = new OpenApiString(keySchema.Type); if (keySchema.Format != null) { dictionary["format"] = new OpenApiString(keySchema.Format); } } foreach (var extension in keySchema.Extensions) { dictionary[extension.Key] = (IOpenApiAny)extension.Value; } schema.Extensions[VendorExtensions.KeySchema] = dictionary; if (schema != null) { if (schema.Properties != null) { var first = schema.Properties.Values.FirstOrDefault(); if (first != null) { // Re-write the schema to be the same "shape" as other dictionaries. schema.Properties = null; schema.AdditionalProperties = first; } } } }
private void ProcessFieldAttributes(OpenApiSchema schema, OpenApiObject templateOptions, PropertyInfo propertyInfo, Type declaringType, List <ValidatorModel> validators, out FormlyFieldAttribute fieldAttr) { fieldAttr = null; var xProps = new OpenApiObject(); foreach (var fieldPropertyAttribute in GetAttributes <FormlyFieldPropAttribute>(propertyInfo, declaringType)) { xProps[fieldPropertyAttribute.FullPath] = OpenApiExtensions.ToOpenApi(fieldPropertyAttribute.Value); } foreach (var patchAttr in GetAttributes <FormlyConfigPatcherAttribute>(propertyInfo, declaringType)) { patchAttr.Patch(schema, xProps, templateOptions, _linkGenerator, validators); if (patchAttr is FormlyFieldAttribute fAttr) { fieldAttr = fAttr; } } if (xProps.Count > 0) { schema.Extensions["x-props"] = xProps; } }
public IEndpoint Parse(OpenApiObject data, string defaultKind = "") { var endpoint = _endpointRegistry.OfKind(data.GetString("kind") ?? defaultKind); endpoint.Parse(data, this); return(endpoint); }
public override void Parse(OpenApiObject data, IEndpointParser parser) { base.Parse(data, parser); RequestSchema = data.GetSchema("request-schema"); ResponseSchema = data.GetSchema("response-schema"); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services .AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddNewtonsoftJson(options => { options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; }); services.AddAuthentication(Constants.SignAuthenticationScheme). AddScheme <StsSettings, SignAuthenticationHandler>(Constants.SignAuthenticationScheme, options => Configuration.Bind("StsSettings", options)); services.AddAuthentication(BasicAuthenticationHandler.AuthenticationScheme). AddScheme <StsSettings, BasicAuthenticationHandler>(BasicAuthenticationHandler.AuthenticationScheme, options => Configuration.Bind("StsSettings", options)); services.AddAuthentication(SrsAuthenticationScheme.SessionAuthenticationScheme) .AddScheme <AuthenticationSchemeOptions, SessionAuthenticationHandler>(SrsAuthenticationScheme.SessionAuthenticationScheme, null); var packageNameExtension = new OpenApiObject(); packageNameExtension.Add("package-name", new OpenApiString("com.vmware.srs")); services.AddSwaggerGen( c => { c.SwaggerDoc( "srs", new OpenApiInfo { Description = APIGatewayResources.ProductApiDescription, Title = APIGatewayResources.ProductName, Version = APIGatewayResources.ProductVersion, Contact = new OpenApiContact() { Name = "Script Runtime Service for vSphere", Url = new Uri(@"https://github.com/vmware/script-runtime-service-for-vsphere"), }, Extensions = { { "x-vmw-vapi-codegenconfig", packageNameExtension } } }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); GlobalTagsSchemeFilter.Configure(c); TagsOperationFilter.Configure(c); VMwareVapiVendorExtensionsOperationFilter.Configure(c); SecurityRequirementsOperationFilter.Configure(c); ScriptExecutionParameterDocumentFilter.Configure(c); ScriptExecutionParameterSchemaFilter.Configure(c); //ServersDocumentFilter.Configure(c); //VMwarePrintingPressExtensionsOperationFilter.Configure(c); //VMwarePrintingPressPathExtensionsDocumentFilter.Configure(c); ReadOnlySchemaFilter.Configure(c); }); services.AddSwaggerGenNewtonsoftSupport(); }
private static IOpenApiAny ToOpenApiAny(Type type, object instance) { var arrayResult = ToOpenApiArray(type, instance); if (arrayResult != null) { return(arrayResult); } var result = new OpenApiObject(); foreach (var property in type.GetRuntimeProperties()) { var value = property.GetValue(instance); if (value != null) { var openValue = GetStructValue(property.PropertyType, value); var key = char.ToLower(property.Name[0]) + property.Name.Substring(1); if (openValue != null) { if (result.ContainsKey(key)) { result[key] = openValue; } else { result.Add(key, openValue); } continue; } var array = default(OpenApiArray); if ((array = ToOpenApiArray(property.PropertyType, value)) != null) { if (result.ContainsKey(key)) { result[key] = array; } else { result.Add(key, array); } continue; } var openObject = ToOpenApiAny(property.PropertyType, value); if (result.ContainsKey(key)) { result[key] = openObject; } else { result.Add(key, openObject); } } } return(result); }
private void PatchEnumProperties(PropertyInfo propertyInfo, OpenApiObject templateOptions, OpenApiSchema schema) { if (!propertyInfo.PropertyType.IsEnum) { return; } schema.Extensions["format"] = Oas("select"); }
public void Apply([NotNull] OpenApiSchema schema, [NotNull] SchemaFilterContext context) { if ((schema == null) || (context == null)) { throw new ArgumentNullException(nameof(schema) + " || " + nameof(context)); } if (!context.Type.IsEnum) { return; } if (context.Type.IsDefined(typeof(FlagsAttribute), false)) { schema.Format = "flags"; } OpenApiObject definition = new OpenApiObject(); foreach (object enumValue in context.Type.GetEnumValues()) { string enumName = Enum.GetName(context.Type, enumValue); if (string.IsNullOrEmpty(enumName)) { enumName = enumValue.ToString(); if (string.IsNullOrEmpty(enumName)) { continue; } } IOpenApiAny enumObject; if (TryCast(enumValue, out int intValue)) { enumObject = new OpenApiInteger(intValue); } else if (TryCast(enumValue, out long longValue)) { enumObject = new OpenApiLong(longValue); } else if (TryCast(enumValue, out ulong ulongValue)) { // OpenApi spec doesn't support ulongs as of now enumObject = new OpenApiString(ulongValue.ToString()); } else { throw new ArgumentOutOfRangeException(nameof(enumValue)); } definition.Add(enumName, enumObject); } schema.AddExtension("x-definition", definition); }
public override void Parse(OpenApiObject data, IEndpointParser parser) { base.Parse(data, parser); if (data.TryGetObject("element", out var element)) { Element = parser.Parse(element); } }
public override void Patch(OpenApiSchema schema, OpenApiObject xProps, OpenApiObject templateOptions, LinkGenerator linkGenerator, List <ValidatorModel> validators) { base.Patch(schema, xProps, templateOptions, linkGenerator, validators); if (!string.IsNullOrEmpty(FieldGroupClassName)) { xProps["fieldGroupClassName"] = OpenApiExtensions.ToOpenApi(FieldGroupClassName); } }
public override void Patch(OpenApiSchema schema, OpenApiObject xProps, OpenApiObject templateOptions, LinkGenerator linkGenerator, List <ValidatorModel> validators) { AttachBasicProps(schema, xProps, templateOptions, linkGenerator); if (HasCustomValidators) { validators.AddRange(GetCustomValidators()); } }
private bool TryParse(JsonElement token, out IOpenApiAny?any) { any = null; switch (token.ValueKind) { case JsonValueKind.Array: var array = new OpenApiArray(); foreach (var value in token.EnumerateArray()) { if (TryParse(value, out var child)) { array.Add(child); } } any = array; return(true); case JsonValueKind.False: any = new OpenApiBoolean(false); return(true); case JsonValueKind.True: any = new OpenApiBoolean(true); return(true); case JsonValueKind.Number: any = new OpenApiDouble(token.GetDouble()); return(true); case JsonValueKind.String: any = new OpenApiString(token.GetString()); return(true); case JsonValueKind.Object: var obj = new OpenApiObject(); foreach (var child in token.EnumerateObject()) { if (TryParse(child.Value, out var value)) { obj[child.Name] = value; } } any = obj; return(true); case JsonValueKind.Null: case JsonValueKind.Undefined: default: return(false); } }
private OpenApiObject BuildSpec() { var spec = new OpenApiObject(); spec.Info.Title = "alba"; spec.Info.Version = "1.0.0"; spec.Paths = Discover.PathsObject; spec.Components = Discover.ComponetsObject; return(spec); }