/// <summary>
        /// Create the dictionary of <see cref="OpenApiExample"/> object.
        /// </summary>
        /// <param name="context">The OData to Open API context.</param>
        /// <param name="securitySchemes">The securitySchemes.</param>
        /// <returns>The created <see cref="OpenApiExample"/> dictionary.</returns>
        public static IDictionary <string, OpenApiExample> CreateExamples(this ODataContext context)
        {
            Utils.CheckArgumentNull(context, nameof(context));

            IDictionary <string, OpenApiExample> examples = new Dictionary <string, OpenApiExample>();

            // Each entity type, complex type, enumeration type, and type definition directly
            // or indirectly used in the paths field is represented as a name / value pair of the schemas map.
            foreach (var element in context.Model.SchemaElements.Where(c => !c.Namespace.StartsWith("Org.OData.")))
            {
                switch (element.SchemaElementKind)
                {
                case EdmSchemaElementKind.TypeDefinition:     // Type definition
                {
                    IEdmType       reference = (IEdmType)element;
                    OpenApiExample example   = context.CreateExample(reference);
                    if (example != null)
                    {
                        examples.Add(reference.FullTypeName(), example);
                    }
                }
                break;
                }
            }

            return(examples);
        }
        /// <summary>
        /// Create a new instance of the <see cref="KeyValuePair{TKey, TValue}"/> class.
        /// </summary>
        /// <param name="name">Name of the example</param>
        /// <param name="summary">Summary of the example</param>
        /// <param name="description">Description of the example</param>
        /// <param name="instance">Example object.</param>
        /// <param name="namingStrategy"><see cref="NamingStrategy"/> instance.</param>
        /// <typeparam name="T">Type of the example object.</typeparam>
        /// <returns>Returns the new instance of the <see cref="KeyValuePair{TKey, TValue}"/> class. </returns>
        public static KeyValuePair <string, OpenApiExample> Resolve <T>(string name, string summary, string description, T instance, NamingStrategy namingStrategy = null)
        {
            name.ThrowIfNullOrWhiteSpace();
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }
            var resolver = new DefaultContractResolver()
            {
                NamingStrategy = namingStrategy ?? new DefaultNamingStrategy()
            };

            settings.ContractResolver = resolver;

            var openApiExampleValue = OpenApiExampleFactory.CreateInstance <T>(instance, settings);
            var example             = new OpenApiExample()
            {
                Summary     = summary,
                Description = description,
                Value       = openApiExampleValue,
            };
            var kvp = new KeyValuePair <string, OpenApiExample>(name, example);

            return(kvp);
        }
        /// <summary>
        /// Create the dictionary of <see cref="OpenApiExample"/> object.
        /// </summary>
        /// <param name="context">The OData to Open API context.</param>
        /// <returns>The created <see cref="OpenApiExample"/> dictionary.</returns>
        public static IDictionary <string, OpenApiExample> CreateExamples(this ODataContext context)
        {
            Utils.CheckArgumentNull(context, nameof(context));

            IDictionary <string, OpenApiExample> examples = new Dictionary <string, OpenApiExample>();

            // Each entity type, complex type, enumeration type, and type definition directly
            // or indirectly used in the paths field is represented as a name / value pair of the schemas map.
            // Ideally this would be driven off the types used in the paths, but in practice, it is simply
            // all of the types present in the model.
            IEnumerable <IEdmSchemaElement> elements = context.Model.GetAllElements();

            foreach (var element in elements)
            {
                switch (element.SchemaElementKind)
                {
                case EdmSchemaElementKind.TypeDefinition:     // Type definition
                {
                    IEdmType       reference = (IEdmType)element;
                    OpenApiExample example   = context.CreateExample(reference);
                    if (example != null)
                    {
                        examples.Add(reference.FullTypeName(), example);
                    }
                }
                break;
                }
            }

            return(examples);
        }
Beispiel #4
0
 public override void Visit(OpenApiExample example)
 {
     if (example.UnresolvedReference)
     {
         throw new ArgumentException("Single pass reference resolution expects this element to already be resolved");
     }
 }
Beispiel #5
0
 public void Traverse(OpenApiExample example)
 {
     if (example == null)
     {
         return;
     }
     Visitor.Visit(example);
 }
Beispiel #6
0
        public static void ShouldMatch <T>(this OpenApiExample actualExample, ISwaggerExample <T> expectedExample, Action <T, T> matcher)
        {
            actualExample.Summary.ShouldBe(expectedExample.Summary);
            var actualRequestValueSerialized = actualExample.Value.ShouldBeAssignableTo <OpenApiString>();
            var actualRequestValue           = JsonConvert.DeserializeObject <T>(actualRequestValueSerialized.Value);

            matcher(actualRequestValue, expectedExample.Value);
        }
Beispiel #7
0
        /// <summary>
        /// Visits <see cref="OpenApiExample"/> and child objects
        /// </summary>
        internal void Walk(OpenApiExample example, bool isComponent = false)
        {
            if (example == null || ProcessAsReference(example, isComponent))
            {
                return;
            }

            _visitor.Visit(example);
            Walk(example as IOpenApiExtensible);
        }
Beispiel #8
0
        /// <summary>
        /// Visits <see cref="OpenApiExample"/> and child objects
        /// </summary>
        internal void Walk(OpenApiExample example)
        {
            if (example == null)
            {
                return;
            }

            _visitor.Visit(example);
            Walk(example as IOpenApiExtensible);
        }
        public void CanWriteExampleObjectAsReferenceObjectYaml()
        {
            // Arrange
            string expect = @"$ref: #/components/schemas/Address";

            OpenApiExample example = new OpenApiExample
            {
                Reference = new OpenApiReference("#/components/schemas/Address")
            };

            // Act & Assert
            Assert.Equal(expect, example.WriteToYaml());
        }
Beispiel #10
0
        /// <summary>
        /// Sets the custom parameters.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <param name="headers">The custom parameters.</param>
        /// <param name="location">The parameter location.</param>
        private static void AppendCustomParameters(IList <OpenApiParameter> parameters, IList <CustomParameter> headers, ParameterLocation location)
        {
            foreach (var param in headers)
            {
                OpenApiParameter parameter = new OpenApiParameter
                {
                    In          = location,
                    Name        = param.Name,
                    Description = param.Description,
                    Schema      = new OpenApiSchema
                    {
                        Type = "string"
                    },
                    Required = param.Required ?? false
                };

                if (param.DocumentationURL != null)
                {
                    parameter.Example = new OpenApiString(param.DocumentationURL ?? "N/A");
                }

                if (param.ExampleValues != null)
                {
                    parameter.Examples = new Dictionary <string, OpenApiExample>();
                    int index = 1;
                    foreach (var example in param.ExampleValues)
                    {
                        OpenApiExample ex = new OpenApiExample
                        {
                            Description = example.Description
                        };

                        if (example is ExternalExample)
                        {
                            var externalExample = (ExternalExample)example;
                            ex.Value = new OpenApiString(externalExample.ExternalValue ?? "N/A");
                        }
                        else
                        {
                            var inlineExample = (InlineExample)example;
                            ex.Value = new OpenApiString(inlineExample.InlineValue ?? "N/A");
                        }

                        parameter.Examples.Add("example-" + index++, ex);
                    }
                }

                parameters.Add(parameter);
            }
        }
Beispiel #11
0
        /// <summary>
        /// Set the <see cref="HttpRequest"/> annotation for the response.
        /// </summary>
        /// <param name="operation">The operation.</param>
        /// <param name="request">The <see cref="HttpRequest"/>.</param>
        protected virtual void AppendHttpResponses(OpenApiOperation operation)
        {
            if (Request == null || Request.HttpResponses == null || !Request.HttpResponses.Any())
            {
                return;
            }

            foreach (var httpResponse in Request.HttpResponses)
            {
                if (operation.Responses.TryGetValue(httpResponse.ResponseCode, out OpenApiResponse response))
                {
                    if (httpResponse.Description != null)
                    {
                        response.Description = httpResponse.Description;
                    }

                    if (httpResponse.Examples != null)
                    {
                        int index = 1;
                        foreach (var example in httpResponse.Examples)
                        {
                            OpenApiExample ex = new OpenApiExample
                            {
                                Description = example.Description
                            };

                            if (example is ExternalExample)
                            {
                                var externalExample = (ExternalExample)example;
                                ex.Value = new OpenApiString(externalExample.ExternalValue ?? "N/A");
                            }
                            else
                            {
                                var inlineExample = (InlineExample)example;
                                ex.Value = new OpenApiString(inlineExample.InlineValue ?? "N/A");
                            }

                            if (ex.Description != null)
                            {
                                if (response.Content.TryGetValue(ex.Description, out OpenApiMediaType mediaType))
                                {
                                    mediaType.Examples.Add("example-" + index++, ex);
                                }
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Sets the custom parameters.
        /// </summary>
        /// <param name="operation">The OpenApi operation.</param>
        /// <param name="customParameters">The custom parameters.</param>
        /// <param name="location">The parameter location.</param>
        protected static void AppendCustomParameters(OpenApiOperation operation, IList <CustomParameter> customParameters, ParameterLocation location)
        {
            foreach (var param in customParameters)
            {
                string documentationUrl = null;
                if (param.DocumentationURL != null)
                {
                    documentationUrl = $" Documentation URL: {param.DocumentationURL}";
                }

                // DocumentationURL value is to be appended to
                // the parameter Description property
                string paramDescription = (param.Description == null) ? documentationUrl?.Remove(0, 1) : param.Description + documentationUrl;

                OpenApiParameter parameter = new()
                {
                    In          = location,
                    Name        = param.Name,
                    Description = paramDescription,
                    Schema      = new OpenApiSchema
                    {
                        Type = "string"
                    },
                    Required = param.Required ?? false
                };

                if (param.ExampleValues != null)
                {
                    parameter.Examples = new Dictionary <string, OpenApiExample>();
                    int index = 1;
                    foreach (var example in param.ExampleValues)
                    {
                        OpenApiExample ex = new OpenApiExample
                        {
                            Description = example.Description
                        };

                        // maybe call convert to Uri literal
                        ex.Value = new OpenApiString(example.Value.ToString());

                        parameter.Examples.Add("example-" + index++, ex);
                    }
                }

                operation.Parameters.AppendParameter(parameter);
            }
        }
    }
        public void CanWriteExampleObjectAsReferenceObjectJson()
        {
            // Arrange
            string expect = @"
{
  ""$ref"": ""#/components/schemas/Address""
}
".Replace();

            OpenApiExample example = new OpenApiExample
            {
                Reference = new OpenApiReference("#/components/schemas/Address")
            };

            // Act & Assert
            Assert.Equal(expect, example.WriteToJson());
        }
        public void CanWriteBasicExampleObjectAsYaml()
        {
            // Arrange
            string expect = @"
summary: A bar example
description: A bar example description
value: 
".Replace();

            OpenApiExample example = new OpenApiExample
            {
                Summary     = "A bar example",
                Description = "A bar example description",
                Value       = new OpenApiAny()
            };

            // Act & Assert
            Assert.Equal(expect, example.WriteToYaml());
        }
        public void CanWriteBasicExampleObjectAsJson()
        {
            // Arrange
            string expect = @"
{
  ""summary"": ""A bar example"",
  ""externalValue"": ""http://example.org/examples/address-example.xml""
}
".Replace();

            OpenApiExample example = new OpenApiExample
            {
                Summary       = "A bar example",
                ExternalValue = new Uri("http://example.org/examples/address-example.xml")
            };

            // Act & Assert
            Assert.Equal(expect, example.WriteToJson());
        }
        /// <summary>
        /// Sets the custom parameters.
        /// </summary>
        /// <param name="operation">The OpenApi operation.</param>
        /// <param name="customParameters">The custom parameters.</param>
        /// <param name="location">The parameter location.</param>
        protected static void AppendCustomParameters(OpenApiOperation operation, IList <CustomParameter> customParameters, ParameterLocation location)
        {
            foreach (var param in customParameters)
            {
                OpenApiParameter parameter = new OpenApiParameter
                {
                    In          = location,
                    Name        = param.Name,
                    Description = param.Description,
                    Schema      = new OpenApiSchema
                    {
                        Type = "string"
                    },
                    Required = param.Required ?? false
                };

                if (param.DocumentationURL != null)
                {
                    parameter.Example = new OpenApiString(param.DocumentationURL ?? "N/A");
                }

                if (param.ExampleValues != null)
                {
                    parameter.Examples = new Dictionary <string, OpenApiExample>();
                    int index = 1;
                    foreach (var example in param.ExampleValues)
                    {
                        OpenApiExample ex = new OpenApiExample
                        {
                            Description = example.Description
                        };

                        // maybe call convert to Uri literal
                        ex.Value = new OpenApiString(example.Value.ToString());

                        parameter.Examples.Add("example-" + index++, ex);
                    }
                }

                AppendParameter(operation, parameter);
            }
        }
        public void OpenApiExampleComparerShouldSucceed(
            string testCaseName,
            OpenApiExample source,
            OpenApiExample target,
            List <OpenApiDifference> expectedDifferences)
        {
            _output.WriteLine(testCaseName);

            var comparisonContext = new ComparisonContext(new OpenApiComparerFactory(), _sourceDocument,
                                                          _targetDocument);
            var comparer = new OpenApiExampleComparer();

            comparer.Compare(source, target, comparisonContext);

            var differences = comparisonContext.OpenApiDifferences.ToList();

            differences.Count().Should().Be(expectedDifferences.Count);

            differences.Should().BeEquivalentTo(expectedDifferences);
        }
Beispiel #18
0
        public static OpenApiExample LoadExample(ParseNode node)
        {
            var mapNode = node.CheckMapNode("example");

            var pointer = mapNode.GetReferencePointer();

            if (pointer != null)
            {
                return(mapNode.GetReferencedObject <OpenApiExample>(ReferenceType.Example, pointer));
            }

            var example = new OpenApiExample();

            foreach (var property in mapNode)
            {
                property.ParseField(example, _exampleFixedFields, _examplePatternFields);
            }

            return(example);
        }
        /// <summary>
        /// Create a new instance of the <see cref="KeyValuePair{TKey, TValue}"/> class.
        /// </summary>
        /// <param name="name">Name of the example</param>
        /// <param name="summary">Summary of the example</param>
        /// <param name="description">Description of the example</param>
        /// <param name="instance">Example object.</param>
        /// <param name="namingStrategy"><see cref="NamingStrategy"/> instance.</param>
        /// <typeparam name="T">Type of the example object.</typeparam>
        /// <returns>Returns the new instance of the <see cref="KeyValuePair{TKey, TValue}"/> class. </returns>
        public static KeyValuePair <string, OpenApiExample> Resolve <T>(string name, string summary, string description, T instance, NamingStrategy namingStrategy = null)
        {
            name.ThrowIfNullOrWhiteSpace();
            instance.ThrowIfNullOrDefault();

            var resolver = new DefaultContractResolver()
            {
                NamingStrategy = namingStrategy ?? new DefaultNamingStrategy()
            };

            settings.ContractResolver = resolver;

            var example = new OpenApiExample()
            {
                Summary     = summary,
                Description = description,
                Value       = new OpenApiString(JsonConvert.SerializeObject(instance, settings)),
            };
            var kvp = new KeyValuePair <string, OpenApiExample>(name, example);

            return(kvp);
        }
        private static OpenApiExample CreateStructuredTypeExample(IEdmStructuredType structuredType)
        {
            OpenApiExample example = new OpenApiExample();

            OpenApiObject value = new OpenApiObject();

            IEdmEntityType entityType = structuredType as IEdmEntityType;

            // properties
            foreach (var property in structuredType.DeclaredProperties.OrderBy(p => p.Name))
            {
                // IOpenApiAny item;
                IEdmTypeReference propertyType = property.Type;

                IOpenApiAny item = GetTypeNameForExample(propertyType);

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

                value.Add(property.Name, item);
            }
            example.Value = value;
            return(example);
        }
Beispiel #21
0
 /// <summary>
 /// Visits <see cref="OpenApiExample"/> and child objects
 /// </summary>
 /// <param name="example"></param>
 internal void Walk(OpenApiExample example)
 {
     _visitor.Visit(example);
     Walk(example as IOpenApiExtensible);
 }
Beispiel #22
0
        public OpenApiDocument AddSecuritySchema(OpenApiDocument document, IList <HttpController> controllers, /*string authorizationUrl,*/ string tokenUrl)
        {
            string schemaName = "oauth";

            OpenApiSecurityScheme globalScheme = new OpenApiSecurityScheme();

            globalScheme.BearerFormat = "JWT";
            globalScheme.Description  = "OAuth 2.0";
            globalScheme.Type         = SecuritySchemeType.OAuth2;
            globalScheme.Name         = schemaName;
            globalScheme.Scheme       = "bearer";
            globalScheme.Flows        = new OpenApiOAuthFlows();

            globalScheme.Flows.Password = new OpenApiOAuthFlow()
            {
                //AuthorizationUrl = new Uri(authorizationUrl),
                TokenUrl = new Uri(tokenUrl),
            };
            globalScheme.Flows.ClientCredentials = new OpenApiOAuthFlow()
            {
                //AuthorizationUrl = new Uri(authorizationUrl),
                TokenUrl = new Uri(tokenUrl),
            };

            IList <string> globalScope = new List <string>();

            foreach (HttpController controller in controllers)
            {
                Type type = controller.GetType();
                foreach (MethodInfo method in type.GetMethods())
                {
                    HttpMethod     verb        = HttpMethod.UNKNOWN;
                    string         path        = "";
                    IList <string> localScopes = new List <string>();

                    //step 1: analyze attributes
                    foreach (Attribute attribute in method.GetCustomAttributes())
                    {
                        if (attribute is SKotstein.Net.Http.Attributes.Path)
                        {
                            SKotstein.Net.Http.Attributes.Path p = (SKotstein.Net.Http.Attributes.Path)attribute;
                            verb = p.Method;
                            path = p.Url;
                        }
                        if (attribute is skotstein.net.http.oauth.AuthorizationScope)
                        {
                            skotstein.net.http.oauth.AuthorizationScope s = (skotstein.net.http.oauth.AuthorizationScope)attribute;
                            if (!localScopes.Contains(s.Scope))
                            {
                                localScopes.Add(s.Scope);
                            }
                        }
                    }
                    //step 2: add scopes to operation
                    if (!String.IsNullOrWhiteSpace(path) && document.Paths.ContainsKey(path))
                    {
                        OpenApiPathItem  openApiPath = document.Paths[path];
                        OpenApiOperation operation   = null;
                        switch (verb)
                        {
                        case HttpMethod.GET:
                            if (openApiPath.Operations.ContainsKey(OperationType.Get))
                            {
                                operation = openApiPath.Operations[OperationType.Get];
                            }
                            break;

                        case HttpMethod.POST:
                            if (openApiPath.Operations.ContainsKey(OperationType.Post))
                            {
                                operation = openApiPath.Operations[OperationType.Post];
                            }
                            break;

                        case HttpMethod.PUT:
                            if (openApiPath.Operations.ContainsKey(OperationType.Put))
                            {
                                operation = openApiPath.Operations[OperationType.Put];
                            }
                            break;

                        case HttpMethod.DELETE:
                            if (openApiPath.Operations.ContainsKey(OperationType.Delete))
                            {
                                operation = openApiPath.Operations[OperationType.Delete];
                            }
                            break;

                        case HttpMethod.PATCH:
                            if (openApiPath.Operations.ContainsKey(OperationType.Patch))
                            {
                                operation = openApiPath.Operations[OperationType.Patch];
                            }
                            break;
                        }
                        if (operation != null)
                        {
                            OpenApiSecurityRequirement security = new OpenApiSecurityRequirement();
                            //OpenApiSecurityScheme scheme = new OpenApiSecurityScheme();
                            //scheme.Name = schemaName;
                            //security.Add(globalScheme, localScopes);
                            OpenApiSecurityScheme scheme    = new OpenApiSecurityScheme();
                            OpenApiReference      reference = new OpenApiReference();
                            reference.Id     = schemaName;
                            reference.Type   = ReferenceType.SecurityScheme;
                            scheme.Reference = reference;



                            security.Add(scheme, localScopes);
                            operation.Security.Add(security);

                            //step 3: add local scopes to global scopes
                            foreach (string scope in localScopes)
                            {
                                if (!globalScope.Contains(scope))
                                {
                                    globalScope.Add(scope);
                                }
                            }

                            //step 4: add 401 response (Unauthorized)
                            OpenApiResponse response401 = new OpenApiResponse();
                            response401.Description = "The client is unauthorized";
                            OpenApiMediaType mediaType401 = new OpenApiMediaType();
                            OpenApiSchema    schema401    = new OpenApiSchema();
                            OpenApiReference reference401 = new OpenApiReference();
                            reference401.Id     = "skotstein.app.ledserver.model.ErrorMessage";
                            reference401.Type   = ReferenceType.Schema;
                            schema401.Reference = reference401;
                            mediaType401.Schema = schema401;

                            OpenApiExample example401_0 = new OpenApiExample();
                            OpenApiString  openApiStringUnauthorized_0 = new OpenApiString("$EXAMPLE_Error_Message_MissingAccessToken");
                            example401_0.Value = openApiStringUnauthorized_0;
                            mediaType401.Examples.Add("Missing access token", example401_0);

                            OpenApiExample example401_1 = new OpenApiExample();
                            OpenApiString  openApiStringUnauthorized_1 = new OpenApiString("$EXAMPLE_Error_Message_InvalidAccessToken");
                            example401_1.Value = openApiStringUnauthorized_1;
                            mediaType401.Examples.Add("Invalid access token", example401_1);

                            OpenApiExample example401_2 = new OpenApiExample();
                            OpenApiString  openApiStringUnauthorized_2 = new OpenApiString("$EXAMPLE_Error_Message_TokenHasExpired");
                            example401_2.Value = openApiStringUnauthorized_2;
                            mediaType401.Examples.Add("Token has expired", example401_2);

                            response401.Content.Add("application/json", mediaType401);
                            operation.Responses.Add("401", response401);

                            //step 5: add 403 response (Forbidden)
                            OpenApiResponse response403 = new OpenApiResponse();
                            response403.Description = "The client is not allowed to access this resource. Make sure that the following scopes are granted to the client: ";
                            foreach (string scope in localScopes)
                            {
                                response403.Description += scope + " \n";
                            }
                            OpenApiMediaType mediaType403 = new OpenApiMediaType();
                            OpenApiSchema    schema403    = new OpenApiSchema();
                            OpenApiReference reference403 = new OpenApiReference();
                            reference403.Id     = "skotstein.app.ledserver.model.ErrorMessage";
                            reference403.Type   = ReferenceType.Schema;
                            schema403.Reference = reference403;
                            mediaType403.Schema = schema403;
                            OpenApiExample example403             = new OpenApiExample();
                            OpenApiString  openApiStringForbidden = new OpenApiString("$EXAMPLE_Error_Message_Forbidden");
                            example403.Value = openApiStringForbidden;
                            mediaType403.Examples.Add("Invalid scope", example403);
                            response403.Content.Add("application/json", mediaType403);
                            operation.Responses.Add("403", response403);
                        }
                    }
                }
            }


            foreach (string scope in globalScope)
            {
                string   description = "";
                string[] split       = scope.Split('-');
                if (split.Length == 2)
                {
                    description = "Grants " + split[1] + " access to " + split[0] + " resources";
                }

                globalScheme.Flows.Password.Scopes.Add(scope, description);
                globalScheme.Flows.ClientCredentials.Scopes.Add(scope, description);
            }

            document.Components.SecuritySchemes.Add(schemaName, globalScheme);
            return(document);
        }
Beispiel #23
0
        private static OpenApiExample ToOpenApiExample(this XElement element, TypeFetcher typeFetcher)
        {
            var exampleChildElements = element.Elements();

            if (!exampleChildElements.Any())
            {
                return(null);
            }

            var summaryElement = exampleChildElements.FirstOrDefault(p => p.Name == KnownXmlStrings.Summary);

            var openApiExample = new OpenApiExample();

            if (summaryElement != null)
            {
                openApiExample.Summary = summaryElement.Value;
            }

            var valueElement = exampleChildElements.FirstOrDefault(p => p.Name == KnownXmlStrings.Value);
            var urlElement   = exampleChildElements.FirstOrDefault(p => p.Name == KnownXmlStrings.Url);

            if (valueElement != null && urlElement != null)
            {
                throw new InvalidExampleException(SpecificationGenerationMessages.ProvideEitherValueOrUrlTag);
            }

            IOpenApiAny exampleValue = null;

            if (valueElement != null)
            {
                var seeNodes  = element.Descendants(KnownXmlStrings.See);
                var crefValue = seeNodes
                                .Select(node => node.Attribute(KnownXmlStrings.Cref)?.Value)
                                .FirstOrDefault(crefVal => crefVal != null);

                if (string.IsNullOrWhiteSpace(valueElement.Value) && string.IsNullOrWhiteSpace(crefValue))
                {
                    throw new InvalidExampleException(SpecificationGenerationMessages.ProvideValueForExample);
                }

                if (!string.IsNullOrWhiteSpace(crefValue))
                {
                    var typeName = crefValue.ExtractTypeNameFromFieldCref();
                    var type     = typeFetcher.LoadTypeFromCrefValues(new List <string> {
                        typeName
                    });
                    var fieldName = crefValue.ExtractFieldNameFromCref();

                    var fields = type.GetFields(BindingFlags.Public
                                                | BindingFlags.Static);
                    var field = fields.FirstOrDefault(f => f.Name == fieldName);

                    if (field == null)
                    {
                        var errorMessage = string.Format(
                            SpecificationGenerationMessages.FieldNotFound,
                            fieldName,
                            typeName);

                        throw new TypeLoadException(errorMessage);
                    }

                    exampleValue = new OpenApiStringReader().ReadFragment <IOpenApiAny>(
                        field.GetValue(null).ToString(),
                        OpenApiSpecVersion.OpenApi3_0,
                        out OpenApiDiagnostic _);
                }

                if (!string.IsNullOrWhiteSpace(valueElement.Value))
                {
                    exampleValue = new OpenApiStringReader()
                                   .ReadFragment <IOpenApiAny>(
                        valueElement.Value,
                        OpenApiSpecVersion.OpenApi3_0,
                        out OpenApiDiagnostic _);
                }

                openApiExample.Value = exampleValue;
            }

            if (urlElement != null)
            {
                openApiExample.ExternalValue = urlElement.Value;
            }

            return(openApiExample);
        }
 public override void Visit(OpenApiExample example)
 {
     EncodeCall();
     base.Visit(example);
 }
Beispiel #25
0
        private static OpenApiExample ToOpenApiExample(
            this XElement element,
            Dictionary <string, FieldValueInfo> crefFieldValueMap,
            List <GenerationError> generationErrors)
        {
            var exampleChildElements = element.Elements();

            if (!exampleChildElements.Any())
            {
                return(null);
            }

            var summaryElement = exampleChildElements.FirstOrDefault(p => p.Name == KnownXmlStrings.Summary);

            var openApiExample = new OpenApiExample();

            if (summaryElement != null)
            {
                openApiExample.Summary = summaryElement.Value;
            }

            var valueElement = exampleChildElements.FirstOrDefault(p => p.Name == KnownXmlStrings.Value);
            var urlElement   = exampleChildElements.FirstOrDefault(p => p.Name == KnownXmlStrings.Url);

            if (valueElement != null && urlElement != null)
            {
                generationErrors.Add(
                    new GenerationError
                {
                    ExceptionType = nameof(InvalidExampleException),
                    Message       = SpecificationGenerationMessages.ProvideEitherValueOrUrlTag
                });

                return(null);
            }

            IOpenApiAny exampleValue = null;

            if (valueElement != null)
            {
                var seeNodes  = element.Descendants(KnownXmlStrings.See);
                var crefValue = seeNodes
                                .Select(node => node.Attribute(KnownXmlStrings.Cref)?.Value)
                                .FirstOrDefault(crefVal => crefVal != null);

                if (string.IsNullOrWhiteSpace(valueElement.Value) && string.IsNullOrWhiteSpace(crefValue))
                {
                    generationErrors.Add(
                        new GenerationError
                    {
                        ExceptionType = nameof(InvalidExampleException),
                        Message       = SpecificationGenerationMessages.ProvideValueForExample
                    });

                    return(null);
                }

                if (!string.IsNullOrWhiteSpace(valueElement.Value))
                {
                    exampleValue = new OpenApiStringReader()
                                   .ReadFragment <IOpenApiAny>(
                        valueElement.Value,
                        OpenApiSpecVersion.OpenApi3_0,
                        out OpenApiDiagnostic _);
                }

                if (!string.IsNullOrWhiteSpace(crefValue) && crefFieldValueMap.ContainsKey(crefValue))
                {
                    var fieldValueInfo = crefFieldValueMap[crefValue];

                    if (fieldValueInfo.Error != null)
                    {
                        generationErrors.Add(fieldValueInfo.Error);

                        return(null);
                    }

                    exampleValue = new OpenApiStringReader().ReadFragment <IOpenApiAny>(
                        fieldValueInfo.Value,
                        OpenApiSpecVersion.OpenApi3_0,
                        out OpenApiDiagnostic _);
                }

                openApiExample.Value = exampleValue;
            }

            if (urlElement != null)
            {
                openApiExample.ExternalValue = urlElement.Value;
            }

            return(openApiExample);
        }
 /// <summary>
 /// Visits <see cref="OpenApiExample"/>
 /// </summary>
 public virtual void Visit(OpenApiExample example)
 {
 }