diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/AssemblyLoader/AppDomainCreator.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/AssemblyLoader/AppDomainCreator.cs new file mode 100644 index 0000000..7375985 --- /dev/null +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/AssemblyLoader/AppDomainCreator.cs @@ -0,0 +1,68 @@ +// ------------------------------------------------------------ +// 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.CSharpAnnotations.DocumentGeneration.AssemblyLoader +{ + +#if NETFRAMEWORK + /// + /// Creates a separate app domain. + /// + /// The type for which instance needs to be created in new app domain. + internal sealed class AppDomainCreator : MarshalByRefObject, IDisposable + { + /// + /// Initializes new instance of . + /// + public AppDomainCreator() + { + var setupInformation = AppDomain.CurrentDomain.SetupInformation; + + // Specify that the new domain should make a copy to the shadow directory, preventing + // the locking of the assemblies. + setupInformation.ShadowCopyFiles = "true"; + + // The privateBinPath is a ; separated list of paths located in the base path of the + // application where the CLR will attempt to locate assemblies during the load process. + // Here we add the location where we will copy dlls. + setupInformation.PrivateBinPath += ";DefaultGenerationBin"; + + // Setup the domain. + Domain = AppDomain.CreateDomain( + "AppDomain" + Guid.NewGuid(), + AppDomain.CurrentDomain.Evidence, + setupInformation ); + + var type = typeof( T ); + + Object = (T) Domain.CreateInstanceAndUnwrap( type.Assembly.FullName, type.FullName ); + } + + /// + /// Gets the . + /// + public AppDomain Domain { get; private set; } + + /// + /// Gets the instance of the object created in the new app domain. + /// + public T Object { get; } + + /// + /// Unloads the app domain. + /// + public void Dispose() + { + if ( Domain != null ) + { + AppDomain.Unload( Domain ); + Domain = null; + } + } + } +#endif +} \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/AssemblyLoader/AssemblyLoadUtility.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/AssemblyLoader/AssemblyLoadUtility.cs new file mode 100644 index 0000000..81e758c --- /dev/null +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/AssemblyLoader/AssemblyLoadUtility.cs @@ -0,0 +1,60 @@ +// ------------------------------------------------------------ +// 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.Diagnostics; +using System.Linq; +using System.Reflection; + +namespace Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.AssemblyLoader +{ + /// + /// Contains reusable methods for loading assembly. + /// + internal static class AssemblyLoadUtility + { + /// + /// Try load the assembly by using provided assembly by name and version if provided. + /// + /// The assembly paths. + /// The assembly name to load.It's not assembly full name. + /// The assembly version to load. + /// The assembly if able to load, otherwise null. + internal static Assembly TryLoadByNameOrVersion( + IList assemblyPaths, + string assemblyName, + string assemblyVersion = null) + { + var assemblyPath = assemblyPaths.FirstOrDefault(path => path.EndsWith(assemblyName + ".dll")); + + if (!string.IsNullOrWhiteSpace(assemblyPath)) + { + if(!string.IsNullOrWhiteSpace(assemblyVersion)) + { + try + { + var info = FileVersionInfo.GetVersionInfo(assemblyPath); + if (info.FileVersion.StartsWith(assemblyVersion)) + { + return Assembly.LoadFrom(assemblyPath); + } + } + catch (Exception) + { + // Do nothing. + } + } + else + { + return Assembly.LoadFrom(assemblyPath); + } + + } + + return null; + } + } +} \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/AssemblyLoader/AssemblyLoader.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/AssemblyLoader/AssemblyLoader.cs new file mode 100644 index 0000000..9d69414 --- /dev/null +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/AssemblyLoader/AssemblyLoader.cs @@ -0,0 +1,422 @@ +// ------------------------------------------------------------ +// 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 System.Reflection; +using System.Xml.Linq; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Extensions; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models.KnownStrings; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.ReferenceRegistries; +using Microsoft.OpenApi.Extensions; +using Newtonsoft.Json; + +#if !NETFRAMEWORK +using System.Runtime.Loader; +#endif + +namespace Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.AssemblyLoader +{ +#if !NETFRAMEWORK + /// + /// Class is used to load assemblies for .net framework and .net core runtimes. + /// + /// + /// For .net framework, the class is loaded in seperate app domain and CurrentDomain.AssemblyResolve event + /// handler is used to resolve the assembly conflict. + /// For .net core custom assembly load context is used to resolve the assemlby conflict. + /// + internal class AssemblyLoader + { + public CustomAssemblyLoadContext Context { get; } + + public AssemblyLoader() + { + Context = new CustomAssemblyLoadContext(); + AssemblyLoadContext.Default.Resolving += (context, name) => Context.Resolve(name); + } +#else + /// + /// Class is used to load assemblies for .net framework and .net core runtimes. + /// + /// + /// For .net framework, the class is loaded in seperate app domain and CurrentDomain.AssemblyResolve event + /// handler is used to resolve the assembly conflict. + /// For .net core custom assembly load context is used to resolve the assemlby conflict. + /// + internal class AssemblyLoader : MarshalByRefObject + { + +#endif + + internal void RegisterAssemblyPaths(IList assemblyPaths) + { +#if !NETFRAMEWORK + Context.AssemblyPaths = assemblyPaths; +#else + AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => + { + Version version = null; + + var separatorIndex = args.Name.IndexOf(",", StringComparison.Ordinal); + + // Fetch assembly name(Newtonsoft.Json) from args value like below + // Newtonsoft.Json, Version=11.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed + var assemblyName = separatorIndex > 0 ? args.Name.Substring(0, separatorIndex) : args.Name; + + if (separatorIndex > 0) + { + // Fetch assembly version(11.0.0.0) from args value like below + // Newtonsoft.Json, Version=11.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed + separatorIndex = args.Name.IndexOf("=", separatorIndex, StringComparison.Ordinal); + if (separatorIndex > 0) + { + var endIndex = args.Name.IndexOf(",", separatorIndex, StringComparison.Ordinal); + if (endIndex > 0) + { + var parts = args.Name + .Substring(separatorIndex + 1, endIndex - separatorIndex - 1) + .Split('.'); + + version = new Version(int.Parse(parts[0]), + int.Parse(parts[1]), + int.Parse(parts[2]), + int.Parse(parts[3])); + } + } + } + + var existingAssembly = AppDomain.CurrentDomain.GetAssemblies() + .FirstOrDefault(a => a.FullName == args.Name); + if (existingAssembly != null) + { + return existingAssembly; + } + + if (version != null) + { + var assemblyByVersion = AssemblyLoadUtility.TryLoadByNameOrVersion( + assemblyPaths, + assemblyName, + version.Major + "." + version.Minor + "." + version.Build + "."); + + if (assemblyByVersion != null) + { + return assemblyByVersion; + } + + assemblyByVersion = AssemblyLoadUtility.TryLoadByNameOrVersion( + assemblyPaths, + assemblyName, + version.Major + "." + version.Minor + "."); + + if (assemblyByVersion != null) + { + return assemblyByVersion; + } + + assemblyByVersion = + AssemblyLoadUtility.TryLoadByNameOrVersion(assemblyPaths, assemblyName, version.Major + "."); + + if (assemblyByVersion != null) + { + return assemblyByVersion; + } + } + + var assembly = AssemblyLoadUtility.TryLoadByNameOrVersion(assemblyPaths, assemblyName); + if (assembly != null) + { + return assembly; + } + + return null; + }; +#endif + } + + /// + /// Builds by reflecting into contract assemblies. + /// + /// The contract assemlby paths. + /// The operation xelements. + /// The property xelements + /// The document variant element name. + /// + /// Serialized + public string BuildInternalGenerationContext( + IList contractAssembliesPaths, + IList operationElements, + IList propertyElements, + string documentVariantElementName, + InternalSchemaGenerationSettings internalSchemaGenerationSettings) + { + var crefSchemaMap = new Dictionary(); + + List xPropertyElements = propertyElements.Select(XElement.Parse).ToList(); + + var propertyMap = new Dictionary(); + + foreach (var xPropertyElement in xPropertyElements) + { + var name = xPropertyElement + .Attributes(KnownXmlStrings.Name)?.FirstOrDefault()?.Value?.Split(':')[1]; + var description = xPropertyElement.Element(KnownXmlStrings.Summary)?.Value.RemoveBlankLines(); + + if (!propertyMap.ContainsKey(name)) + { + propertyMap.Add(name, description); + } + } + + var referenceRegistryMap = new Dictionary(); + + var schemaGenerationSettings = new SchemaGenerationSettings(new DefaultPropertyNameResolver()); + + if (internalSchemaGenerationSettings.PropertyNameResolverName == + typeof(CamelCasePropertyNameResolver).FullName) + { + schemaGenerationSettings = new SchemaGenerationSettings(new CamelCasePropertyNameResolver()); + } + + var internalGenerationContext = new InternalGenerationContext(); + +#if !NETFRAMEWORK + var typeFetcher = new TypeFetcher(contractAssembliesPaths, Context); +#else + var typeFetcher = new TypeFetcher(contractAssembliesPaths); +#endif + + List xOperationElements = operationElements.Select(XElement.Parse).ToList(); + + foreach (var xOperationElement in xOperationElements) + { + if(!referenceRegistryMap.ContainsKey(DocumentVariantInfo.Default)) + { + referenceRegistryMap.Add( + DocumentVariantInfo.Default, + new SchemaReferenceRegistry(schemaGenerationSettings, propertyMap)); + } + + // Recursively build the various cref-schema, cref-fieldValue map. + BuildMap( + xOperationElement, + crefSchemaMap, + internalGenerationContext.CrefToFieldValueMap, + typeFetcher, + referenceRegistryMap[DocumentVariantInfo.Default]); + + var customElements = xOperationElement.Descendants(documentVariantElementName); + + // Build the various cref-schema, cref-fieldValue map for each customElement. + foreach (var customElement in customElements) + { + var documentVariantInfo = new DocumentVariantInfo + { + Categorizer = customElement.Name.LocalName.Trim(), + Title = customElement.Value.Trim() + }; + + if (!referenceRegistryMap.ContainsKey(documentVariantInfo)) + { + referenceRegistryMap.Add( + documentVariantInfo, + new SchemaReferenceRegistry(schemaGenerationSettings, propertyMap)); + } + + BuildMap( + xOperationElement, + crefSchemaMap, + internalGenerationContext.CrefToFieldValueMap, + typeFetcher, + referenceRegistryMap[documentVariantInfo]); + } + } + + foreach(var key in referenceRegistryMap.Keys) + { + var references = referenceRegistryMap[key].References; + + internalGenerationContext.VariantSchemaReferenceMap.Add( + key.ToString(), + references.ToDictionary(k => k.Key, k => k.Value.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0))); + } + + internalGenerationContext.CrefToSchemaMap = crefSchemaMap; + + // Serialize the context to transfer across app domain. + var document = JsonConvert.SerializeObject(internalGenerationContext); + + return document; + } + + /// + /// Fetches all the cref's from the provided operation element and build cref --> schema, cref --> field value + /// maps. + /// + /// The XElement to fetch cref and see tags for. + /// The cref to map. + /// The cref to map. + /// The type fetcher used to fetch type, field information. + /// . + private void BuildMap( + XElement currentXElement, + Dictionary crefSchemaMap, + Dictionary crefFieldMap, + TypeFetcher typeFetcher, + SchemaReferenceRegistry schemaReferenceRegistry) + { + if (currentXElement == null) + { + return; + } + + var cref = currentXElement.Attribute(KnownXmlStrings.Cref)?.Value.Trim(); + + if (!string.IsNullOrWhiteSpace(cref)) + { + var allListedTypes = new List() { cref }; + + if (allListedTypes.Where(i => i.StartsWith("F:")).Any()) + { + BuildCrefFieldValueMap(allListedTypes.FirstOrDefault(), crefFieldMap, typeFetcher); + } + else + { + BuildCrefSchemaMap(allListedTypes, crefSchemaMap, typeFetcher, schemaReferenceRegistry); + } + } + + if (!currentXElement.Elements().Any()) + { + return; + } + + var seeNodes = currentXElement.Elements().Where(i => i.Name == KnownXmlStrings.See); + + if (seeNodes.Any()) + { + var allListedTypes = seeNodes + .Select(node => node.Attribute(KnownXmlStrings.Cref)?.Value) + .Where(crefValue => crefValue != null).ToList(); + + if (allListedTypes.Where(i => i.StartsWith("F:")).Any()) + { + BuildCrefFieldValueMap(allListedTypes.FirstOrDefault(), crefFieldMap, typeFetcher); + } + else + { + BuildCrefSchemaMap(allListedTypes, crefSchemaMap, typeFetcher, schemaReferenceRegistry); + } + } + + var remainingNodes = currentXElement.Elements().Where(i => i.Name != KnownXmlStrings.See); + + foreach (var remainingNode in remainingNodes) + { + BuildMap( + remainingNode, + crefSchemaMap, + crefFieldMap, + typeFetcher, + schemaReferenceRegistry); + } + } + + /// + /// Generates schema for the provided list of types and store them in the provided dictionary. + /// + /// The listed types to fetch schema for. + /// The cref to map. + /// The type fetcher used to fetch type information using reflection. + /// . + private void BuildCrefSchemaMap( + IList allListedTypes, + Dictionary crefSchemaMap, + TypeFetcher typeFetcher, + SchemaReferenceRegistry schemaReferenceRegistry) + { + var key = allListedTypes.ToCrefKey(); + + var schemaInfo = new InternalSchemaGenerationInfo(); + try + { + var type = typeFetcher.LoadTypeFromCrefValues(allListedTypes); + var schema = schemaReferenceRegistry.FindOrAddReference(type); + schemaInfo.Schema = schema.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); + } + catch (Exception e) + { + var error = new GenerationError + { + ExceptionType = e.GetType().Name, + Message = e.Message + }; + + schemaInfo.Error = error; + } + + if (!crefSchemaMap.ContainsKey(key)) + { + crefSchemaMap.Add(key, schemaInfo); + } + } + + /// + /// Provided a field cref value, fetches the field value using reflection. + /// + /// The cref value for the field. + /// The cref value to map. + /// The type fetcher used to fetch field value from the loaded assemblies. + private void BuildCrefFieldValueMap( + string crefValue, + Dictionary crefFieldMap, + TypeFetcher typeFetcher) + { + if (string.IsNullOrWhiteSpace(crefValue) || crefFieldMap.ContainsKey(crefValue)) + { + return; + } + + var fieldValueInfo = new FieldValueInfo(); + + try + { + var typeName = crefValue.ExtractTypeNameFromFieldCref(); + var type = typeFetcher.LoadTypeFromCrefValues(new List { 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); + } + + fieldValueInfo.Value = field.GetValue(null).ToString(); + } + catch (Exception e) + { + var error = new GenerationError + { + ExceptionType = e.GetType().Name, + Message = e.Message + }; + + fieldValueInfo.Error = error; + } + + crefFieldMap.Add(crefValue, fieldValueInfo); + } + } +} \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/AssemblyLoader/CustomAssemblyLoadContext.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/AssemblyLoader/CustomAssemblyLoadContext.cs new file mode 100644 index 0000000..2eb9d13 --- /dev/null +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/AssemblyLoader/CustomAssemblyLoadContext.cs @@ -0,0 +1,166 @@ +// ------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. +// ------------------------------------------------------------ + +#if !NETFRAMEWORK + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Runtime.Loader; +using System.Text; +using System.Threading.Tasks; +using System.IO; +using System.Diagnostics; + +namespace Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.AssemblyLoader +{ + internal class CustomAssemblyLoadContext : AssemblyLoadContext + { + private readonly HashSet _assembliesLoadedByAssemblyName = new HashSet(); + private bool _isResolving = false; + + internal Dictionary Assemblies { get; } = new Dictionary(); + + internal IList AssemblyPaths { get; set; } + + public Assembly Resolve(AssemblyName args) + { + if (!_isResolving) + return Load(args); + else + return null; + } + + protected override Assembly Load(AssemblyName args) + { + if (Assemblies.ContainsKey(args.Name)) + { + return Assemblies[args.Name]; + } + + var separatorIndex = args.Name.IndexOf(",", StringComparison.Ordinal); + var assemblyName = separatorIndex > 0 ? args.Name.Substring(0, separatorIndex) : args.Name; + + var assembly = TryLoadExistingAssemblyName(args.FullName); + + if (assembly != null) + { + Assemblies[args.Name] = assembly; + return assembly; + } + + // Try to load assembly using version. + var version = args.Version; + if (version != null) + { + var assemblyByVersion = TryLoadByVersion(AssemblyPaths, assemblyName, version.Major + "." + version.Minor + "." + version.Build + "."); + if (assemblyByVersion != null) + { + Assemblies[args.Name] = assemblyByVersion; + return assemblyByVersion; + } + + assemblyByVersion = TryLoadByVersion(AssemblyPaths, assemblyName, version.Major + "." + version.Minor + "."); + if (assemblyByVersion != null) + { + Assemblies[args.Name] = assemblyByVersion; + return assemblyByVersion; + } + + assemblyByVersion = TryLoadByVersion(AssemblyPaths, assemblyName, version.Major + "."); + if (assemblyByVersion != null) + { + Assemblies[args.Name] = assemblyByVersion; + return assemblyByVersion; + } + } + + // Try to load assembly using full name, which includes version too. + assembly = TryLoadByAssemblyName(args.FullName); + if (assembly != null) + { + Assemblies[args.Name] = assembly; + return assembly; + } + + // Try to load assembly using short assembly name. + assembly = AssemblyLoadUtility.TryLoadByNameOrVersion(AssemblyPaths, assemblyName); + if (assembly != null) + { + Assemblies[args.Name] = assembly; + return assembly; + } + + Assemblies[args.Name] = TryLoadByAssemblyName(assemblyName); + return Assemblies[args.Name]; + } + + private Assembly TryLoadExistingAssemblyName(string assemblyName) + { + try + { + _isResolving = true; + return Default.LoadFromAssemblyName(new AssemblyName(assemblyName)); + } + catch (Exception) + { + // Do nothing. + } + finally + { + _isResolving = false; + } + + return null; + } + + private Assembly TryLoadByAssemblyName(string assemblyName) + { + if (!_assembliesLoadedByAssemblyName.Contains(assemblyName)) + { + try + { + _assembliesLoadedByAssemblyName.Add(assemblyName); + return LoadFromAssemblyName(new AssemblyName(assemblyName)); + } + catch (Exception) + { + // Do nothing. + } + } + + return null; + } + + private Assembly TryLoadByVersion( + IList assemblyPaths, + string assemblyName, + string assemblyVersion) + { + var assemblyPath = assemblyPaths.FirstOrDefault(path => path.EndsWith(assemblyName + ".dll")); + + if (!string.IsNullOrWhiteSpace(assemblyPath)) + { + try + { + var info = FileVersionInfo.GetVersionInfo(assemblyPath); + if (info.FileVersion.StartsWith(assemblyVersion)) + { + return LoadFromAssemblyPath(assemblyPath); + } + } + catch (Exception) + { + // Do nothing. + } + } + + return null; + } + } +} + +#endif \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentConfigFilters/DocumentVariantAttributesFilter.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentConfigFilters/DocumentVariantAttributesFilter.cs index c1636ea..9038dbe 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentConfigFilters/DocumentVariantAttributesFilter.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentConfigFilters/DocumentVariantAttributesFilter.cs @@ -3,6 +3,7 @@ // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ +using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; @@ -30,70 +31,92 @@ public class DocumentVariantAttributesFilter : IDocumentConfigFilter /// Thrown when there is a conflict /// between the attributes in the existing document variant info and the new one. /// - public void Apply( + /// The list of generation errors, if any produced when processing the filter. + public IList Apply( IDictionary documents, XElement element, IList xmlDocuments, DocumentConfigFilterSettings settings) { - var variantElements = element.Elements(KnownXmlStrings.Variant); - - foreach (var variantElement in variantElements) + var generationErrors = new List(); + + if (element == null || xmlDocuments == null) + { + return generationErrors; + } + + + try { - // First, populate the document variant info attributes using the document variant option. - var variantOptions = variantElement.Element(KnownXmlStrings.Options)?.Elements(KnownXmlStrings.Option); + var variantElements = element.Elements(KnownXmlStrings.Variant); - if (variantOptions != null) + foreach (var variantElement in variantElements) { - foreach (var variantOption in variantOptions) + // First, populate the document variant info attributes using the document variant option. + var variantOptions = variantElement.Element(KnownXmlStrings.Options)?.Elements(KnownXmlStrings.Option); + + if (variantOptions != null) { - var documentVariantInfo = new DocumentVariantInfo + foreach (var variantOption in variantOptions) { - Title = variantOption.Value, - Categorizer = variantElement.Element(KnownXmlStrings.Name)?.Value - }; + var documentVariantInfo = new DocumentVariantInfo + { + Title = variantOption.Value, + Categorizer = variantElement.Element(KnownXmlStrings.Name)?.Value + }; - foreach (var attribute in variantOption.Attributes()) - { - if (!documentVariantInfo.Attributes.ContainsKey(attribute.Name.ToString())) + foreach (var attribute in variantOption.Attributes()) { - documentVariantInfo.Attributes[attribute.Name.ToString()] = attribute.Value; + if (!documentVariantInfo.Attributes.ContainsKey(attribute.Name.ToString())) + { + documentVariantInfo.Attributes[attribute.Name.ToString()] = attribute.Value; + } } - } - PopulateAttributesInExistingDocumentVariantInfo(documents, documentVariantInfo); + PopulateAttributesInExistingDocumentVariantInfo(documents, documentVariantInfo); + } } - } - // Second, populate the document variant info attributes using the information from the documents. - var allCategorizerNodes = new List(); + // Second, populate the document variant info attributes using the information from the documents. + var allCategorizerNodes = new List(); - foreach (var xmlDocument in xmlDocuments) - { - allCategorizerNodes.AddRange( - xmlDocument.Descendants(variantElement.Element(KnownXmlStrings.Name)?.Value)); - } - - foreach (var categorizerNode in allCategorizerNodes) - { - var documentVariantInfo = new DocumentVariantInfo + foreach (var xmlDocument in xmlDocuments) { - Title = categorizerNode.Value, - Categorizer = categorizerNode.Name.ToString() - }; + allCategorizerNodes.AddRange( + xmlDocument.Descendants(variantElement.Element(KnownXmlStrings.Name)?.Value)); + } - foreach (var attribute in categorizerNode.Attributes()) + foreach (var categorizerNode in allCategorizerNodes) { - if (!documentVariantInfo.Attributes.ContainsKey(attribute.Name.ToString())) + var documentVariantInfo = new DocumentVariantInfo { - documentVariantInfo.Attributes[attribute.Name.ToString()] = attribute.Value; + Title = categorizerNode.Value, + Categorizer = categorizerNode.Name.ToString() + }; + + foreach (var attribute in categorizerNode.Attributes()) + { + if (!documentVariantInfo.Attributes.ContainsKey(attribute.Name.ToString())) + { + documentVariantInfo.Attributes[attribute.Name.ToString()] = attribute.Value; + } } - } - PopulateAttributesInExistingDocumentVariantInfo(documents, documentVariantInfo); + PopulateAttributesInExistingDocumentVariantInfo(documents, documentVariantInfo); + } } } + catch (Exception ex) + { + generationErrors.Add( + new GenerationError + { + Message = ex.Message, + ExceptionType = ex.GetType().Name + }); + } + return generationErrors; } private void PopulateAttributesInExistingDocumentVariantInfo( diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentConfigFilters/IDocumentConfigFilter.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentConfigFilters/IDocumentConfigFilter.cs index 2a144de..d834487 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentConfigFilters/IDocumentConfigFilter.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentConfigFilters/IDocumentConfigFilter.cs @@ -30,7 +30,8 @@ public interface IDocumentConfigFilter : IFilter /// The list of XML documentations provided in /// . /// - void Apply( + /// The list of generation errors, if any produced when processing the filter. + IList Apply( IDictionary documents, XElement documentConfigElement, IList xmlDocuments, diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentFilters/AssemblyNameToInfoFilter.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentFilters/AssemblyNameToInfoFilter.cs index acada6b..56887a1 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentFilters/AssemblyNameToInfoFilter.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentFilters/AssemblyNameToInfoFilter.cs @@ -3,10 +3,12 @@ // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ +using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using System.Xml.XPath; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; using Microsoft.OpenApi.Models; namespace Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.DocumentFilters @@ -24,28 +26,45 @@ public class AssemblyNameToInfoFilter : IDocumentFilter /// The list of documents representing the annotation xmls. /// Settings for document filters. /// - public void Apply( + /// The list of generation errors, if any produced when processing the filter. + public IList Apply( OpenApiDocument specificationDocument, IList xmlDocuments, DocumentFilterSettings settings, OpenApiDocumentGenerationSettings openApiDocumentGenerationSettings) { - // Find the xml document that contains member tag with url and verb, - // as that should be the service api documenation xml. - var xmlDocument = xmlDocuments - .FirstOrDefault(i => i.XPathSelectElement("//doc/members/member[url and verb]") != null); + var generationErrors = new List(); - if (xmlDocument == null) + try { - return; - } + // Find the xml document that contains member tag with url and verb, + // as that should be the service api documenation xml. + var xmlDocument = xmlDocuments + .FirstOrDefault(i => i.XPathSelectElement("//doc/members/member[url and verb]") != null); + + if (xmlDocument == null) + { + return generationErrors; + } - specificationDocument.Info = new OpenApiInfo + specificationDocument.Info = new OpenApiInfo + { + Title = xmlDocument.XPathSelectElement("//doc/assembly/name")?.Value, + Version = settings.OpenApiDocumentVersion, + Description = settings.OpenApiInfoDescription + }; + } + catch(Exception ex) { - Title = xmlDocument.XPathSelectElement("//doc/assembly/name")?.Value, - Version = settings.OpenApiDocumentVersion, - Description = settings.OpenApiInfoDescription - }; + generationErrors.Add( + new GenerationError + { + Message = ex.Message, + ExceptionType = ex.GetType().Name + }); + } + + return generationErrors; } } } \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentFilters/DocumentFilterSettings.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentFilters/DocumentFilterSettings.cs index a542bd4..01e8d23 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentFilters/DocumentFilterSettings.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentFilters/DocumentFilterSettings.cs @@ -26,10 +26,5 @@ public class DocumentFilterSettings /// Gets the reference registry manager. /// public ReferenceRegistryManager ReferenceRegistryManager { get; set; } - - /// - /// Gets or sets the type fetcher. - /// - public TypeFetcher TypeFetcher { get; set; } } } \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentFilters/IDocumentFilter.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentFilters/IDocumentFilter.cs index 2e89880..81e2134 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentFilters/IDocumentFilter.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentFilters/IDocumentFilter.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Xml.Linq; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.OperationFilters; using Microsoft.OpenApi.Models; @@ -24,7 +25,8 @@ public interface IDocumentFilter : IFilter /// . /// /// - void Apply( + /// The list of generation errors, if any produced when processing the filter. + IList Apply( OpenApiDocument openApiDocument, IList xmlDocuments, DocumentFilterSettings settings, diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentFilters/MemberSummaryToSchemaDescriptionFilter.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentFilters/MemberSummaryToSchemaDescriptionFilter.cs deleted file mode 100644 index ff6d959..0000000 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentFilters/MemberSummaryToSchemaDescriptionFilter.cs +++ /dev/null @@ -1,139 +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 System.Reflection; -using System.Xml.Linq; -using System.Xml.XPath; -using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Extensions; -using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models.KnownStrings; -using Microsoft.OpenApi.Models; - -namespace Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.DocumentFilters -{ - /// - /// Filter to parse the values from the summary tags for all the properties - /// to populate descriptions in the schema. - /// - public class MemberSummaryToSchemaDescriptionFilter : IDocumentFilter - { - /// - /// Parses the values from the summary for all the properties to populate descriptions in the schema. - /// - /// The Open API specification document to be updated. - /// The list of documents representing the annotation xmls. - /// Settings for document filters. - /// - public void Apply( - OpenApiDocument openApiDocument, - IList xmlDocuments, - DocumentFilterSettings settings, - OpenApiDocumentGenerationSettings openApiDocumentGenerationSettings) - { - if (openApiDocument == null) - { - throw new ArgumentNullException(nameof(openApiDocument)); - } - - if (settings == null) - { - throw new ArgumentNullException(nameof(settings)); - } - - if (xmlDocuments == null) - { - throw new ArgumentNullException(nameof(xmlDocuments)); - } - - var propertyMembers = new List(); - - foreach (var xmlDocument in xmlDocuments) - { - propertyMembers.AddRange(xmlDocument.XPathSelectElements("//doc/members/member") - .Where( - m => m.Attribute(KnownXmlStrings.Name) != null && - m.Attribute(KnownXmlStrings.Name).Value.StartsWith("P:"))); - } - - // Fetches distinct type names like - // Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests.Contracts.SampleBaseObject - // From property memeber names like - // P:Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests.Contracts.SampleBaseObject.SampleBaseProprety - var typeNames = propertyMembers - .Attributes(KnownXmlStrings.Name) - .Select(i => - string.Join(".", i.Value.Split('.').Take(i.Value.Split('.').Length - 1)) - .Substring(2)) - .Distinct() - .ToList(); - - foreach (var typeName in typeNames) - { - // We need to sanitize class name to match the format in the schema reference registry. - // Note that this class may also match several classes in the registry given that generics - // with different types are treated as different schemas. - // For example, summary information for properties in class name A - // should apply to those properties in schema A, A_B_, and A_B_C__ as well. - var sanitizedClassName = typeName.SanitizeClassName(); - - var schemas = openApiDocument.Components.Schemas.Where( - s => s.Key == sanitizedClassName || - s.Key.StartsWith(sanitizedClassName + "_")) - .ToList(); - - if (!schemas.Any()) - { - continue; - } - - var typeInfo = settings.TypeFetcher.LoadType(typeName); - - var typesToFetchPropertiesFor = settings.TypeFetcher.GetBaseTypes(typeInfo); - typesToFetchPropertiesFor.Add(typeInfo); - - var propertiesMap = new Dictionary(); - - foreach (var type in typesToFetchPropertiesFor) - { - foreach (var property in type.GetProperties()) - { - if (!propertiesMap.ContainsKey(property.Name)) - { - propertiesMap.Add(property.Name, property); - } - } - } - - foreach (var property in propertiesMap.Keys) - { - var propertyName = openApiDocumentGenerationSettings - .SchemaGenerationSettings - .PropertyNameResolver - .ResolvePropertyName(propertiesMap[property]); - - foreach (var schema in schemas) - { - var propertyMember = propertyMembers.FirstOrDefault( - i => i.Attribute(KnownXmlStrings.Name)?.Value == - $"P:{propertiesMap[property].DeclaringType}.{property}"); - - if (propertyMember == null) - { - continue; - } - - if (schema.Value.Properties.ContainsKey(propertyName)) - { - schema.Value.Properties[propertyName].Description = - propertyMember.Element(KnownXmlStrings.Summary)?.Value.RemoveBlankLines(); - } - } - } - } - } - } -} \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentFilters/SecurityToSecurityRequirementDocumentFilter.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentFilters/SecurityToSecurityRequirementDocumentFilter.cs index 27218f9..e9f7245 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentFilters/SecurityToSecurityRequirementDocumentFilter.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentFilters/SecurityToSecurityRequirementDocumentFilter.cs @@ -8,6 +8,7 @@ using System.Linq; using System.Xml.Linq; using System.Xml.XPath; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models.KnownStrings; using Microsoft.OpenApi.Models; @@ -27,55 +28,72 @@ public class SecurityToSecurityRequirementDocumentFilter : IDocumentFilter /// The list of documents representing the annotation xmls. /// Settings for document filters. /// - public void Apply( + /// The list of generation errors, if any produced when processing the filter. + public IList Apply( OpenApiDocument openApiDocument, IList xmlDocuments, DocumentFilterSettings settings, OpenApiDocumentGenerationSettings openApiDocumentGenerationSettings) { - if (openApiDocument == null) - { - throw new ArgumentNullException( nameof( openApiDocument ) ); - } + var generationErrors = new List(); - if (settings == null) + try { - throw new ArgumentNullException( nameof( settings ) ); - } + if (openApiDocument == null) + { + throw new ArgumentNullException(nameof(openApiDocument)); + } - if (xmlDocuments == null) - { - throw new ArgumentNullException( nameof( xmlDocuments ) ); - } + if (settings == null) + { + throw new ArgumentNullException(nameof(settings)); + } - var securityElements = new List(); + if (xmlDocuments == null) + { + throw new ArgumentNullException(nameof(xmlDocuments)); + } - foreach (var xmlDocument in xmlDocuments) - { - securityElements.AddRange( xmlDocument.XPathSelectElements( "//doc/members/member" ) - .Where( - m => m.Attribute( KnownXmlStrings.Name ) != null && - m.Attribute( KnownXmlStrings.Name ).Value.StartsWith( "T:" ) ) - .Elements() - .Where( p => p.Name == KnownXmlStrings.Security ) ); - } + var securityElements = new List(); - if (!securityElements.Any()) - { - return; - } + foreach (var xmlDocument in xmlDocuments) + { + securityElements.AddRange(xmlDocument.XPathSelectElements("//doc/members/member") + .Where( + m => m.Attribute(KnownXmlStrings.Name) != null && + m.Attribute(KnownXmlStrings.Name).Value.StartsWith("T:")) + .Elements() + .Where(p => p.Name == KnownXmlStrings.Security)); + } - var openApiSecurityRequirement = new OpenApiSecurityRequirement(); - var securitySchemeRegistry = settings.ReferenceRegistryManager.SecuritySchemeReferenceRegistry; + if (!securityElements.Any()) + { + return generationErrors; + } - foreach (var securityElement in securityElements) - { - var securityScheme = securitySchemeRegistry.FindOrAddReference(securityElement); + var openApiSecurityRequirement = new OpenApiSecurityRequirement(); + var securitySchemeRegistry = settings.ReferenceRegistryManager.SecuritySchemeReferenceRegistry; + + foreach (var securityElement in securityElements) + { + var securityScheme = securitySchemeRegistry.FindOrAddReference(securityElement); - openApiSecurityRequirement.Add(securityScheme, securitySchemeRegistry.Scopes); + openApiSecurityRequirement.Add(securityScheme, securitySchemeRegistry.Scopes); + } + + openApiDocument.SecurityRequirements.Add(openApiSecurityRequirement); + } + catch(Exception ex) + { + generationErrors.Add( + new GenerationError + { + Message = ex.Message, + ExceptionType = ex.GetType().Name + }); } - openApiDocument.SecurityRequirements.Add(openApiSecurityRequirement); + return generationErrors; } } } \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentFilters/UrlToServerFilter.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentFilters/UrlToServerFilter.cs index b513cba..bb83cfb 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentFilters/UrlToServerFilter.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/DocumentFilters/UrlToServerFilter.cs @@ -9,6 +9,7 @@ using System.Text.RegularExpressions; using System.Xml.Linq; using System.Xml.XPath; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; using Microsoft.OpenApi.Models; namespace Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.DocumentFilters @@ -26,35 +27,52 @@ public class UrlToServerFilter : IDocumentFilter /// The documents representing the annotation xmls. /// Settings for document filters. /// - public void Apply( + /// The list of generation errors, if any produced when processing the filter. + public IList Apply( OpenApiDocument specificationDocument, IList xmlDocuments, DocumentFilterSettings settings, OpenApiDocumentGenerationSettings openApiDocumentGenerationSettings) { - var basePaths = new List(); - var urlElements = new List(); + var generationErrors = new List(); - foreach (var xmlDocument in xmlDocuments) + try { - urlElements.AddRange(xmlDocument.XPathSelectElements("//doc/members/member/url")); - } + var basePaths = new List(); + var urlElements = new List(); - foreach (var urlElement in urlElements) - { - var url = urlElement.Value; - var sanitizedUrl = SanitizeUrl(url); + foreach (var xmlDocument in xmlDocuments) + { + urlElements.AddRange(xmlDocument.XPathSelectElements("//doc/members/member/url")); + } - if (sanitizedUrl != null) + foreach (var urlElement in urlElements) { - basePaths.Add(sanitizedUrl.GetLeftPart(UriPartial.Authority)); + var url = urlElement.Value; + var sanitizedUrl = SanitizeUrl(url); + + if (sanitizedUrl != null) + { + basePaths.Add(sanitizedUrl.GetLeftPart(UriPartial.Authority)); + } } - } - foreach (var basePath in basePaths.Distinct()) + foreach (var basePath in basePaths.Distinct()) + { + specificationDocument.Servers.Add(new OpenApiServer { Url = basePath }); + } + } + catch(Exception ex) { - specificationDocument.Servers.Add(new OpenApiServer { Url = basePath}); + generationErrors.Add( + new GenerationError + { + Message = ex.Message, + ExceptionType = ex.GetType().Name + }); } + + return generationErrors; } private static Uri SanitizeUrl(string url) diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Extensions/IListExtensions.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Extensions/IListExtensions.cs new file mode 100644 index 0000000..6cc0d8c --- /dev/null +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Extensions/IListExtensions.cs @@ -0,0 +1,26 @@ +// ------------------------------------------------------------ +// 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; +using System.Collections.Generic; + +namespace Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Extensions +{ + /// + /// Extensions for . + /// + internal static class IListExtensions + { + /// + /// Converts list of cref values to a unique key. + /// + /// The list of cref values. + /// The unique key. + public static string ToCrefKey( this IList value ) + { + return string.Join( "_", value ); + } + } +} \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Extensions/OpenApiSchemaExtensions.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Extensions/OpenApiSchemaExtensions.cs new file mode 100644 index 0000000..37f6d87 --- /dev/null +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Extensions/OpenApiSchemaExtensions.cs @@ -0,0 +1,63 @@ +// ------------------------------------------------------------ +// 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.Models; + +namespace Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Extensions +{ + /// + /// Class containing extensions for . + /// + public static class OpenApiSchemaExtensions + { + /// + /// Copies source to target . + /// + /// The source schema to copy. + /// The target schema to copy into. + public static void CopyInto(this OpenApiSchema sourceOpenApiSchema, OpenApiSchema targetOpenApiSchema) + { + if(targetOpenApiSchema == null) + { + throw new ArgumentNullException(nameof(targetOpenApiSchema)); + } + + if (sourceOpenApiSchema == null) + { + throw new ArgumentNullException(nameof(sourceOpenApiSchema)); + } + + targetOpenApiSchema.Format = sourceOpenApiSchema.Format; + targetOpenApiSchema.Type = sourceOpenApiSchema.Type; + targetOpenApiSchema.Maximum = sourceOpenApiSchema.Maximum; + targetOpenApiSchema.Minimum = sourceOpenApiSchema.Minimum; + targetOpenApiSchema.MaxItems = sourceOpenApiSchema.MaxItems; + targetOpenApiSchema.MaxLength = sourceOpenApiSchema.MaxLength; + targetOpenApiSchema.Properties = sourceOpenApiSchema.Properties; + targetOpenApiSchema.MaxProperties = sourceOpenApiSchema.MaxProperties; + targetOpenApiSchema.Enum = sourceOpenApiSchema.Enum; + targetOpenApiSchema.Discriminator = sourceOpenApiSchema.Discriminator; + targetOpenApiSchema.AdditionalProperties = sourceOpenApiSchema.AdditionalProperties; + targetOpenApiSchema.AdditionalPropertiesAllowed = sourceOpenApiSchema.AdditionalPropertiesAllowed; + targetOpenApiSchema.Nullable = sourceOpenApiSchema.Nullable; + targetOpenApiSchema.Items = sourceOpenApiSchema.Items; + targetOpenApiSchema.Example = sourceOpenApiSchema.Example; + targetOpenApiSchema.AnyOf = sourceOpenApiSchema.AnyOf; + targetOpenApiSchema.Reference = sourceOpenApiSchema.Reference; + targetOpenApiSchema.OneOf = sourceOpenApiSchema.OneOf; + targetOpenApiSchema.AllOf = sourceOpenApiSchema.AllOf; + targetOpenApiSchema.Description = sourceOpenApiSchema.Description; + targetOpenApiSchema.Deprecated = sourceOpenApiSchema.Deprecated; + targetOpenApiSchema.Default = sourceOpenApiSchema.Default; + targetOpenApiSchema.ExclusiveMaximum = sourceOpenApiSchema.ExclusiveMaximum; + targetOpenApiSchema.ExclusiveMinimum = sourceOpenApiSchema.ExclusiveMinimum; + targetOpenApiSchema.ExternalDocs = sourceOpenApiSchema.ExternalDocs; + targetOpenApiSchema.Reference = sourceOpenApiSchema.Reference; + targetOpenApiSchema.Required = sourceOpenApiSchema.Required; + targetOpenApiSchema.ReadOnly = sourceOpenApiSchema.ReadOnly; + } + } +} diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Extensions/TypeExtensions.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Extensions/TypeExtensions.cs index 0b82d94..42173e0 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Extensions/TypeExtensions.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Extensions/TypeExtensions.cs @@ -23,6 +23,7 @@ public static class TypeExtensions [typeof(byte)] = () => new OpenApiSchema {Type = "string", Format = "byte"}, [typeof(int)] = () => new OpenApiSchema {Type = "integer", Format = "int32"}, [typeof(uint)] = () => new OpenApiSchema {Type = "integer", Format = "int32"}, + [typeof(ushort)] = () => new OpenApiSchema { Type = "integer", Format = "int32" }, [typeof(long)] = () => new OpenApiSchema {Type = "integer", Format = "int64"}, [typeof(ulong)] = () => new OpenApiSchema {Type = "integer", Format = "int64"}, [typeof(float)] = () => new OpenApiSchema {Type = "number", Format = "float"}, @@ -37,6 +38,7 @@ public static class TypeExtensions [typeof(byte?)] = () => new OpenApiSchema {Type = "string", Format = "byte", Nullable = true}, [typeof(int?)] = () => new OpenApiSchema {Type = "integer", Format = "int32", Nullable = true}, [typeof(uint?)] = () => new OpenApiSchema {Type = "integer", Format = "int32", Nullable = true}, + [typeof(ushort?)] = () => new OpenApiSchema { Type = "integer", Format = "int32", Nullable = true }, [typeof(long?)] = () => new OpenApiSchema {Type = "integer", Format = "int64", Nullable = true}, [typeof(ulong?)] = () => new OpenApiSchema {Type = "integer", Format = "int64", Nullable = true}, [typeof(float?)] = () => new OpenApiSchema {Type = "number", Format = "float", Nullable = true}, diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Extensions/XElementExtensions.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Extensions/XElementExtensions.cs index 0db546d..456d366 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Extensions/XElementExtensions.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Extensions/XElementExtensions.cs @@ -4,14 +4,13 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Reflection; using System.Text; using System.Xml; using System.Xml.Linq; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Exceptions; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models.KnownStrings; -using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.ReferenceRegistries; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Readers; @@ -388,7 +387,10 @@ private static OpenApiOAuthFlow ToOAuthFlow(this XElement element, string flowTy return oAuthFlow; } - private static OpenApiExample ToOpenApiExample(this XElement element, TypeFetcher typeFetcher) + private static OpenApiExample ToOpenApiExample( + this XElement element, + Dictionary crefFieldValueMap, + List generationErrors) { var exampleChildElements = element.Elements(); @@ -411,7 +413,14 @@ private static OpenApiExample ToOpenApiExample(this XElement element, TypeFetche if (valueElement != null && urlElement != null) { - throw new InvalidExampleException(SpecificationGenerationMessages.ProvideEitherValueOrUrlTag); + generationErrors.Add( + new GenerationError + { + ExceptionType = nameof(InvalidExampleException), + Message = SpecificationGenerationMessages.ProvideEitherValueOrUrlTag + }); + + return null; } IOpenApiAny exampleValue = null; @@ -425,44 +434,42 @@ private static OpenApiExample ToOpenApiExample(this XElement element, TypeFetche if (string.IsNullOrWhiteSpace(valueElement.Value) && string.IsNullOrWhiteSpace(crefValue)) { - throw new InvalidExampleException(SpecificationGenerationMessages.ProvideValueForExample); + generationErrors.Add( + new GenerationError + { + ExceptionType = nameof(InvalidExampleException), + Message = SpecificationGenerationMessages.ProvideValueForExample + }); + + return null; } - if (!string.IsNullOrWhiteSpace(crefValue)) + if (!string.IsNullOrWhiteSpace(valueElement.Value)) { - var typeName = crefValue.ExtractTypeNameFromFieldCref(); - var type = typeFetcher.LoadTypeFromCrefValues(new List {typeName}); - var fieldName = crefValue.ExtractFieldNameFromCref(); + exampleValue = new OpenApiStringReader() + .ReadFragment( + valueElement.Value, + OpenApiSpecVersion.OpenApi3_0, + out OpenApiDiagnostic _); + } - var fields = type.GetFields(BindingFlags.Public - | BindingFlags.Static); - var field = fields.FirstOrDefault(f => f.Name == fieldName); + if (!string.IsNullOrWhiteSpace(crefValue) && crefFieldValueMap.ContainsKey(crefValue)) + { + var fieldValueInfo = crefFieldValueMap[crefValue]; - if (field == null) + if (fieldValueInfo.Error != null) { - var errorMessage = string.Format( - SpecificationGenerationMessages.FieldNotFound, - fieldName, - typeName); + generationErrors.Add(fieldValueInfo.Error); - throw new TypeLoadException(errorMessage); + return null; } exampleValue = new OpenApiStringReader().ReadFragment( - field.GetValue(null).ToString(), + fieldValueInfo.Value, OpenApiSpecVersion.OpenApi3_0, out OpenApiDiagnostic _); } - if (!string.IsNullOrWhiteSpace(valueElement.Value)) - { - exampleValue = new OpenApiStringReader() - .ReadFragment( - valueElement.Value, - OpenApiSpecVersion.OpenApi3_0, - out OpenApiDiagnostic _); - } - openApiExample.Value = exampleValue; } @@ -479,11 +486,13 @@ private static OpenApiExample ToOpenApiExample(this XElement element, TypeFetche /// and generates a map of string to OpenApiExample. /// /// The XElement to process. - /// The type fetcher. + /// The cref to field value map. + /// The generation errors produced while processing header. /// The map of string to OpenApiExample. internal static Dictionary ToOpenApiExamples( this XElement xElement, - TypeFetcher typeFetcher) + Dictionary crefFieldValueMap, + List generationErrors) { var exampleElements = xElement.Elements().Where(p => p.Name == KnownXmlStrings.Example); var examples = new Dictionary(); @@ -492,7 +501,7 @@ internal static Dictionary ToOpenApiExamples( foreach (var exampleElement in exampleElements) { var exampleName = exampleElement.Attribute(KnownXmlStrings.Name)?.Value.Trim(); - var example = exampleElement.ToOpenApiExample(typeFetcher); + var example = exampleElement.ToOpenApiExample(crefFieldValueMap, generationErrors); if (example != null) { @@ -510,13 +519,13 @@ internal static Dictionary ToOpenApiExamples( /// and generates a map of string to OpenApiHeader. /// /// The XElement to process. - /// The type fetcher. - /// The schema reference registry. + /// The cref to schema map. + /// The generation errors produced while processing header. /// The map of string to OpenApiHeader. internal static Dictionary ToOpenApiHeaders( this XElement xElement, - TypeFetcher typeFetcher, - SchemaReferenceRegistry schemaReferenceRegistry) + Dictionary crefSchemaMap, + IList generationErrors) { var headerElements = xElement.Elements() .Where( @@ -530,8 +539,13 @@ internal static Dictionary ToOpenApiHeaders( var name = headerElement.Attribute(KnownXmlStrings.Name)?.Value.Trim(); if (string.IsNullOrWhiteSpace(name)) { - throw new InvalidHeaderException( - string.Format(SpecificationGenerationMessages.UndocumentedName, "header")); + generationErrors.Add(new GenerationError + { + ExceptionType = nameof(InvalidHeaderException), + Message = string.Format(SpecificationGenerationMessages.UndocumentedName, "header") + }); + + return null; } var description = headerElement @@ -539,9 +553,27 @@ internal static Dictionary ToOpenApiHeaders( .FirstOrDefault(p => p.Name == KnownXmlStrings.Description)?.Value.Trim().RemoveBlankLines(); var listedTypes = headerElement.GetListedTypes(); - var type = typeFetcher.LoadTypeFromCrefValues(listedTypes); + var crefKey = listedTypes.ToCrefKey(); + + var schema = new OpenApiSchema + { + Type = "string" + }; + + if (crefSchemaMap.ContainsKey(crefKey)) + { + var schemaInfo = crefSchemaMap[crefKey]; + + if (schemaInfo.Error != null) + { + generationErrors.Add(schemaInfo.Error); + + return null; + } + + schema = schemaInfo.Schema; + } - var schema = schemaReferenceRegistry.FindOrAddReference(type); openApiHeaders.Add( name, new OpenApiHeader diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/FilterSet.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/FilterSet.cs index d695c11..968e15f 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/FilterSet.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/FilterSet.cs @@ -95,7 +95,6 @@ public static FilterSet GetDefaultFilterSet(FilterSetVersion version) //Document filters _defaultFilterSet.Add(new AssemblyNameToInfoFilter()); _defaultFilterSet.Add(new UrlToServerFilter()); - _defaultFilterSet.Add(new MemberSummaryToSchemaDescriptionFilter()); _defaultFilterSet.Add(new SecurityToSecurityRequirementDocumentFilter()); //Operation config filters diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/InternalOpenApiGenerator.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/InternalOpenApiGenerator.cs index 508081d..2e78e8d 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/InternalOpenApiGenerator.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/InternalOpenApiGenerator.cs @@ -3,20 +3,25 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Xml.Linq; using System.Xml.XPath; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.AssemblyLoader; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.DocumentConfigFilters; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.DocumentFilters; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Exceptions; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Extensions; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models.KnownStrings; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.OperationConfigFilters; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.OperationFilters; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.PostProcessingDocumentFilters; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.PreprocessingOperationFilters; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.ReferenceRegistries; using Microsoft.OpenApi.Models; +using Microsoft.OpenApi.Readers; +using Newtonsoft.Json; namespace Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration { @@ -32,6 +37,7 @@ internal class InternalOpenApiGenerator private readonly IList _operationFilters; private readonly IList _postProcessingDocumentFilters; private readonly IList _preProcessingOperationFilters; + private readonly OpenApiStringReader _openApiStringReader = new OpenApiStringReader(); /// /// Creates a new instance of . @@ -67,33 +73,22 @@ public InternalOpenApiGenerator( private void AddOperation( IDictionary specificationDocuments, IDictionary referenceRegistryManagerMap, - IList operationGenerationErrors, + List operationGenerationErrors, DocumentVariantInfo documentVariantInfo, XElement operationElement, XElement operationConfigElement, - TypeFetcher typeFetcher) + GenerationContext generationContext) { var paths = new OpenApiPaths(); foreach (var preprocessingOperationFilter in _preProcessingOperationFilters) { - try - { - preprocessingOperationFilter.Apply( + var generationErrors = preprocessingOperationFilter.Apply( paths, operationElement, new PreProcessingOperationFilterSettings()); - } - catch (Exception e) - { - operationGenerationErrors.Add( - new GenerationError - { - ExceptionType = e.GetType().Name, - Message = e.Message - } - ); - } + + operationGenerationErrors.AddRange(generationErrors); } if (!referenceRegistryManagerMap.ContainsKey(documentVariantInfo)) @@ -114,7 +109,7 @@ private void AddOperation( var operationFilterSettings = new OperationFilterSettings { - TypeFetcher = typeFetcher, + GenerationContext = generationContext, ReferenceRegistryManager = referenceRegistryManagerMap[documentVariantInfo], Path = path, OperationMethod = operationMethod.ToString(), @@ -127,23 +122,12 @@ private void AddOperation( // since the config filters may rely on information generated from operation filters. foreach (var operationFilter in _operationFilters) { - try - { - operationFilter.Apply( + var generationErrors = operationFilter.Apply( operation, operationElement, operationFilterSettings); - } - catch (Exception e) - { - operationGenerationErrors.Add( - new GenerationError - { - ExceptionType = e.GetType().Name, - Message = e.Message - } - ); - } + + operationGenerationErrors.AddRange(generationErrors); } if (operationConfigElement != null) @@ -152,9 +136,7 @@ private void AddOperation( // that can be applied to the operations. foreach (var configFilter in _operationConfigFilters) { - try - { - configFilter.Apply( + var generationErrors = configFilter.Apply( operation, operationConfigElement, new OperationConfigFilterSettings @@ -162,17 +144,8 @@ private void AddOperation( OperationFilterSettings = operationFilterSettings, OperationFilters = _operationFilters }); - } - catch (Exception e) - { - operationGenerationErrors.Add( - new GenerationError - { - ExceptionType = e.GetType().Name, - Message = e.Message - } - ); - } + + operationGenerationErrors.AddRange(generationErrors); } } @@ -246,11 +219,17 @@ IDictionary openApiDocuments = new Dictionary(); var operationElements = new List(); + var propertyElements = new List(); foreach (var annotationXmlDocument in annotationXmlDocuments) { operationElements.AddRange( annotationXmlDocument.XPathSelectElements("//doc/members/member[url and verb]")); + + propertyElements.AddRange(annotationXmlDocument.XPathSelectElements("//doc/members/member") + .Where( + m => m.Attribute(KnownXmlStrings.Name) != null && + m.Attribute(KnownXmlStrings.Name).Value.StartsWith("P:"))); } XElement operationConfigElement = null; @@ -292,6 +271,15 @@ IDictionary openApiDocuments try { + var propertyNameResolverTypeName = _openApiDocumentGenerationSettings.SchemaGenerationSettings + .PropertyNameResolver.GetType().FullName; + + var internalGenerationContext = new InternalGenerationContext(); + var internalSchemaGenerationSettings = new InternalSchemaGenerationSettings() + { + PropertyNameResolverName = propertyNameResolverTypeName + }; + generationDiagnostic = new GenerationDiagnostic(); var documentGenerationDiagnostic = new DocumentGenerationDiagnostic(); @@ -305,10 +293,42 @@ IDictionary openApiDocuments }); } - var typeFetcher = new TypeFetcher(contractAssemblyPaths); +#if !NETFRAMEWORK + var assemblyLoader = new AssemblyLoader.AssemblyLoader(); + assemblyLoader.RegisterAssemblyPaths(contractAssemblyPaths); + var internalGenerationContextAsString = new AssemblyLoader.AssemblyLoader().BuildInternalGenerationContext( + contractAssemblyPaths, + operationElements.Select(i => i.ToString()).ToList(), + propertyElements.Select(i => i.ToString()).ToList(), + documentVariantElementNames.FirstOrDefault(), + internalSchemaGenerationSettings); + + internalGenerationContext = + (InternalGenerationContext)JsonConvert.DeserializeObject( + internalGenerationContextAsString, + typeof(InternalGenerationContext)); +#else + using (var isolatedDomain = new AppDomainCreator()) + { + isolatedDomain.Object.RegisterAssemblyPaths(contractAssemblyPaths); + var internalGenerationContextAsString = isolatedDomain.Object.BuildInternalGenerationContext( + contractAssemblyPaths, + operationElements.Select(i => i.ToString()).ToList(), + propertyElements.Select(i => i.ToString()).ToList(), + documentVariantElementNames.FirstOrDefault(), + internalSchemaGenerationSettings); + + internalGenerationContext = + (InternalGenerationContext)JsonConvert.DeserializeObject( + internalGenerationContextAsString, + typeof(InternalGenerationContext)); + } +#endif + + GenerationContext generationContext = internalGenerationContext.ToGenerationContext(); var operationGenerationDiagnostics = GenerateSpecificationDocuments( - typeFetcher, + generationContext, operationElements, operationConfigElement, documentVariantElementNames.FirstOrDefault(), @@ -328,39 +348,36 @@ IDictionary openApiDocuments foreach (var documentFilter in _documentFilters) { - try - { - documentFilter.Apply( + var generationErrors = documentFilter.Apply( openApiDocument, annotationXmlDocuments, new DocumentFilterSettings { - TypeFetcher = typeFetcher, OpenApiDocumentVersion = openApiDocumentVersion, OpenApiInfoDescription = openApiInfoDescription, ReferenceRegistryManager = referenceRegistryManager }, _openApiDocumentGenerationSettings); - } - catch (Exception e) + + foreach(var error in generationErrors) { - documentGenerationDiagnostic.Errors.Add( - new GenerationError - { - ExceptionType = e.GetType().Name, - Message = e.Message - }); + documentGenerationDiagnostic.Errors.Add(error); } } foreach (var filter in _postProcessingDocumentFilters) { - filter.Apply( + var generationErrors = filter.Apply( openApiDocument, new PostProcessingDocumentFilterSettings { OperationGenerationDiagnostics = operationGenerationDiagnostics }); + + foreach (var error in generationErrors) + { + documentGenerationDiagnostic.Errors.Add(error); + } } referenceRegistryManager.SecuritySchemeReferenceRegistry.References.CopyInto( @@ -371,22 +388,15 @@ IDictionary openApiDocuments { foreach (var documentConfigFilter in _documentConfigFilters) { - try - { - documentConfigFilter.Apply( + var generationErrors = documentConfigFilter.Apply( documents, documentConfigElement, annotationXmlDocuments, new DocumentConfigFilterSettings()); - } - catch (Exception e) + + foreach (var error in generationErrors) { - documentGenerationDiagnostic.Errors.Add( - new GenerationError - { - ExceptionType = e.GetType().Name, - Message = e.Message - }); + documentGenerationDiagnostic.Errors.Add(error); } } } @@ -439,7 +449,7 @@ IDictionary openApiDocuments /// /// The operation generation results from populating the specification documents. private IList GenerateSpecificationDocuments( - TypeFetcher typeFetcher, + GenerationContext generationContext, IList operationElements, XElement operationConfigElement, string documentVariantElementName, @@ -515,7 +525,7 @@ private IList GenerateSpecificationDocuments( DocumentVariantInfo.Default, operationElement, operationConfigElement, - typeFetcher); + generationContext); } catch (Exception e) { @@ -545,7 +555,7 @@ private IList GenerateSpecificationDocuments( documentVariantInfo, operationElement, operationConfigElement, - typeFetcher); + generationContext); } catch (Exception e) { @@ -575,12 +585,20 @@ private IList GenerateSpecificationDocuments( operationGenerationResults.Add(operationGenerationResult); } - foreach (var documentVariantInfo in specificationDocuments.Keys) + foreach (var documentVariantInfo in generationContext.VariantSchemaReferenceMap.Keys) { - referenceRegistryManagerMap[documentVariantInfo] - .SchemaReferenceRegistry.References.CopyInto( - specificationDocuments[documentVariantInfo].Components.Schemas); + var references = generationContext.VariantSchemaReferenceMap[documentVariantInfo].ToDictionary( + k => k.Key, + k => k.Value); + if (specificationDocuments.ContainsKey(documentVariantInfo)) + { + references.CopyInto(specificationDocuments[documentVariantInfo].Components.Schemas); + } + } + + foreach (var documentVariantInfo in specificationDocuments.Keys) + { referenceRegistryManagerMap[documentVariantInfo] .SecuritySchemeReferenceRegistry.References.CopyInto( specificationDocuments[documentVariantInfo].Components.SecuritySchemes); diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/InternalSchemaGenerationSettings.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/InternalSchemaGenerationSettings.cs new file mode 100644 index 0000000..90b5a89 --- /dev/null +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/InternalSchemaGenerationSettings.cs @@ -0,0 +1,19 @@ +// ------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License (MIT). See License.txt in the repo root for license information. +// ------------------------------------------------------------ + +using System; + +namespace Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration +{ +#if NETFRAMEWORK + internal class InternalSchemaGenerationSettings : MarshalByRefObject + { +#else + internal class InternalSchemaGenerationSettings + { +#endif + public string PropertyNameResolverName { get; set; } + } +} \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.csproj b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.csproj index 4288161..e7c77da 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.csproj +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.csproj @@ -10,7 +10,7 @@ Microsoft Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration - 1.0.0-beta049 + 2.0.0-beta01 Library that translates Visual Studio C# Annotations into .NET objects representing OpenAPI specification. © Microsoft Corporation. All rights reserved. Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration @@ -28,5 +28,12 @@ + + + + + + 4.3.0 + diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Models/DocumentVariantInfo.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Models/DocumentVariantInfo.cs index 2b153a7..79d0b89 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Models/DocumentVariantInfo.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Models/DocumentVariantInfo.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Extensions; +using Newtonsoft.Json; namespace Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models { @@ -41,11 +42,13 @@ public DocumentVariantInfo(DocumentVariantInfo other) /// /// Gets or sets the other attributes related to this document variant. /// + [JsonProperty] public IDictionary Attributes { get; set; } = new Dictionary(); /// /// Gets or sets the categorizer used to fork the document. /// + [JsonProperty] public string Categorizer { get; set; } /// @@ -57,6 +60,7 @@ public DocumentVariantInfo(DocumentVariantInfo other) /// /// Gets or sets the title of this document variant. /// + [JsonProperty] public string Title { get; set; } /// @@ -90,5 +94,13 @@ public bool Equals(DocumentVariantInfo specificationDocumentVariantInfo) /// Gets the hash code. /// public override int GetHashCode() => new {Title}.GetHashCode(); + + /// + /// Gets the string representation. + /// + public override string ToString() + { + return JsonConvert.SerializeObject(this); + } } } \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Models/FieldValueInfo.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Models/FieldValueInfo.cs new file mode 100644 index 0000000..58169eb --- /dev/null +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Models/FieldValueInfo.cs @@ -0,0 +1,23 @@ +// ------------------------------------------------------------ +// 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.CSharpAnnotations.DocumentGeneration.Models +{ + /// + /// Stores field values. + /// + public class FieldValueInfo + { + /// + /// Gets or sets the field value. + /// + public string Value { get; set; } + + /// + /// Gets or sets the error encountered while fetching field value. + /// + public GenerationError Error { get; set; } + } +} \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Models/GenerationContext.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Models/GenerationContext.cs new file mode 100644 index 0000000..3149e39 --- /dev/null +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Models/GenerationContext.cs @@ -0,0 +1,34 @@ +// ------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License (MIT). See License.txt in the repo root for license information. +// ------------------------------------------------------------ + +using System.Collections.Generic; +using Microsoft.OpenApi.Models; + +namespace Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models +{ + /// + /// Holds various required map b/w cref and schema to perform Open API spec generation. + /// + public class GenerationContext + { + /// + /// Cref key to map. + /// + public Dictionary CrefToSchemaMap { get; set; } = + new Dictionary(); + + /// + /// Cref key to map. + /// + public Dictionary CrefToFieldValueMap { get; set; } + = new Dictionary(); + + /// + /// Document Variant to Schema reference map (Schema key --> OpenApiSchema). + /// + public Dictionary> VariantSchemaReferenceMap { get; set; } = + new Dictionary>(); + } +} diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Models/InternalGenerationContext.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Models/InternalGenerationContext.cs new file mode 100644 index 0000000..80314fa --- /dev/null +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Models/InternalGenerationContext.cs @@ -0,0 +1,84 @@ +// ------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License (MIT). See License.txt in the repo root for license information. +// ------------------------------------------------------------ + +using System.Collections.Generic; +using System.Linq; +using Microsoft.OpenApi.Models; +using Microsoft.OpenApi.Readers; +using Newtonsoft.Json; + +namespace Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models +{ + /// + /// Holds various required map b/w cref and schema to perform Open API spec generation. + /// This class will be used to transfer data across app domain. + /// + internal class InternalGenerationContext + { + OpenApiStringReader openApiStringReader = new OpenApiStringReader(); + + /// + /// Cref key to map. + /// + public Dictionary CrefToSchemaMap { get; set; } = + new Dictionary(); + + /// + /// Cref key to map. + /// + public Dictionary CrefToFieldValueMap { get; set; } + = new Dictionary(); + + + /// + /// Serialized to Schema reference map (Schema key --> Serialized OpenApiSchema). + /// + public Dictionary> VariantSchemaReferenceMap { get; set; } = + new Dictionary>(); + + /// + /// Converts to . + /// + /// + public GenerationContext ToGenerationContext() + { + var generationContext = new GenerationContext + { + CrefToFieldValueMap = this.CrefToFieldValueMap + }; + + foreach (var key in this.CrefToSchemaMap.Keys) + { + InternalSchemaGenerationInfo schemaInfo = this.CrefToSchemaMap[key]; + var internalSchemaInfo = new SchemaGenerationInfo + { + Schema = schemaInfo.Schema == null + ? null + : openApiStringReader.ReadFragment( + schemaInfo.Schema, + OpenApiSpecVersion.OpenApi3_0, + out OpenApiDiagnostic diagnostic), + Error = schemaInfo.Error + }; + + generationContext.CrefToSchemaMap.Add(key, internalSchemaInfo); + } + + foreach (var key in this.VariantSchemaReferenceMap.Keys) + { + var documentVariantInfo = JsonConvert.DeserializeObject(key); + Dictionary schemaCrefMap = this.VariantSchemaReferenceMap[key].ToDictionary( + k => k.Key, k => openApiStringReader.ReadFragment( + k.Value, + OpenApiSpecVersion.OpenApi3_0, + out OpenApiDiagnostic diagnostic)); + + generationContext.VariantSchemaReferenceMap.Add(documentVariantInfo, schemaCrefMap); + } + + return generationContext; + } + } +} \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Models/InternalSchemaGenerationInfo.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Models/InternalSchemaGenerationInfo.cs new file mode 100644 index 0000000..87f10ae --- /dev/null +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Models/InternalSchemaGenerationInfo.cs @@ -0,0 +1,25 @@ +// ------------------------------------------------------------ +// 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.CSharpAnnotations.DocumentGeneration.Models +{ + /// + ///The internal class to hold schema generation info and used to transport data across app domain. + /// + internal class InternalSchemaGenerationInfo + { + /// + /// Gets or sets the error encountered while generating schema. + /// + public GenerationError Error { get; set; } + + /// + /// Gets or sets the serialized + /// + public string Schema { get; set; } + } +} diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Models/SchemaGenerationInfo.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Models/SchemaGenerationInfo.cs new file mode 100644 index 0000000..63a8ed7 --- /dev/null +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/Models/SchemaGenerationInfo.cs @@ -0,0 +1,25 @@ +// ------------------------------------------------------------ +// 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.CSharpAnnotations.DocumentGeneration.Models +{ + /// + /// Gets or sets the generated schema info. + /// + public class SchemaGenerationInfo + { + /// + /// Gets or sets the schema. + /// + public OpenApiSchema Schema { get; set; } + + /// + /// Gets or sets the error encountered while generating schema. + /// + public GenerationError Error { get; set; } + } +} diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationConfigFilters/CommonAnnotationFilter.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationConfigFilters/CommonAnnotationFilter.cs index 9a5d054..71507e5 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationConfigFilters/CommonAnnotationFilter.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationConfigFilters/CommonAnnotationFilter.cs @@ -4,8 +4,10 @@ // ------------------------------------------------------------ using System; +using System.Collections.Generic; using System.Linq; using System.Xml.Linq; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models.KnownStrings; using Microsoft.OpenApi.Models; @@ -22,31 +24,51 @@ public class CommonAnnotationFilter : IOperationConfigFilter /// The operation to be updated. /// The xml element containing operation-level config in the config xml. /// The operation config filter settings. - public void Apply(OpenApiOperation operation, XElement element, OperationConfigFilterSettings settings) + /// The list of generation errors, if any produced when processing the filter. + public IList Apply( + OpenApiOperation operation, + XElement element, + OperationConfigFilterSettings settings) { - var annotationElements = element.Descendants().Where(i => i.Name == KnownXmlStrings.Annotation); + var generationErrors = new List(); - foreach (var annotationElement in annotationElements) + try { - var targetedTag = annotationElement.Attribute(KnownXmlStrings.Tag); + var annotationElements = element.Descendants().Where(i => i.Name == KnownXmlStrings.Annotation); - // Only proceed if the target tag is null (indicating that the annotation applies to all operations) - // or if the target tag matches with tags in this operation. - if (targetedTag != null && - !operation.Tags.Select(t => t.Name) - .Contains(targetedTag.Value.Trim(), StringComparer.InvariantCultureIgnoreCase)) + foreach (var annotationElement in annotationElements) { - continue; - } + var targetedTag = annotationElement.Attribute(KnownXmlStrings.Tag); - foreach (var operationFilter in settings.OperationFilters) - { - operationFilter.Apply( - operation, - annotationElement, - settings.OperationFilterSettings); + // Only proceed if the target tag is null (indicating that the annotation applies to all operations) + // or if the target tag matches with tags in this operation. + if (targetedTag != null && + !operation.Tags.Select(t => t.Name) + .Contains(targetedTag.Value.Trim(), StringComparer.InvariantCultureIgnoreCase)) + { + continue; + } + + foreach (var operationFilter in settings.OperationFilters) + { + operationFilter.Apply( + operation, + annotationElement, + settings.OperationFilterSettings); + } } } + catch(Exception ex) + { + generationErrors.Add( + new GenerationError + { + Message = ex.Message, + ExceptionType = ex.GetType().Name + }); + } + + return generationErrors; } } } \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationConfigFilters/IOperationConfigFilter.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationConfigFilters/IOperationConfigFilter.cs index a21bfd4..a2ff5cb 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationConfigFilters/IOperationConfigFilter.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationConfigFilters/IOperationConfigFilter.cs @@ -3,7 +3,9 @@ // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ +using System.Collections.Generic; using System.Xml.Linq; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.OperationFilters; using Microsoft.OpenApi.Models; @@ -26,6 +28,10 @@ public interface IOperationConfigFilter : IFilter /// . /// /// - void Apply(OpenApiOperation operation, XElement element, OperationConfigFilterSettings settings); + /// The list of generation errors, if any produced when processing the filter. + IList Apply( + OpenApiOperation operation, + XElement element, + OperationConfigFilterSettings settings); } } \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/GroupToTagFilter.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/GroupToTagFilter.cs index c1ea55d..49846d4 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/GroupToTagFilter.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/GroupToTagFilter.cs @@ -3,8 +3,11 @@ // 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 System.Xml.Linq; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models.KnownStrings; using Microsoft.OpenApi.Models; @@ -27,26 +30,46 @@ public class GroupToTagFilter : IOperationFilter /// It also guarantees that common annotations in the config file do not overwrite the /// annotations in the main documentation. /// - public void Apply(OpenApiOperation operation, XElement element, OperationFilterSettings settings) + /// The list of generation errors, if any produced when processing the filter. + public IList Apply( + OpenApiOperation operation, + XElement element, + OperationFilterSettings settings) { - var groupElement = element.Descendants().FirstOrDefault(i => i.Name == KnownXmlStrings.Group); + var generationErrors = new List(); - var groupValue = groupElement?.Value.Trim(); - - if (string.IsNullOrWhiteSpace(groupValue)) + try { - return; - } + var groupElement = element.Descendants().FirstOrDefault(i => i.Name == KnownXmlStrings.Group); + + var groupValue = groupElement?.Value.Trim(); - if (!operation.Tags.Select(t => t.Name).Contains(groupValue)) + if (string.IsNullOrWhiteSpace(groupValue)) + { + return generationErrors; + } + + if (!operation.Tags.Select(t => t.Name).Contains(groupValue)) + { + operation.Tags.Add( + new OpenApiTag + { + Name = groupValue + } + ); + } + } + catch (Exception ex) { - operation.Tags.Add( - new OpenApiTag - { - Name = groupValue - } - ); + generationErrors.Add( + new GenerationError + { + Message = ex.Message, + ExceptionType = ex.GetType().Name + }); } + + return generationErrors; } } } \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/IOperationFilter.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/IOperationFilter.cs index da26b86..895b5fd 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/IOperationFilter.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/IOperationFilter.cs @@ -3,7 +3,9 @@ // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ +using System.Collections.Generic; using System.Xml.Linq; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; using Microsoft.OpenApi.Models; namespace Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.OperationFilters @@ -21,12 +23,16 @@ public interface IOperationFilter : IFilter /// The xml element representing an operation in the annotation xmls provided in /// . /// + /// The list of generation errors, if any produced when processing the filter. /// /// Care should be taken to not overwrite the existing value in Operation if already present. /// This guarantees the predictable behavior that the first tag in the XML will be respected. /// It also guarantees that common annotations in the config file do not overwrite the /// annotations in the main documentation. /// - void Apply(OpenApiOperation operation, XElement element, OperationFilterSettings settings); + IList Apply( + OpenApiOperation operation, + XElement element, + OperationFilterSettings settings); } } \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/OperationFilterSettings.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/OperationFilterSettings.cs index fe9acfb..06cb440 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/OperationFilterSettings.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/OperationFilterSettings.cs @@ -3,6 +3,7 @@ // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.ReferenceRegistries; namespace Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.OperationFilters @@ -12,6 +13,11 @@ namespace Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.OperationFilter /// public class OperationFilterSettings { + /// + /// Gets or sets the generation context. + /// + public GenerationContext GenerationContext { get; set; } + /// /// Gets or sets the operation method for the operation. /// @@ -32,10 +38,5 @@ public class OperationFilterSettings /// roslyn issue. https://github.com/dotnet/roslyn/issues/26292. /// public bool RemoveRoslynDuplicateStringFromParamName { get; set; } - - /// - /// Gets or sets the type fetcher. - /// - public TypeFetcher TypeFetcher { get; set; } } } \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/ParamToParameterFilter.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/ParamToParameterFilter.cs index 30d3676..fd6a032 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/ParamToParameterFilter.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/ParamToParameterFilter.cs @@ -4,12 +4,16 @@ // ------------------------------------------------------------ using System; +using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Extensions; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models.KnownStrings; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.ReferenceRegistries; +using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; +using Microsoft.OpenApi.Readers; namespace Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.OperationFilters { @@ -24,100 +28,141 @@ public class ParamToParameterFilter : IOperationFilter /// The operation to be updated. /// The xml element representing an operation in the annotation xml. /// The operation filter settings. + /// The list of generation errors(if any) produced when processing the filter. /// /// Care should be taken to not overwrite the existing value in Operation if already present. /// This guarantees the predictable behavior that the first tag in the XML will be respected. /// It also guarantees that common annotations in the config file do not overwrite the /// annotations in the main documentation. /// - public void Apply(OpenApiOperation operation, XElement element, OperationFilterSettings settings) + public IList Apply( + OpenApiOperation operation, + XElement element, + OperationFilterSettings settings) { - var paramElements = element.Elements() - .Where( - p => p.Name == KnownXmlStrings.Param) - .ToList(); - - // Query paramElements again to get all the parameter elements that have "in" attribute. - // This will include those whose "in" attribute were just populated in PopulateInAttributeFilter, but exclude - // those that have "in" attribute being "body" since they will be handled as a request body. - var paramElementsWithIn = paramElements.Where( - p => - KnownXmlStrings.InValuesTranslatableToParameter.Contains( - p.Attribute(KnownXmlStrings.In)?.Value)) - .ToList(); - - SchemaReferenceRegistry schemaReferenceRegistry - = settings.ReferenceRegistryManager.SchemaReferenceRegistry; - - foreach (var paramElement in paramElementsWithIn) - { - var inValue = paramElement.Attribute(KnownXmlStrings.In)?.Value.Trim(); - var name = paramElement.Attribute(KnownXmlStrings.Name)?.Value.Trim(); + var generationErrors = new List(); - if (settings.RemoveRoslynDuplicateStringFromParamName) + try + { + var paramElements = element.Elements() + .Where( + p => p.Name == KnownXmlStrings.Param) + .ToList(); + + // Query paramElements again to get all the parameter elements that have "in" attribute. + // This will include those whose "in" attribute were just populated in PopulateInAttributeFilter, but exclude + // those that have "in" attribute being "body" since they will be handled as a request body. + var paramElementsWithIn = paramElements.Where( + p => + KnownXmlStrings.InValuesTranslatableToParameter.Contains( + p.Attribute(KnownXmlStrings.In)?.Value)) + .ToList(); + + var generationContext = settings.GenerationContext; + + foreach (var paramElement in paramElementsWithIn) { - name = name.RemoveRoslynDuplicateString(); - } + var inValue = paramElement.Attribute(KnownXmlStrings.In)?.Value.Trim(); + var name = paramElement.Attribute(KnownXmlStrings.Name)?.Value.Trim(); - if (inValue == KnownXmlStrings.Path && - !settings.Path.Contains($"{{{name}}}", StringComparison.InvariantCultureIgnoreCase)) - { - continue; - } + if (settings.RemoveRoslynDuplicateStringFromParamName) + { + name = name.RemoveRoslynDuplicateString(); + } - var isRequired = paramElement.Attribute(KnownXmlStrings.Required)?.Value.Trim(); - var cref = paramElement.Attribute(KnownXmlStrings.Cref)?.Value.Trim(); + if (inValue == KnownXmlStrings.Path && + !settings.Path.Contains($"{{{name}}}", StringComparison.InvariantCultureIgnoreCase)) + { + continue; + } - var description = paramElement.GetDescriptionTextFromLastTextNode(); + var isRequired = paramElement.Attribute(KnownXmlStrings.Required)?.Value.Trim(); + var cref = paramElement.Attribute(KnownXmlStrings.Cref)?.Value.Trim(); - var type = typeof(string); - var allListedTypes = paramElement.GetListedTypes(); + var description = paramElement.GetDescriptionTextFromLastTextNode(); - if (allListedTypes.Any()) - { - type = settings.TypeFetcher.LoadTypeFromCrefValues(allListedTypes); - } + var allListedTypes = paramElement.GetListedTypes(); - var schema = schemaReferenceRegistry.FindOrAddReference(type); - var parameterLocation = GetParameterKind(inValue); + OpenApiSchema schema = new OpenApiSchema(); - var examples = paramElement.ToOpenApiExamples(settings.TypeFetcher); + if (!allListedTypes.Any()) + { + // Set default schema as string. + schema = new OpenApiSchema() + { + Type = "string" + }; + } - var openApiParameter = new OpenApiParameter - { - Name = name, - In = parameterLocation, - Description = description, - Required = parameterLocation == ParameterLocation.Path || Convert.ToBoolean(isRequired), - Schema = schema - }; - - if (examples.Count > 0) - { - var firstExample = examples.First().Value?.Value; + var crefKey = allListedTypes.ToCrefKey(); - if (firstExample != null) + if (generationContext.CrefToSchemaMap.ContainsKey(crefKey)) { - if (openApiParameter.Schema.Reference != null) + var schemaInfo = generationContext.CrefToSchemaMap[crefKey]; + + if (schemaInfo.Error != null) { - var key = schemaReferenceRegistry.GetKey(type); + generationErrors.Add(schemaInfo.Error); - if (schemaReferenceRegistry.References.ContainsKey(key)) - { - schemaReferenceRegistry.References[key].Example = firstExample; - } + return generationErrors; } - else + + schemaInfo.Schema.CopyInto(schema); + } + + var parameterLocation = GetParameterKind(inValue); + + var examples = paramElement.ToOpenApiExamples( + generationContext.CrefToFieldValueMap, + generationErrors); + + var schemaReferenceDefaultVariant = generationContext + .VariantSchemaReferenceMap[DocumentVariantInfo.Default]; + + if (examples.Any()) + { + var firstExample = examples.First().Value?.Value; + + if (firstExample != null) { - openApiParameter.Schema.Example = firstExample; + if (schema.Reference != null) + { + if (schemaReferenceDefaultVariant.ContainsKey(schema.Reference.Id)) + { + schemaReferenceDefaultVariant[schema.Reference.Id].Example = firstExample; + } + } + else + { + schema.Example = firstExample; + } } } - openApiParameter.Examples = examples; + var openApiParameter = new OpenApiParameter + { + Name = name, + In = parameterLocation, + Description = description, + Required = parameterLocation == ParameterLocation.Path || Convert.ToBoolean(isRequired), + Schema = schema, + Examples = examples.Any() ? examples : null + }; + + operation.Parameters.Add(openApiParameter); } - - operation.Parameters.Add(openApiParameter); } + catch(Exception ex) + { + generationErrors.Add( + new GenerationError + { + Message = ex.Message, + ExceptionType = ex.GetType().Name + }); + } + + return generationErrors; } private static ParameterLocation GetParameterKind(string parameterKind) diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/ParamToRequestBodyFilter.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/ParamToRequestBodyFilter.cs index 14bac4d..658ba04 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/ParamToRequestBodyFilter.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/ParamToRequestBodyFilter.cs @@ -3,14 +3,19 @@ // 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 System.Xml; using System.Xml.Linq; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Exceptions; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Extensions; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models.KnownStrings; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.ReferenceRegistries; +using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; +using Microsoft.OpenApi.Readers; namespace Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.OperationFilters { @@ -26,120 +31,156 @@ public class ParamToRequestBodyFilter : IOperationFilter /// The operation to be updated. /// The xml element representing an operation in the annotation xml. /// The operation filter settings. + /// The list of generation errors, if any produced when processing the filter. /// /// Care should be taken to not overwrite the existing value in Operation if already present. /// This guarantees the predictable behavior that the first tag in the XML will be respected. /// It also guarantees that common annotations in the config file do not overwrite the /// annotations in the main documentation. /// - public void Apply(OpenApiOperation operation, XElement element, OperationFilterSettings settings) + public IList Apply( + OpenApiOperation operation, + XElement element, + OperationFilterSettings settings) { - var bodyElements = element.Elements() - .Where( - p => p.Name == KnownXmlStrings.Param && - p.Attribute(KnownXmlStrings.In)?.Value == KnownXmlStrings.Body) - .ToList(); + var generationErrors = new List(); - SchemaReferenceRegistry schemaReferenceRegistry = settings.ReferenceRegistryManager.SchemaReferenceRegistry; - - foreach (var bodyElement in bodyElements) + try { - var name = bodyElement.Attribute(KnownXmlStrings.Name)?.Value.Trim(); - var mediaType = bodyElement.Attribute(KnownXmlStrings.Type)?.Value ?? "application/json"; - - var description = bodyElement.GetDescriptionTextFromLastTextNode(); + var bodyElements = element.Elements() + .Where( + p => p.Name == KnownXmlStrings.Param && + p.Attribute(KnownXmlStrings.In)?.Value == KnownXmlStrings.Body) + .ToList(); - var allListedTypes = bodyElement.GetListedTypes(); + var generationContext = settings.GenerationContext; - if (!allListedTypes.Any()) + foreach (var bodyElement in bodyElements) { - throw new InvalidRequestBodyException( - string.Format(SpecificationGenerationMessages.MissingSeeCrefTag, name)); - } + var name = bodyElement.Attribute(KnownXmlStrings.Name)?.Value.Trim(); + var mediaType = bodyElement.Attribute(KnownXmlStrings.Type)?.Value ?? "application/json"; - var type = settings.TypeFetcher.LoadTypeFromCrefValues(allListedTypes); - var schema = schemaReferenceRegistry.FindOrAddReference(type); + var description = bodyElement.GetDescriptionTextFromLastTextNode(); - var examples = bodyElement.ToOpenApiExamples(settings.TypeFetcher); + var allListedTypes = bodyElement.GetListedTypes(); - if (examples.Count > 0) - { - var firstExample = examples.First().Value?.Value; + if (!allListedTypes.Any()) + { + throw new InvalidRequestBodyException( + string.Format(SpecificationGenerationMessages.MissingSeeCrefTag, name)); + } + + var crefKey = allListedTypes.ToCrefKey(); - if (firstExample != null) + OpenApiSchema schema = new OpenApiSchema(); + if (generationContext.CrefToSchemaMap.ContainsKey(crefKey)) { - // In case a schema is a reference, find that schmea object in schema registry - // and update the example. - if (schema.Reference != null) - { - var key = schemaReferenceRegistry.GetKey(type); + var schemaInfo = generationContext.CrefToSchemaMap[crefKey]; - if (schemaReferenceRegistry.References.ContainsKey(key)) - { - settings.ReferenceRegistryManager.SchemaReferenceRegistry.References[key].Example - = firstExample; - } - } - else + if (schemaInfo.Error != null) { - schema.Example = firstExample; + generationErrors.Add(schemaInfo.Error); + + return generationErrors; } + + schemaInfo.Schema.CopyInto(schema); } - } - if (operation.RequestBody == null) - { - operation.RequestBody = new OpenApiRequestBody + var examples = bodyElement.ToOpenApiExamples( + generationContext.CrefToFieldValueMap, + generationErrors); + + var schemaReferenceDefaultVariant = generationContext + .VariantSchemaReferenceMap[DocumentVariantInfo.Default]; + + if (examples.Count > 0) { - Description = description.RemoveBlankLines(), - Content = + var firstExample = examples.First().Value?.Value; + + if (firstExample != null) { - [mediaType] = new OpenApiMediaType {Schema = schema} - }, - Required = true - }; - } - else - { - if (string.IsNullOrWhiteSpace(operation.RequestBody.Description)) - { - operation.RequestBody.Description = description.RemoveBlankLines(); + // In case a schema is a reference, find that schema object in schema registry + // and update the example. + if (schema.Reference != null) + { + if (schemaReferenceDefaultVariant.ContainsKey(schema.Reference.Id)) + { + schemaReferenceDefaultVariant[schema.Reference.Id].Example = firstExample; + } + } + else + { + schema.Example = firstExample; + } + } } - if (!operation.RequestBody.Content.ContainsKey(mediaType)) + if (operation.RequestBody == null) { - operation.RequestBody.Content[mediaType] = new OpenApiMediaType + operation.RequestBody = new OpenApiRequestBody { - Schema = schema + Description = description.RemoveBlankLines(), + Content = + { + [mediaType] = new OpenApiMediaType {Schema = schema} + }, + Required = true }; } else { - if (!operation.RequestBody.Content[mediaType].Schema.AnyOf.Any()) + if (string.IsNullOrWhiteSpace(operation.RequestBody.Description)) { - var existingSchema = operation.RequestBody.Content[mediaType].Schema; - var newSchema = new OpenApiSchema(); - newSchema.AnyOf.Add(existingSchema); + operation.RequestBody.Description = description.RemoveBlankLines(); + } - operation.RequestBody.Content[mediaType].Schema = newSchema; + if (!operation.RequestBody.Content.ContainsKey(mediaType)) + { + operation.RequestBody.Content[mediaType] = new OpenApiMediaType + { + Schema = schema + }; } + else + { + if (!operation.RequestBody.Content[mediaType].Schema.AnyOf.Any()) + { + var existingSchema = operation.RequestBody.Content[mediaType].Schema; + var newSchema = new OpenApiSchema(); + newSchema.AnyOf.Add(existingSchema); - operation.RequestBody.Content[mediaType].Schema.AnyOf.Add(schema); - } - } + operation.RequestBody.Content[mediaType].Schema = newSchema; + } - if (examples.Count > 0) - { - if (operation.RequestBody.Content[mediaType].Examples.Any()) - { - examples.CopyInto(operation.RequestBody.Content[mediaType].Examples); + operation.RequestBody.Content[mediaType].Schema.AnyOf.Add(schema); + } } - else + + if (examples.Count > 0) { - operation.RequestBody.Content[mediaType].Examples = examples; + if (operation.RequestBody.Content[mediaType].Examples.Any()) + { + examples.CopyInto(operation.RequestBody.Content[mediaType].Examples); + } + else + { + operation.RequestBody.Content[mediaType].Examples = examples; + } } } } + catch (Exception ex) + { + generationErrors.Add( + new GenerationError + { + Message = ex.Message, + ExceptionType = ex.GetType().Name + }); + } + + return generationErrors; } } } \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/RemarksToDescriptionFilter.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/RemarksToDescriptionFilter.cs index beaa10b..44fde7b 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/RemarksToDescriptionFilter.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/RemarksToDescriptionFilter.cs @@ -3,9 +3,12 @@ // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ +using System; +using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Extensions; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models.KnownStrings; using Microsoft.OpenApi.Models; @@ -22,26 +25,46 @@ public class RemarksToDescriptionFilter : IOperationFilter /// The operation to be updated. /// The xml element representing an operation in the annotation xml. /// The operation filter settings. + /// The list of generation errors, if any produced when processing the filter. /// /// Care should be taken to not overwrite the existing value in Operation if already present. /// This guarantees the predictable behavior that the first tag in the XML will be respected. /// It also guarantees that common annotations in the config file do not overwrite the /// annotations in the main documentation. /// - public void Apply(OpenApiOperation operation, XElement element, OperationFilterSettings settings) + public IList Apply( + OpenApiOperation operation, + XElement element, + OperationFilterSettings settings) { - string description = null; - var remarksElement = element.Descendants().FirstOrDefault(i => i.Name == KnownXmlStrings.Remarks); + var generationErrors = new List(); - if (remarksElement != null) + try { - description = remarksElement.GetDescriptionText(); - } + string description = null; + var remarksElement = element.Descendants().FirstOrDefault(i => i.Name == KnownXmlStrings.Remarks); + + if (remarksElement != null) + { + description = remarksElement.GetDescriptionText(); + } - if (string.IsNullOrWhiteSpace(operation.Description)) + if (string.IsNullOrWhiteSpace(operation.Description)) + { + operation.Description = description; + } + } + catch(Exception ex) { - operation.Description = description; + generationErrors.Add( + new GenerationError + { + Message = ex.Message, + ExceptionType = ex.GetType().Name + }); } + + return generationErrors; } } } \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/ResponseToResponseFilter.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/ResponseToResponseFilter.cs index 2b26245..be342c7 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/ResponseToResponseFilter.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/ResponseToResponseFilter.cs @@ -3,13 +3,18 @@ // 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 System.Xml; using System.Xml.Linq; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Extensions; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models.KnownStrings; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.ReferenceRegistries; +using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; +using Microsoft.OpenApi.Readers; namespace Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.OperationFilters { @@ -24,154 +29,184 @@ public class ResponseToResponseFilter : IOperationFilter /// The operation to be updated. /// The xml element representing an operation in the annotation xml. /// The operation filter settings. + /// The list of generation errors, if any produced when processing the filter. /// /// Care should be taken to not overwrite the existing value in Operation if already present. /// This guarantees the predictable behavior that the first tag in the XML will be respected. /// It also guarantees that common annotations in the config file do not overwrite the /// annotations in the main documentation. /// - public void Apply(OpenApiOperation operation, XElement element, OperationFilterSettings settings) + public IList Apply( + OpenApiOperation operation, + XElement element, + OperationFilterSettings settings) { - var responseElements = element.Elements() - .Where( - p => p.Name == KnownXmlStrings.Response || - p.Name == KnownXmlStrings.ResponseType); + var generationErrors = new List(); - SchemaReferenceRegistry schemaReferenceRegistry = settings.ReferenceRegistryManager.SchemaReferenceRegistry; - - foreach (var responseElement in responseElements) + try { - var code = responseElement.Attribute(KnownXmlStrings.Code)?.Value; + var responseElements = element.Elements() + .Where( + p => p.Name == KnownXmlStrings.Response || + p.Name == KnownXmlStrings.ResponseType); - if (string.IsNullOrWhiteSpace(code)) - { - // Most APIs only document responses for a successful operation, so if code is not specified, - // we will assume it is for a successful operation. This also allows us to comply with OpenAPI spec: - // The Responses Object MUST contain at least one response code, - // and it SHOULD be the response for a successful operation call. - code = "200"; - } + var generationContext = settings.GenerationContext; - var mediaType = responseElement.Attribute(KnownXmlStrings.Type)?.Value ?? "application/json"; + foreach (var responseElement in responseElements) + { + var code = responseElement.Attribute(KnownXmlStrings.Code)?.Value; - var description = responseElement.GetDescriptionTextFromLastTextNode(); + if (string.IsNullOrWhiteSpace(code)) + { + // Most APIs only document responses for a successful operation, so if code is not specified, + // we will assume it is for a successful operation. This also allows us to comply with OpenAPI spec: + // The Responses Object MUST contain at least one response code, + // and it SHOULD be the response for a successful operation call. + code = "200"; + } - var type = typeof(string); - var allListedTypes = responseElement.GetListedTypes(); + var mediaType = responseElement.Attribute(KnownXmlStrings.Type)?.Value ?? "application/json"; - var responseContractType = settings.TypeFetcher.LoadTypeFromCrefValues(allListedTypes); + var description = responseElement.GetDescriptionTextFromLastTextNode(); - OpenApiSchema schema = null; - if (responseContractType != null) - { - schema = schemaReferenceRegistry.FindOrAddReference(responseContractType); - } + var allListedTypes = responseElement.GetListedTypes(); - var examples = responseElement.ToOpenApiExamples(settings.TypeFetcher); - var headers = responseElement.ToOpenApiHeaders( - settings.TypeFetcher, - settings.ReferenceRegistryManager.SchemaReferenceRegistry); + var crefKey = allListedTypes.ToCrefKey(); - if (schema != null) - { - if (examples.Count > 0) + OpenApiSchema schema = null; + if (generationContext.CrefToSchemaMap.ContainsKey(crefKey)) { - var firstExample = examples.First().Value?.Value; + var schemaInfo = generationContext.CrefToSchemaMap[crefKey]; - if (firstExample != null) + if (schemaInfo.Error != null) { - if (schema.Reference != null) - { - var key = schemaReferenceRegistry.GetKey(responseContractType); + generationErrors.Add(schemaInfo.Error); - if (schemaReferenceRegistry.References.ContainsKey(key)) - { - settings.ReferenceRegistryManager.SchemaReferenceRegistry.References[key].Example - = firstExample; - } - } - else - { - schema.Example = firstExample; - } + return generationErrors; } - } - } - if (operation.Responses.ContainsKey(code)) - { - if (string.IsNullOrWhiteSpace(operation.Responses[code].Description)) - { - operation.Responses[code].Description = description.RemoveBlankLines(); + schema = new OpenApiSchema(); + schemaInfo.Schema.CopyInto(schema); } + var examples = responseElement.ToOpenApiExamples( + generationContext.CrefToFieldValueMap, + generationErrors); + + var headers = responseElement.ToOpenApiHeaders(generationContext.CrefToSchemaMap, generationErrors); + + var schemaReferenceDefaultVariant = generationContext + .VariantSchemaReferenceMap[DocumentVariantInfo.Default]; + if (schema != null) { - if (!operation.Responses[code].Content.ContainsKey(mediaType)) + if (examples.Count > 0) { - operation.Responses[code].Content[mediaType] = new OpenApiMediaType + var firstExample = examples.First().Value?.Value; + + if (firstExample != null) { - Schema = schema - }; + if (schema.Reference != null) + { + if (schemaReferenceDefaultVariant.ContainsKey(schema.Reference.Id)) + { + schemaReferenceDefaultVariant[schema.Reference.Id].Example = firstExample; + } + } + else + { + schema.Example = firstExample; + } + } } - else + } + + if (operation.Responses.ContainsKey(code)) + { + if (string.IsNullOrWhiteSpace(operation.Responses[code].Description)) { - // If the existing schema is just a single schema (not a list of AnyOf), then - // we create a new schema and add that schema to AnyOf to allow us to add - // more schemas to it later. - if (!operation.Responses[code].Content[mediaType].Schema.AnyOf.Any()) + operation.Responses[code].Description = description.RemoveBlankLines(); + } + + if (schema != null) + { + if (!operation.Responses[code].Content.ContainsKey(mediaType)) + { + operation.Responses[code].Content[mediaType] = new OpenApiMediaType + { + Schema = schema + }; + } + else { - var existingSchema = operation.Responses[code].Content[mediaType].Schema; - var newSchema = new OpenApiSchema(); + // If the existing schema is just a single schema (not a list of AnyOf), then + // we create a new schema and add that schema to AnyOf to allow us to add + // more schemas to it later. + if (!operation.Responses[code].Content[mediaType].Schema.AnyOf.Any()) + { + var existingSchema = operation.Responses[code].Content[mediaType].Schema; + var newSchema = new OpenApiSchema(); - newSchema.AnyOf.Add(existingSchema); + newSchema.AnyOf.Add(existingSchema); - operation.Responses[code].Content[mediaType].Schema = newSchema; - } + operation.Responses[code].Content[mediaType].Schema = newSchema; + } - operation.Responses[code].Content[mediaType].Schema.AnyOf.Add(schema); + operation.Responses[code].Content[mediaType].Schema.AnyOf.Add(schema); + } } } - } - else - { - var response = new OpenApiResponse + else { - Description = description.RemoveBlankLines(), - }; + var response = new OpenApiResponse + { + Description = description.RemoveBlankLines(), + }; - if (schema != null) - { - response.Content[mediaType] = new OpenApiMediaType { Schema = schema }; + if (schema != null) + { + response.Content[mediaType] = new OpenApiMediaType { Schema = schema }; + } + + if (headers != null && headers.Any()) + { + response.Headers = headers; + } + + operation.Responses.Add(code, response); } - if (headers.Any()) + if (examples.Count > 0) { - response.Headers = headers; + if (operation.Responses[code].Content[mediaType].Examples.Any()) + { + examples.CopyInto(operation.Responses[code].Content[mediaType].Examples); + } + else + { + operation.Responses[code].Content[mediaType].Examples = examples; + } } - - operation.Responses.Add(code, response); } - if (examples.Count > 0) + if (!operation.Responses.Any()) { - if (operation.Responses[code].Content[mediaType].Examples.Any()) - { - examples.CopyInto(operation.Responses[code].Content[mediaType].Examples); - } - else - { - operation.Responses[code].Content[mediaType].Examples = examples; - } + operation.Responses.Add( + "default", + new OpenApiResponse { Description = "Responses cannot be located for this operation." }); } } - - if (!operation.Responses.Any()) + catch(Exception ex) { - operation.Responses.Add( - "default", - new OpenApiResponse {Description = "Responses cannot be located for this operation."}); + generationErrors.Add( + new GenerationError + { + Message = ex.Message, + ExceptionType = ex.GetType().Name + }); } + + return generationErrors; } } } \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/SecurityToSecurityRequirementOperationFilter.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/SecurityToSecurityRequirementOperationFilter.cs index 4b5f2fb..6bd95a9 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/SecurityToSecurityRequirementOperationFilter.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/SecurityToSecurityRequirementOperationFilter.cs @@ -4,8 +4,10 @@ // ------------------------------------------------------------ using System; +using System.Collections.Generic; using System.Linq; using System.Xml.Linq; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models.KnownStrings; using Microsoft.OpenApi.Models; @@ -23,43 +25,63 @@ public class SecurityToSecurityRequirementOperationFilter : IOperationFilter /// The operation to be updated. /// The xml element representing an operation in the annotation xml. /// The operation filter settings. - public void Apply(OpenApiOperation operation, XElement element, OperationFilterSettings settings) + /// The list of generation errors, if any produced when processing the filter. + public IList Apply( + OpenApiOperation operation, + XElement element, + OperationFilterSettings settings) { - if (settings == null) - { - throw new ArgumentNullException(nameof(settings)); - } + var generationErrors = new List(); - if (element == null) + try { - throw new ArgumentNullException(nameof(element)); - } + if (settings == null) + { + throw new ArgumentNullException(nameof(settings)); + } - if (operation == null) - { - throw new ArgumentNullException(nameof(operation)); - } + if (element == null) + { + throw new ArgumentNullException(nameof(element)); + } - var securityElements = element.Elements() - .Where( - p => p.Name == KnownXmlStrings.Security); + if (operation == null) + { + throw new ArgumentNullException(nameof(operation)); + } - if (!securityElements.Any()) - { - return; - } + var securityElements = element.Elements() + .Where( + p => p.Name == KnownXmlStrings.Security); - var openApiSecurityRequirement = new OpenApiSecurityRequirement(); - var securitySchemeRegistry = settings.ReferenceRegistryManager.SecuritySchemeReferenceRegistry; + if (!securityElements.Any()) + { + return generationErrors; + } - foreach (var securityElement in securityElements) - { - var securityScheme = securitySchemeRegistry.FindOrAddReference(securityElement); + var openApiSecurityRequirement = new OpenApiSecurityRequirement(); + var securitySchemeRegistry = settings.ReferenceRegistryManager.SecuritySchemeReferenceRegistry; + + foreach (var securityElement in securityElements) + { + var securityScheme = securitySchemeRegistry.FindOrAddReference(securityElement); - openApiSecurityRequirement.Add(securityScheme, securitySchemeRegistry.Scopes); + openApiSecurityRequirement.Add(securityScheme, securitySchemeRegistry.Scopes); + } + + operation.Security.Add(openApiSecurityRequirement); + } + catch(Exception ex) + { + generationErrors.Add( + new GenerationError + { + Message = ex.Message, + ExceptionType = ex.GetType().Name + }); } - operation.Security.Add(openApiSecurityRequirement); + return generationErrors; } } } \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/SummaryToSummaryFilter.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/SummaryToSummaryFilter.cs index d98ef69..b3689e0 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/SummaryToSummaryFilter.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/SummaryToSummaryFilter.cs @@ -3,9 +3,12 @@ // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ +using System; +using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Extensions; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models.KnownStrings; using Microsoft.OpenApi.Models; @@ -22,25 +25,45 @@ public class SummaryToSummaryFilter : IOperationFilter /// The operation to be updated. /// The xml element representing an operation in the annotation xml. /// The operation filter settings. + /// The list of generation errors, if any produced when processing the filter. /// /// Care should be taken to not overwrite the existing value in Operation if already present. /// This guarantees the predictable behavior that the first tag in the XML will be respected. /// It also guarantees that common annotations in the config file do not overwrite the /// annotations in the main documentation. /// - public void Apply(OpenApiOperation operation, XElement element, OperationFilterSettings settings) + public IList Apply( + OpenApiOperation operation, + XElement element, + OperationFilterSettings settings) { - var summaryElement = element.Descendants().FirstOrDefault(i => i.Name == KnownXmlStrings.Summary); + var generationErrors = new List(); - if (summaryElement == null) + try { - return; - } + var summaryElement = element.Descendants().FirstOrDefault(i => i.Name == KnownXmlStrings.Summary); + + if (summaryElement == null) + { + return generationErrors; + } - if (string.IsNullOrWhiteSpace(operation.Summary)) + if (string.IsNullOrWhiteSpace(operation.Summary)) + { + operation.Summary = summaryElement.GetDescriptionText(); + } + } + catch(Exception ex) { - operation.Summary = summaryElement.GetDescriptionText(); + generationErrors.Add( + new GenerationError + { + Message = ex.Message, + ExceptionType = ex.GetType().Name + }); } + + return generationErrors; } } } \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/PostProcessingDocumentFilters/IPostProcessingDocumentFilter.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/PostProcessingDocumentFilters/IPostProcessingDocumentFilter.cs index 8754d89..8da1de5 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/PostProcessingDocumentFilters/IPostProcessingDocumentFilter.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/PostProcessingDocumentFilters/IPostProcessingDocumentFilter.cs @@ -3,7 +3,9 @@ // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ +using System.Collections.Generic; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.DocumentFilters; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.OperationFilters; using Microsoft.OpenApi.Models; @@ -20,6 +22,7 @@ public interface IPostProcessingDocumentFilter : IFilter /// /// The OpenAPI document to process. /// - void Apply(OpenApiDocument openApiDocument, PostProcessingDocumentFilterSettings settings); + /// The list of generation errors, if any produced when processing the filter. + IList Apply(OpenApiDocument openApiDocument, PostProcessingDocumentFilterSettings settings); } } \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/PostProcessingDocumentFilters/RemoveFailedGenerationOperationFilter.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/PostProcessingDocumentFilters/RemoveFailedGenerationOperationFilter.cs index b796fd2..508bc95 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/PostProcessingDocumentFilters/RemoveFailedGenerationOperationFilter.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/PostProcessingDocumentFilters/RemoveFailedGenerationOperationFilter.cs @@ -4,8 +4,10 @@ // ------------------------------------------------------------ using System; +using System.Collections.Generic; using System.Linq; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Exceptions; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; using Microsoft.OpenApi.Models; namespace Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.PostProcessingDocumentFilters @@ -20,41 +22,58 @@ public class RemoveFailedGenerationOperationFilter : IPostProcessingDocumentFilt /// /// The OpenAPI document to process. /// The filter settings. - public void Apply( + /// The list of generation errors, if any produced when processing the filter. + public IList Apply( OpenApiDocument openApiDocument, PostProcessingDocumentFilterSettings settings) { - if (openApiDocument == null || settings == null) - { - return; - } + var generationErrors = new List(); - // Remove all operations with generation errors except for with DuplicateOperationException as only the - // first occurrence of the duplicate paths added to the document and rest all are never added to the document. - foreach (var operationDiagnostic in - settings.OperationGenerationDiagnostics.Where( - operationDiagnostic => operationDiagnostic.Errors.Any() - && operationDiagnostic.Errors.Any(i => i.ExceptionType - != typeof(DuplicateOperationException).Name))) + try { - if (!Enum.TryParse(operationDiagnostic.OperationMethod, true, out OperationType operationMethod) || - !openApiDocument.Paths.ContainsKey(operationDiagnostic.Path)) + if (openApiDocument == null || settings == null) { - continue; + return generationErrors; } - var operations = openApiDocument.Paths[operationDiagnostic.Path].Operations; - - if (operations.Count == 1) - { - // If there is only one operation under the path and it failed generation, remove complete path. - openApiDocument.Paths.Remove(operationDiagnostic.Path); - } - else + // Remove all operations with generation errors except for with DuplicateOperationException as only the + // first occurrence of the duplicate paths added to the document and rest all are never added to the document. + foreach (var operationDiagnostic in + settings.OperationGenerationDiagnostics.Where( + operationDiagnostic => operationDiagnostic.Errors.Any() + && operationDiagnostic.Errors.Any(i => i.ExceptionType + != typeof(DuplicateOperationException).Name))) { - openApiDocument.Paths[operationDiagnostic.Path].Operations.Remove(operationMethod); + if (!Enum.TryParse(operationDiagnostic.OperationMethod, true, out OperationType operationMethod) || + !openApiDocument.Paths.ContainsKey(operationDiagnostic.Path)) + { + continue; + } + + var operations = openApiDocument.Paths[operationDiagnostic.Path].Operations; + + if (operations.Count == 1) + { + // If there is only one operation under the path and it failed generation, remove complete path. + openApiDocument.Paths.Remove(operationDiagnostic.Path); + } + else + { + openApiDocument.Paths[operationDiagnostic.Path].Operations.Remove(operationMethod); + } } } + catch(Exception ex) + { + generationErrors.Add( + new GenerationError + { + Message = ex.Message, + ExceptionType = ex.GetType().Name + }); + } + + return generationErrors; } } } \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/PreprocessingOperationFilters/BranchOptionalPathParametersFilter.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/PreprocessingOperationFilters/BranchOptionalPathParametersFilter.cs index df3278a..ad82087 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/PreprocessingOperationFilters/BranchOptionalPathParametersFilter.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/PreprocessingOperationFilters/BranchOptionalPathParametersFilter.cs @@ -9,6 +9,7 @@ using System.Text.RegularExpressions; using System.Xml.Linq; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Extensions; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models.KnownStrings; using Microsoft.OpenApi.Models; @@ -26,46 +27,66 @@ public class BranchOptionalPathParametersFilter : IPreProcessingOperationFilter /// The paths to be updated. /// The xml element representing an operation in the annotation xml. /// The operation filter settings. - public void Apply(OpenApiPaths paths, XElement element, PreProcessingOperationFilterSettings settings) + /// The list of generation errors, if any produced when processing the filter. + public IList Apply( + OpenApiPaths paths, + XElement element, + PreProcessingOperationFilterSettings settings) { - var paramElements = element.Elements() - .Where( - p => p.Name == KnownXmlStrings.Param) - .ToList(); - - // We need both the full URL and the absolute paths for processing. - // Full URL contains all path and query parameters. - // Absolute path is needed to get OperationId parsed out correctly. - var fullUrl = element.Elements() - .FirstOrDefault(p => p.Name == KnownXmlStrings.Url) - ?.Value; - - var absolutePath = fullUrl.UrlStringToAbsolutePath(); - - var operationMethod = (OperationType)Enum.Parse( - typeof(OperationType), - element.Elements().FirstOrDefault(p => p.Name == KnownXmlStrings.Verb)?.Value, - ignoreCase: true); - - var allGeneratedPathStrings = GeneratePossiblePaths( - absolutePath, - paramElements.Where( - p => p.Attribute(KnownXmlStrings.In)?.Value == KnownXmlStrings.Path) - .ToList()); - - foreach (var pathString in allGeneratedPathStrings) + var generationErrors = new List(); + + try { - if (!paths.ContainsKey(pathString)) + var paramElements = element.Elements() + .Where( + p => p.Name == KnownXmlStrings.Param) + .ToList(); + + // We need both the full URL and the absolute paths for processing. + // Full URL contains all path and query parameters. + // Absolute path is needed to get OperationId parsed out correctly. + var fullUrl = element.Elements() + .FirstOrDefault(p => p.Name == KnownXmlStrings.Url) + ?.Value; + + var absolutePath = fullUrl.UrlStringToAbsolutePath(); + + var operationMethod = (OperationType)Enum.Parse( + typeof(OperationType), + element.Elements().FirstOrDefault(p => p.Name == KnownXmlStrings.Verb)?.Value, + ignoreCase: true); + + var allGeneratedPathStrings = GeneratePossiblePaths( + absolutePath, + paramElements.Where( + p => p.Attribute(KnownXmlStrings.In)?.Value == KnownXmlStrings.Path) + .ToList()); + + foreach (var pathString in allGeneratedPathStrings) { - paths[pathString] = new OpenApiPathItem(); - } - - paths[pathString].Operations[operationMethod] = - new OpenApiOperation + if (!paths.ContainsKey(pathString)) { - OperationId = OperationHandler.GetOperationId(pathString, operationMethod) - }; + paths[pathString] = new OpenApiPathItem(); + } + + paths[pathString].Operations[operationMethod] = + new OpenApiOperation + { + OperationId = OperationHandler.GetOperationId(pathString, operationMethod) + }; + } + } + catch(Exception ex) + { + generationErrors.Add( + new GenerationError + { + Message = ex.Message, + ExceptionType = ex.GetType().Name + }); } + + return generationErrors; } /// diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/PreprocessingOperationFilters/ConvertAlternativeParamTagsFilter.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/PreprocessingOperationFilters/ConvertAlternativeParamTagsFilter.cs index 7892a2f..6186eb6 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/PreprocessingOperationFilters/ConvertAlternativeParamTagsFilter.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/PreprocessingOperationFilters/ConvertAlternativeParamTagsFilter.cs @@ -3,8 +3,11 @@ // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ +using System; +using System.Collections.Generic; using System.Linq; using System.Xml.Linq; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models.KnownStrings; using Microsoft.OpenApi.Models; @@ -21,69 +24,111 @@ public class ConvertAlternativeParamTagsFilter : IPreProcessingOperationFilter /// The paths to be updated. /// The xml element representing an operation in the annotation xml. /// The operation filter settings. - public void Apply(OpenApiPaths paths, XElement element, PreProcessingOperationFilterSettings settings) + /// The list of generation errors, if any produced when processing the filter. + public IList Apply( + OpenApiPaths paths, + XElement element, + PreProcessingOperationFilterSettings settings) { - var pathParamElements = element.Elements() - .Where(p => p.Name == KnownXmlStrings.PathParam) - .ToList(); + var generationErrors = new List(); - var queryParamElements = element.Elements() - .Where(p => p.Name == KnownXmlStrings.QueryParam) - .ToList(); - - var headerParamElements = element.Elements() - .Where(p => p.Name == KnownXmlStrings.Header) - .ToList(); + try + { - var requestTypeElements = element.Elements() - .Where(p => p.Name == KnownXmlStrings.RequestType) - .ToList(); + var pathParamElements = element.Elements() + .Where(p => p.Name == KnownXmlStrings.PathParam) + .ToList(); - var paramElements = element.Elements().Where(i => i.Name == KnownXmlStrings.Param); - var paramElementsWithInAttributeNotSpecified = paramElements.Where(i => i.Attribute("in") == null); + var queryParamElements = element.Elements() + .Where(p => p.Name == KnownXmlStrings.QueryParam) + .ToList(); - if (pathParamElements.Any()) - { - foreach (var pathParamElement in pathParamElements) - { - var conflictingPathParam = paramElements.Where( - i => i.Attribute("name")?.Value == pathParamElement.Attribute("name")?.Value); + var headerParamElements = element.Elements() + .Where(p => p.Name == KnownXmlStrings.Header) + .ToList(); - // Remove param tags that have same name as pathParam tags - // e.g. if service is documented like below, it will remove the param tag - // - // Sample path param - // Sample path param - conflictingPathParam?.Remove(); + var requestTypeElements = element.Elements() + .Where(p => p.Name == KnownXmlStrings.RequestType) + .ToList(); - var nameAttribute = pathParamElement.Attribute(KnownXmlStrings.Name); - var name = nameAttribute?.Value.Trim(); + var paramElements = element.Elements().Where(i => i.Name == KnownXmlStrings.Param); + var paramElementsWithInAttributeNotSpecified = paramElements.Where(i => i.Attribute("in") == null); - if (!string.IsNullOrWhiteSpace(name)) + if (pathParamElements.Any()) + { + foreach (var pathParamElement in pathParamElements) { - nameAttribute.Value = name; + var conflictingPathParam = paramElements.Where( + i => i.Attribute("name")?.Value == pathParamElement.Attribute("name")?.Value); + + // Remove param tags that have same name as pathParam tags + // e.g. if service is documented like below, it will remove the param tag + // + // Sample path param + // Sample path param + conflictingPathParam?.Remove(); + + var nameAttribute = pathParamElement.Attribute(KnownXmlStrings.Name); + var name = nameAttribute?.Value.Trim(); + + if (!string.IsNullOrWhiteSpace(name)) + { + nameAttribute.Value = name; + } + + pathParamElement.Name = KnownXmlStrings.Param; + pathParamElement.Add(new XAttribute(KnownXmlStrings.In, KnownXmlStrings.Path)); } + } - pathParamElement.Name = KnownXmlStrings.Param; - pathParamElement.Add(new XAttribute(KnownXmlStrings.In, KnownXmlStrings.Path)); + if (queryParamElements.Any()) + { + foreach (var queryParamElement in queryParamElements) + { + var conflictingQueryParam = paramElements.Where( + i => i.Attribute("name")?.Value == queryParamElement.Attribute("name")?.Value); + + // Remove param tags that have same name as queryParam tags + // e.g. if service is documented like below, it will remove the param tag + // + // Sample query param + // Sample query param + conflictingQueryParam?.Remove(); + + var nameAttribute = queryParamElement.Attribute(KnownXmlStrings.Name); + var name = nameAttribute?.Value.Trim(); + + if (!string.IsNullOrWhiteSpace(name)) + { + nameAttribute.Value = name; + } + + queryParamElement.Name = KnownXmlStrings.Param; + queryParamElement.Add(new XAttribute(KnownXmlStrings.In, KnownXmlStrings.Query)); + } } - } - if (queryParamElements.Any()) - { - foreach (var queryParamElement in queryParamElements) + if (requestTypeElements.Any()) { - var conflictingQueryParam = paramElements.Where( - i => i.Attribute("name")?.Value == queryParamElement.Attribute("name")?.Value); + var paramTagToRemove = element.Elements() + .Where(i => i.Name == KnownXmlStrings.Param + && string.IsNullOrWhiteSpace(i.Attribute("in")?.Value)); + + // If there are still conflicting param tags remaining, then it's safe to assume that these are neither + // path nor query params and could be documented request params which is not intended to be used with + // C# document generator so remove the tags. + paramTagToRemove?.Remove(); - // Remove param tags that have same name as queryParam tags - // e.g. if service is documented like below, it will remove the param tag - // - // Sample query param - // Sample query param - conflictingQueryParam?.Remove(); + foreach (var requestTypeElement in requestTypeElements) + { + requestTypeElement.Name = KnownXmlStrings.Param; + requestTypeElement.Add(new XAttribute(KnownXmlStrings.In, KnownXmlStrings.Body)); + } + } - var nameAttribute = queryParamElement.Attribute(KnownXmlStrings.Name); + foreach (var headerParamElement in headerParamElements) + { + var nameAttribute = headerParamElement.Attribute(KnownXmlStrings.Name); var name = nameAttribute?.Value.Trim(); if (!string.IsNullOrWhiteSpace(name)) @@ -91,53 +136,32 @@ public void Apply(OpenApiPaths paths, XElement element, PreProcessingOperationFi nameAttribute.Value = name; } - queryParamElement.Name = KnownXmlStrings.Param; - queryParamElement.Add(new XAttribute(KnownXmlStrings.In, KnownXmlStrings.Query)); + headerParamElement.Name = KnownXmlStrings.Param; + headerParamElement.Add(new XAttribute(KnownXmlStrings.In, KnownXmlStrings.Header)); } - } - - if (requestTypeElements.Any()) - { - var paramTagToRemove = element.Elements() - .Where(i => i.Name == KnownXmlStrings.Param - && string.IsNullOrWhiteSpace(i.Attribute("in")?.Value)); - - // If there are still conflicting param tags remaining, then it's safe to assume that these are neither - // path nor query params and could be documented request params which is not intended to be used with - // C# document generator so remove the tags. - paramTagToRemove?.Remove(); - foreach (var requestTypeElement in requestTypeElements) + // If any of the alternative tags are present then remove any param tag element that have "in" attribute + // not specified b/c assumption is made that those params are not supposed to be processed by + // CSharp Annotation Document Generator. + if (pathParamElements.Any() + || queryParamElements.Any() + || requestTypeElements.Any() + || headerParamElements.Any()) { - requestTypeElement.Name = KnownXmlStrings.Param; - requestTypeElement.Add(new XAttribute(KnownXmlStrings.In, KnownXmlStrings.Body)); + paramElementsWithInAttributeNotSpecified?.Remove(); } } - - foreach (var headerParamElement in headerParamElements) + catch(Exception ex) { - var nameAttribute = headerParamElement.Attribute(KnownXmlStrings.Name); - var name = nameAttribute?.Value.Trim(); - - if (!string.IsNullOrWhiteSpace(name)) - { - nameAttribute.Value = name; - } - - headerParamElement.Name = KnownXmlStrings.Param; - headerParamElement.Add(new XAttribute(KnownXmlStrings.In, KnownXmlStrings.Header)); + generationErrors.Add( + new GenerationError + { + Message = ex.Message, + ExceptionType = ex.GetType().Name + }); } - // If any of the alternative tags are present then remove any param tag element that have "in" attribute - // not specified b/c assumption is made that those params are not supposed to be processed by - // CSharp Annotation Document Generator. - if (pathParamElements.Any() - || queryParamElements.Any() - || requestTypeElements.Any() - || headerParamElements.Any()) - { - paramElementsWithInAttributeNotSpecified?.Remove(); - } + return generationErrors; } } } \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/PreprocessingOperationFilters/IPreProcessingOperationFilter.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/PreprocessingOperationFilters/IPreProcessingOperationFilter.cs index 97a74b4..fec3d9f 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/PreprocessingOperationFilters/IPreProcessingOperationFilter.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/PreprocessingOperationFilters/IPreProcessingOperationFilter.cs @@ -3,7 +3,9 @@ // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ +using System.Collections.Generic; using System.Xml.Linq; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.OperationFilters; using Microsoft.OpenApi.Models; @@ -26,6 +28,7 @@ public interface IPreProcessingOperationFilter : IFilter /// . /// /// - void Apply(OpenApiPaths paths, XElement element, PreProcessingOperationFilterSettings settings); + /// The list of generation errors, if any produced when processing the filter. + IList Apply(OpenApiPaths paths, XElement element, PreProcessingOperationFilterSettings settings); } } \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/PreprocessingOperationFilters/PopulateInAttributeFilter.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/PreprocessingOperationFilters/PopulateInAttributeFilter.cs index a7b648e..c624831 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/PreprocessingOperationFilters/PopulateInAttributeFilter.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/PreprocessingOperationFilters/PopulateInAttributeFilter.cs @@ -4,10 +4,12 @@ // ------------------------------------------------------------ using System; +using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Exceptions; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Extensions; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models.KnownStrings; using Microsoft.OpenApi.Models; @@ -25,48 +27,68 @@ public class PopulateInAttributeFilter : IPreProcessingOperationFilter /// The paths to be updated. /// The xml element representing an operation in the annotation xml. /// The operation filter settings. - public void Apply(OpenApiPaths paths, XElement element, PreProcessingOperationFilterSettings settings) + /// The list of generation errors, if any produced when processing the filter. + public IList Apply( + OpenApiPaths paths, + XElement element, + PreProcessingOperationFilterSettings settings) { - var paramElementsWithoutIn = element.Elements().Where( - p => p.Name == KnownXmlStrings.Param - && p.Attribute(KnownXmlStrings.In)?.Value == null) - .ToList(); + var generationErrors = new List(); - var url = element.Elements() - .FirstOrDefault(p => p.Name == KnownXmlStrings.Url) - ?.Value; - - if (!string.IsNullOrWhiteSpace(url)) + try { - foreach (var paramElement in paramElementsWithoutIn) + var paramElementsWithoutIn = element.Elements().Where( + p => p.Name == KnownXmlStrings.Param + && p.Attribute(KnownXmlStrings.In)?.Value == null) + .ToList(); + + var url = element.Elements() + .FirstOrDefault(p => p.Name == KnownXmlStrings.Url) + ?.Value; + + if (!string.IsNullOrWhiteSpace(url)) { - var paramName = paramElement.Attribute(KnownXmlStrings.Name)?.Value; + foreach (var paramElement in paramElementsWithoutIn) + { + var paramName = paramElement.Attribute(KnownXmlStrings.Name)?.Value; - if (url.Contains( + if (url.Contains( + $"/{{{paramName}}}", + StringComparison.InvariantCultureIgnoreCase) && + url.Contains( + $"={{{paramName}}}", + StringComparison.InvariantCultureIgnoreCase)) + { + // The parameter is in both path and query. We cannot determine what to put for "in" attribute. + throw new ConflictingPathAndQueryParametersException(paramName, url); + } + + if (url.Contains( $"/{{{paramName}}}", - StringComparison.InvariantCultureIgnoreCase) && - url.Contains( + StringComparison.InvariantCultureIgnoreCase)) + { + paramElement.Add(new XAttribute(KnownXmlStrings.In, KnownXmlStrings.Path)); + } + else if (url.Contains( $"={{{paramName}}}", StringComparison.InvariantCultureIgnoreCase)) - { - // The parameter is in both path and query. We cannot determine what to put for "in" attribute. - throw new ConflictingPathAndQueryParametersException(paramName, url); - } - - if (url.Contains( - $"/{{{paramName}}}", - StringComparison.InvariantCultureIgnoreCase)) - { - paramElement.Add(new XAttribute(KnownXmlStrings.In, KnownXmlStrings.Path)); - } - else if (url.Contains( - $"={{{paramName}}}", - StringComparison.InvariantCultureIgnoreCase)) - { - paramElement.Add(new XAttribute(KnownXmlStrings.In, KnownXmlStrings.Query)); + { + paramElement.Add(new XAttribute(KnownXmlStrings.In, KnownXmlStrings.Query)); + } } } } + catch(Exception ex) + { + generationErrors.Add( + new GenerationError + { + Message = ex.Message, + ExceptionType = ex.GetType().Name + }); + } + + return generationErrors; } } } \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/PreprocessingOperationFilters/ValidateInAttributeFilter.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/PreprocessingOperationFilters/ValidateInAttributeFilter.cs index ccd9b7e..2c93c02 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/PreprocessingOperationFilters/ValidateInAttributeFilter.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/PreprocessingOperationFilters/ValidateInAttributeFilter.cs @@ -3,10 +3,13 @@ // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ +using System; +using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Xml.Linq; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Exceptions; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models.KnownStrings; using Microsoft.OpenApi.Models; @@ -23,51 +26,71 @@ public class ValidateInAttributeFilter : IPreProcessingOperationFilter /// The paths to be validated. /// The xml element representing an operation in the annotation xml. /// The operation filter settings. - public void Apply(OpenApiPaths paths, XElement element, PreProcessingOperationFilterSettings settings) + /// The list of generation errors, if any produced when processing the filter. + public IList Apply( + OpenApiPaths paths, + XElement element, + PreProcessingOperationFilterSettings settings) { - var paramElements = element.Elements() + var generationErrors = new List(); + + try + { + var paramElements = element.Elements() .Where(p => p.Name == KnownXmlStrings.Param) .ToList(); - var paramWithInValues = paramElements.Where(p => p.Attribute(KnownXmlStrings.In)?.Value != null).ToList(); - - if (!paramWithInValues.Any()) - { - return; - } + var paramWithInValues = paramElements.Where(p => p.Attribute(KnownXmlStrings.In)?.Value != null).ToList(); - var paramElementsWithoutAllowedValues = paramWithInValues.Where( - p => !KnownXmlStrings.AllowedInValues.Contains(p.Attribute(KnownXmlStrings.In)?.Value)).ToList(); + if (!paramWithInValues.Any()) + { + return generationErrors; + } - if (paramElementsWithoutAllowedValues.Any()) - { - throw new NotSupportedInAttributeValueException( - paramElementsWithoutAllowedValues.Select( - p => p.Attribute(KnownXmlStrings.Name)?.Value), - paramElementsWithoutAllowedValues.Select( - p => p.Attribute(KnownXmlStrings.In)?.Value)); - } + var paramElementsWithoutAllowedValues = paramWithInValues.Where( + p => !KnownXmlStrings.AllowedInValues.Contains(p.Attribute(KnownXmlStrings.In)?.Value)).ToList(); - var url = element.Elements() - .FirstOrDefault(p => p.Name == KnownXmlStrings.Url) - ?.Value; + if (paramElementsWithoutAllowedValues.Any()) + { + throw new NotSupportedInAttributeValueException( + paramElementsWithoutAllowedValues.Select( + p => p.Attribute(KnownXmlStrings.Name)?.Value), + paramElementsWithoutAllowedValues.Select( + p => p.Attribute(KnownXmlStrings.In)?.Value)); + } - var pathParamElements = paramElements - .Where(p => p.Attribute(KnownXmlStrings.In)?.Value == KnownXmlStrings.Path) - .ToList(); + var url = element.Elements() + .FirstOrDefault(p => p.Name == KnownXmlStrings.Url) + ?.Value; - var matches = new Regex(@"\{(.*?)\}").Matches(url.Split('?')[0]); + var pathParamElements = paramElements + .Where(p => p.Attribute(KnownXmlStrings.In)?.Value == KnownXmlStrings.Path) + .ToList(); - foreach (Match match in matches) - { - var pathParamNameFromUrl = match.Groups[1].Value; + var matches = new Regex(@"\{(.*?)\}").Matches(url.Split('?')[0]); - // All path params in the URL must be documented. - if (!pathParamElements.Any(p => p.Attribute(KnownXmlStrings.Name)?.Value == pathParamNameFromUrl)) + foreach (Match match in matches) { - throw new UndocumentedPathParameterException(pathParamNameFromUrl, url); + var pathParamNameFromUrl = match.Groups[1].Value; + + // All path params in the URL must be documented. + if (!pathParamElements.Any(p => p.Attribute(KnownXmlStrings.Name)?.Value == pathParamNameFromUrl)) + { + throw new UndocumentedPathParameterException(pathParamNameFromUrl, url); + } } } + catch(Exception ex) + { + generationErrors.Add( + new GenerationError + { + Message = ex.Message, + ExceptionType = ex.GetType().Name + }); + } + + return generationErrors; } } } \ No newline at end of file diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/ReferenceRegistries/SchemaReferenceRegistry.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/ReferenceRegistries/SchemaReferenceRegistry.cs index e814695..33ac30f 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/ReferenceRegistries/SchemaReferenceRegistry.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/ReferenceRegistries/SchemaReferenceRegistry.cs @@ -5,6 +5,8 @@ using System; using System.Collections.Generic; +using System.IO; +using System.Xml.Linq; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Exceptions; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Extensions; @@ -19,6 +21,7 @@ public class SchemaReferenceRegistry : ReferenceRegistry { private readonly SchemaGenerationSettings _schemaGenerationSettings; private IPropertyNameResolver _propertyNameResolver; + private readonly Dictionary _propertyDescriptionMap = new Dictionary(); /// /// Creates an instance of . @@ -31,6 +34,21 @@ public SchemaReferenceRegistry(SchemaGenerationSettings schemaGenerationSettings _propertyNameResolver = schemaGenerationSettings.PropertyNameResolver; } + /// + /// Creates an instance of . + /// + /// The schema generation settings. + /// The property description map. + public SchemaReferenceRegistry( SchemaGenerationSettings schemaGenerationSettings, + Dictionary propertyDescriptionMap ) + { + _schemaGenerationSettings = schemaGenerationSettings + ?? throw new ArgumentNullException( nameof( schemaGenerationSettings ) ); + _propertyNameResolver = schemaGenerationSettings.PropertyNameResolver; + _propertyDescriptionMap = propertyDescriptionMap + ?? throw new ArgumentNullException( nameof( propertyDescriptionMap ) ); + } + /// /// The dictionary containing all references of the given type. /// @@ -95,6 +113,14 @@ internal override OpenApiSchema FindOrAddReference(Type input) return schema; } + if (input == typeof(Stream) || input.BaseType == typeof(Stream)) + { + schema.Type = "string"; + schema.Format = "binary"; + + return schema; + } + if (input.IsEnum) { schema.Type = "string"; @@ -167,6 +193,8 @@ internal override OpenApiSchema FindOrAddReference(Type input) } } + var a = input.FullName; + foreach (var propertyInfo in input.GetProperties()) { var ignoreProperty = false; @@ -175,6 +203,15 @@ internal override OpenApiSchema FindOrAddReference(Type input) var propertyName = _propertyNameResolver.ResolvePropertyName(propertyInfo); + // Construct property name like it shows up in documentation xml. + var propertyFullName = propertyInfo.DeclaringType.Namespace + "." + + propertyInfo.DeclaringType?.Name + "." + propertyInfo.Name; + + if ( this._propertyDescriptionMap.ContainsKey( propertyFullName ) ) + { + innerSchema.Description = this._propertyDescriptionMap[propertyFullName]; + } + var attributes = propertyInfo.GetCustomAttributes(false); foreach (var attribute in attributes) diff --git a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/TypeFetcher.cs b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/TypeFetcher.cs index 212f637..7c07528 100644 --- a/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/TypeFetcher.cs +++ b/src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/TypeFetcher.cs @@ -12,10 +12,14 @@ using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Exceptions; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Extensions; +#if !NETFRAMEWORK +using System.Runtime.Loader; +#endif + namespace Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration { /// - /// Proxy class for fetching type information by loading assemblies into private AppDomain. + /// Proxy class for fetching type information by loading assemblies. /// public class TypeFetcher { @@ -23,6 +27,20 @@ public class TypeFetcher private readonly IList _contractAssemblyPaths = new List(); private readonly IDictionary _typeMap = new Dictionary(); +#if !NETFRAMEWORK + private readonly AssemblyLoadContext _context; + + /// + /// Creates new instance of . + /// + /// The list of contract assembly paths. + /// The assembly load context. + public TypeFetcher(IList contractAssemblyPaths, AssemblyLoadContext context) + { + _context = context; + _contractAssemblyPaths = contractAssemblyPaths; + } +#else /// /// Creates new instance of . /// @@ -31,6 +49,7 @@ public TypeFetcher(IList contractAssemblyPaths) { _contractAssemblyPaths = contractAssemblyPaths; } +#endif private Type CreateListType(string typeName) { @@ -150,11 +169,14 @@ public Type LoadType(string typeName) return _typeMap[typeName]; } - // Load custom type from the given list of assemblies. - foreach (var file in _contractAssemblyPaths) + // Try to fetch the type from the already loaded assemblies, so we do not load duplicate assemblies in + // app domain. + var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies() + .Where(a => !a.IsDynamic); + + foreach (var loadedAssembly in loadedAssemblies) { - var assembly = Assembly.LoadFrom(file); - var contractType = assembly.GetType(typeName); + var contractType = loadedAssembly.GetType(typeName); if (contractType == null) { @@ -166,12 +188,11 @@ public Type LoadType(string typeName) return contractType; } - var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies() - .Where(a => !a.IsDynamic); - - foreach (var loadedAssembly in loadedAssemblies) +#if !NETFRAMEWORK + foreach (var contractAssemblyPath in this._contractAssemblyPaths) { - var contractType = loadedAssembly.GetType(typeName); + var assembly = _context.LoadFromAssemblyPath(contractAssemblyPath); + var contractType = assembly.GetType(typeName); if (contractType == null) { @@ -179,11 +200,24 @@ public Type LoadType(string typeName) } _typeMap.Add(typeName, contractType); - return contractType; } +#else + // Load custom type from the given list of assemblies. + foreach (var contractAssemblyPath in _contractAssemblyPaths) + { + var assembly = Assembly.LoadFrom(contractAssemblyPath); + var contractType = assembly.GetType(typeName); + if (contractType == null) + { + continue; + } + _typeMap.Add(typeName, contractType); + return contractType; + } +#endif var errorMessage = string.Format( SpecificationGenerationMessages.TypeNotFound, typeName, diff --git a/test/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests/ExtensionsTests/XElementExtensionTest.cs b/test/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests/ExtensionsTests/XElementExtensionTest.cs index 57a043e..e5e833c 100644 --- a/test/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests/ExtensionsTests/XElementExtensionTest.cs +++ b/test/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests/ExtensionsTests/XElementExtensionTest.cs @@ -9,7 +9,9 @@ using System.Xml.Linq; using FluentAssertions; using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Exceptions; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Extensions; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.ReferenceRegistries; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Readers; @@ -23,10 +25,6 @@ public class XElementExtensionTest { private const string InputDirectory = "ExtensionsTests/Input"; private readonly ITestOutputHelper _output; - private readonly TypeFetcher typeFetcher = new TypeFetcher( - new List() { Path.Combine( - InputDirectory, - "Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests.Contracts.dll") }); private readonly SchemaReferenceRegistry schemaReferenceRegistry = new SchemaReferenceRegistry( new SchemaGenerationSettings(new DefaultPropertyNameResolver())); @@ -83,6 +81,7 @@ public static IEnumerable GetTestCasesForXElementExtensionExampleShoul { "Empty example element", XElement.Parse(""), + new Dictionary(), new Dictionary() }; @@ -91,6 +90,7 @@ public static IEnumerable GetTestCasesForXElementExtensionExampleShoul "Example with url", XElement.Parse( "Test Examplehttps://localhost/test.json"), + new Dictionary(), new Dictionary() { { @@ -109,6 +109,16 @@ public static IEnumerable GetTestCasesForXElementExtensionExampleShoul "Example element with cref", XElement.Parse(@"" + @""), + new Dictionary() + { + { + "F:Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests.Contracts.Examples.SampleObject1Example", + new FieldValueInfo + { + Value = ExpectedExamples.SampleObject1Example + } + } + }, new Dictionary() { { @@ -129,6 +139,16 @@ public static IEnumerable GetTestCasesForXElementExtensionExampleShoul + @"" + @"" + @"Test example 2"), + new Dictionary() + { + { + "F:Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests.Contracts.Examples.SampleObject1Example", + new FieldValueInfo + { + Value = ExpectedExamples.SampleObject1Example + } + } + }, new Dictionary() { { @@ -150,6 +170,7 @@ public static IEnumerable GetTestCasesForXElementExtensionExampleShoul { "Example element with inline value", XElement.Parse(@"Test Example"), + new Dictionary(), new Dictionary() { { @@ -167,7 +188,15 @@ public static IEnumerable GetTestCasesForXElementExtensionExampleShoul { "Example element contain both value and url.", XElement.Parse(""), - SpecificationGenerationMessages.ProvideEitherValueOrUrlTag + new Dictionary(), + new List + { + new GenerationError + { + ExceptionType=nameof(InvalidExampleException), + Message = SpecificationGenerationMessages.ProvideEitherValueOrUrlTag + } + } }; yield return new object[] @@ -175,7 +204,15 @@ public static IEnumerable GetTestCasesForXElementExtensionExampleShoul "Example value with no cref and value.", XElement.Parse( @"Test Example"), - SpecificationGenerationMessages.ProvideValueForExample + new Dictionary(), + new List + { + new GenerationError + { + ExceptionType=nameof(InvalidExampleException), + Message = SpecificationGenerationMessages.ProvideValueForExample + } + } }; yield return new object[] @@ -183,18 +220,32 @@ public static IEnumerable GetTestCasesForXElementExtensionExampleShoul "Example element with cref containing type that doesn't exists in provided assembly.", XElement.Parse(@""), - "Type \"Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests.DoesnotExists\" could not be found." - + " Ensure that it exists in one of the following assemblies: " - + "Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests.Contracts.dll" - }; - - yield return new object[] - { - "Example element with cref containing filed that doesn't exists in provided type.", - XElement.Parse(@""), - "Field \"DoesNotExists\" could not be found for type: " - + "\"Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests.Contracts.Examples\"." + new Dictionary() + { + { + "F:Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests.DoesnotExists.DoesnotExists", + new FieldValueInfo + { + Error = new GenerationError + { + ExceptionType = nameof(TypeLoadException), + Message = "Type \"Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests.DoesnotExists\" could not be found." + + " Ensure that it exists in one of the following assemblies: " + + "Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests.Contracts.dll" + } + } + } + }, + new List + { + new GenerationError + { + ExceptionType = nameof(TypeLoadException), + Message = "Type \"Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests.DoesnotExists\" could not be found." + + " Ensure that it exists in one of the following assemblies: " + + "Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests.Contracts.dll" + } + } }; } @@ -204,7 +255,15 @@ public static IEnumerable GetTestCasesForXElementExtensionHeaderShould { "Header element with no name attribute.", XElement.Parse("
"), - string.Format(SpecificationGenerationMessages.UndocumentedName, "header") + new Dictionary(), + new List + { + new GenerationError + { + ExceptionType=nameof(InvalidHeaderException), + Message = string.Format(SpecificationGenerationMessages.UndocumentedName, "header") + } + } }; } @@ -215,12 +274,25 @@ public static IEnumerable GetTestCasesForXElementExtensionHeaderShould "Header with no description element", XElement.Parse( @"
"), + new Dictionary() + { + { + "T:System.String", + new SchemaGenerationInfo + { + Schema = new OpenApiSchema + { + Type = "string" + } + } + } + }, new Dictionary() { { "header1", new OpenApiHeader { - Schema = new OpenApiSchema + Schema = new OpenApiSchema { Type = "string" } @@ -234,6 +306,19 @@ public static IEnumerable GetTestCasesForXElementExtensionHeaderShould "Header with description element", XElement.Parse( @"
Test header
"), + new Dictionary() + { + { + "T:System.String", + new SchemaGenerationInfo + { + Schema = new OpenApiSchema + { + Type = "string" + } + } + } + }, new Dictionary() { { @@ -255,6 +340,19 @@ public static IEnumerable GetTestCasesForXElementExtensionHeaderShould XElement.Parse( @"
Test header
" + @"
"), + new Dictionary() + { + { + "T:System.String", + new SchemaGenerationInfo + { + Schema = new OpenApiSchema + { + Type = "string" + } + } + } + }, new Dictionary() { { @@ -298,12 +396,14 @@ public void GetDescriptionTextFromLastTextNodeShouldSucceed( public void XElementExtensionExampleShouldFail( string testCaseName, XElement xElement, - string expectedExceptionMessage) + Dictionary crefFieldValueMap, + List expectedGenerationErrors) { _output.WriteLine(testCaseName); - Action action = () => xElement.ToOpenApiExamples(typeFetcher); - action.Should().Throw(expectedExceptionMessage); + var generationErrors = new List(); + xElement.ToOpenApiExamples(crefFieldValueMap, generationErrors); + generationErrors.Should().BeEquivalentTo(expectedGenerationErrors); } [Theory] @@ -311,12 +411,15 @@ public void XElementExtensionExampleShouldFail( public void XElementExtensionExampleShouldSucceed( string testCaseName, XElement xElement, + Dictionary crefFieldValueMap, Dictionary expectedOpenApiExamples) { _output.WriteLine(testCaseName); - var openApiExamples = xElement.ToOpenApiExamples(typeFetcher); + var generationErrors = new List(); + var openApiExamples = xElement.ToOpenApiExamples(crefFieldValueMap, generationErrors); openApiExamples.Should().BeEquivalentTo(expectedOpenApiExamples); + generationErrors.Count.Should().Be(0); } [Theory] @@ -324,12 +427,15 @@ public void XElementExtensionExampleShouldSucceed( public void XElementExtensionHeaderShouldFail( string testCaseName, XElement xElement, - string expectedExceptionMessage) + Dictionary crefSchemaMap, + List expectedGenerationErrors) { _output.WriteLine(testCaseName); - Action action = () => xElement.ToOpenApiHeaders(typeFetcher, schemaReferenceRegistry); - action.Should().Throw(expectedExceptionMessage); + var generationErrors = new List(); + xElement.ToOpenApiHeaders(crefSchemaMap, generationErrors); + + generationErrors.Should().BeEquivalentTo(expectedGenerationErrors); } [Theory] @@ -337,13 +443,16 @@ public void XElementExtensionHeaderShouldFail( public void XElementExtensionHeaderShouldSucceed( string testCaseName, XElement xElement, - Dictionary expectedOpenApiHeaders) + Dictionary crefSchemaMap, + Dictionary expectedOpenApiHeaders) { _output.WriteLine(testCaseName); - var openApiHeaders = xElement.ToOpenApiHeaders(typeFetcher,schemaReferenceRegistry); + var generationErrors = new List(); + var openApiHeaders = xElement.ToOpenApiHeaders(crefSchemaMap, generationErrors); openApiHeaders.Should().BeEquivalentTo(expectedOpenApiHeaders); + generationErrors.Count.Should().Be(0); } } } \ No newline at end of file diff --git a/test/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests/FilterTests/Input/ParamWithNotSupportedInValue.xml b/test/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests/FilterTests/Input/ParamWithNotSupportedInValue.xml index 2ef950b..a3d26a6 100644 --- a/test/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests/FilterTests/Input/ParamWithNotSupportedInValue.xml +++ b/test/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests/FilterTests/Input/ParamWithNotSupportedInValue.xml @@ -8,7 +8,7 @@ Header param 1 Header param 2 - Header param 2 + Header param 2 The object id Sample query boolean diff --git a/test/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests/FilterTests/ValidateInAttributeFilterTest.cs b/test/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests/FilterTests/ValidateInAttributeFilterTest.cs index b413b57..e4f07ca 100644 --- a/test/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests/FilterTests/ValidateInAttributeFilterTest.cs +++ b/test/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests/FilterTests/ValidateInAttributeFilterTest.cs @@ -9,6 +9,7 @@ using System.Xml.Linq; using FluentAssertions; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Exceptions; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models.KnownStrings; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.PreprocessingOperationFilters; using Microsoft.OpenApi.Models; @@ -35,20 +36,28 @@ public static IEnumerable GetTestCasesForValidateInAttributeShouldFail { "Param with not supported in value", XElement.Load(Path.Combine(InputDirectory, "ParamWithNotSupportedInValue.xml")), - string.Format( + new List + { + new GenerationError + { + ExceptionType = nameof(NotSupportedInAttributeValueException), + Message = string.Format( SpecificationGenerationMessages.NotSupportedInAttributeValue, - "notSupported, notSupported2", "sampleHeaderParam2, sampleHeaderParam3", + "notSupported, notSupported2", string.Join(", ", KnownXmlStrings.AllowedInValues)) + } + } + }; } [Theory] [MemberData(nameof(GetTestCasesForValidateInAttributeShouldFail))] - public void ValidateInAttributeShouldFail( + public void ValidateInAttributeShouldGenerateErrors( string testName, XElement xElement, - string expectedExceptionMessage) + IList expectedGenerationErrors) { var filter = new ValidateInAttributeFilter(); var settings = new PreProcessingOperationFilterSettings(); @@ -56,8 +65,8 @@ public void ValidateInAttributeShouldFail( var openApiPaths = new OpenApiPaths(); _output.WriteLine(testName); - Action action = () => filter.Apply(openApiPaths, xElement, settings); - action.Should().Throw(expectedExceptionMessage); + var actualGenerationErrors = filter.Apply(openApiPaths, xElement, settings); + actualGenerationErrors.Should().BeEquivalentTo(expectedGenerationErrors); } } } \ No newline at end of file diff --git a/test/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests.csproj b/test/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests.csproj index 18adfec..26bd7cd 100644 --- a/test/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests.csproj +++ b/test/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests.csproj @@ -20,7 +20,7 @@ - + @@ -200,6 +200,9 @@ PreserveNewest + + PreserveNewest + PreserveNewest diff --git a/test/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests/OpenApiDocumentGeneratorTests/Input/Newtonsoft.Json.dll b/test/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests/OpenApiDocumentGeneratorTests/Input/Newtonsoft.Json.dll new file mode 100644 index 0000000..d0aaed9 Binary files /dev/null and b/test/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests/OpenApiDocumentGeneratorTests/Input/Newtonsoft.Json.dll differ diff --git a/test/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests/OpenApiDocumentGeneratorTests/OpenApiDocumentGeneratorTest.cs b/test/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests/OpenApiDocumentGeneratorTests/OpenApiDocumentGeneratorTest.cs index 0ad4219..f352eaf 100644 --- a/test/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests/OpenApiDocumentGeneratorTests/OpenApiDocumentGeneratorTest.cs +++ b/test/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests/OpenApiDocumentGeneratorTests/OpenApiDocumentGeneratorTest.cs @@ -103,6 +103,9 @@ public static IEnumerable GetTestCasesForCustomGenerationSettingsShoul Path.Combine( InputDirectory, "Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests.SampleApis.dll"), + Path.Combine( + InputDirectory, + "Newtonsoft.Json.dll"), Path.Combine( InputDirectory, "Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests.Contracts.dll") diff --git a/test/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests/OpenApiDocumentGeneratorTests/UpdateDescriptionFilter.cs b/test/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests/OpenApiDocumentGeneratorTests/UpdateDescriptionFilter.cs index 382e497..d254bdc 100644 --- a/test/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests/OpenApiDocumentGeneratorTests/UpdateDescriptionFilter.cs +++ b/test/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests/OpenApiDocumentGeneratorTests/UpdateDescriptionFilter.cs @@ -3,6 +3,8 @@ // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------ +using System.Collections.Generic; +using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.PostProcessingDocumentFilters; using Microsoft.OpenApi.Models; @@ -18,11 +20,14 @@ internal class UpdateDescriptionFilter : IPostProcessingDocumentFilter ///
/// The open API document to update. /// The filter settings. - public void Apply( + /// The list of generation errors, if any produced when processing the filter. + public IList Apply( OpenApiDocument openApiDocument, PostProcessingDocumentFilterSettings settings) { openApiDocument.Info.Description = "Updated Description"; + + return new List(); } } } \ No newline at end of file