示例#1
0
        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {
            var aboutTag = new OpenApiTag();

            aboutTag.Name        = "about";
            aboutTag.Description = APIGatewayResources.AboutTagDescription;

            var authenticationTag = new OpenApiTag();

            authenticationTag.Name        = "authentication";
            authenticationTag.Description = APIGatewayResources.AuthenticationTagDescription;

            var argumentScriptsTag = new OpenApiTag();

            argumentScriptsTag.Name        = "argument_scripts";
            argumentScriptsTag.Description = APIGatewayResources.ArgumentScriptsTagDescription;

            var runspacesTag = new OpenApiTag();

            runspacesTag.Name        = "runspaces";
            runspacesTag.Description = APIGatewayResources.RunspaceTagDescription;

            var scriptExecutionsTag = new OpenApiTag();

            scriptExecutionsTag.Name        = "script_executions";
            scriptExecutionsTag.Description = APIGatewayResources.ScriptExecutionsTagDescription;

            swaggerDoc.Tags.Add(aboutTag);
            swaggerDoc.Tags.Add(authenticationTag);
            swaggerDoc.Tags.Add(argumentScriptsTag);
            swaggerDoc.Tags.Add(runspacesTag);
            swaggerDoc.Tags.Add(scriptExecutionsTag);
        }
示例#2
0
        internal static void ProcessTagAttribute(OpenApiDocument document, dynamic tagAttribute)
        {
            if (document.Tags == null)
            {
                document.Tags = new List <OpenApiTag>();
            }

            var tag = document.Tags.SingleOrDefault(t => t.Name == tagAttribute.Name);

            if (tag == null)
            {
                tag = new OpenApiTag();
                document.Tags.Add(tag);
            }

            tag.Description = tagAttribute.Description;
            tag.Name        = tagAttribute.Name;

            if (!string.IsNullOrEmpty(tagAttribute.DocumentationDescription) ||
                !string.IsNullOrEmpty(tagAttribute.DocumentationUrl))
            {
                tag.ExternalDocumentation = new OpenApiExternalDocumentation
                {
                    Description = tagAttribute.DocumentationDescription,
                    Url         = tagAttribute.DocumentationUrl
                };
            }
        }
        public void ValidateExtensionNameStartsWithXDashInTag()
        {
            // Arrange
            IEnumerable <ValidationError> errors;
            OpenApiTag tag = new OpenApiTag
            {
                Name = "tag"
            };

            tag.Extensions.Add("tagExt", new OpenApiString("value"));

            // Act
            var validator = new OpenApiValidator();

            validator.Visit(tag as IOpenApiExtensible);
            errors = validator.Errors;
            bool result = !errors.Any();

            // Assert
            Assert.False(result);
            Assert.NotNull(errors);
            ValidationError error = Assert.Single(errors);

            Assert.Equal(String.Format(SRResource.Validation_ExtensionNameMustBeginWithXDash, "tagExt", "#/extensions"), error.ErrorMessage);
        }
 private void AddTagsToOperations(ICollection <OpenApiOperation> operations, OpenApiTag tag)
 {
     foreach (var operation in operations)
     {
         operation.Tags.Clear();
         operation.Tags.Add(tag);
     }
 }
示例#5
0
 public void Traverse(OpenApiTag tag)
 {
     if (tag == null)
     {
         return;
     }
     Visitor.Visit(tag);
     Traverse(tag.ExternalDocs);
 }
 private OATag CreateOATag(OpenApiTag openApiTag)
 {
     return(new OATag()
     {
         Name = openApiTag.Name,
         Description = openApiTag.Description,
         ExternalDocs = CreateExternalDocs(openApiTag.ExternalDocs),
     });
 }
示例#7
0
        /// <summary>
        /// Visits <see cref="OpenApiTag"/> and child objects
        /// </summary>
        internal void Walk(OpenApiTag tag)
        {
            if (tag == null)
            {
                return;
            }

            _visitor.Visit(tag);
            _visitor.Visit(tag.ExternalDocs);
            _visitor.Visit(tag as IOpenApiExtensible);
        }
示例#8
0
        /// <summary>
        /// Visits <see cref="OpenApiTag"/> and child objects
        /// </summary>
        internal void Walk(OpenApiTag tag)
        {
            if (tag == null || ProcessAsReference(tag))
            {
                return;
            }

            _visitor.Visit(tag);
            _visitor.Visit(tag.ExternalDocs);
            _visitor.Visit(tag as IOpenApiExtensible);
        }
示例#9
0
        private void AddToIndex(OpenApiTag tag, OpenApiOperation operation)
        {
            List <OpenApiOperation> operations;

            if (!Index.TryGetValue(tag, out operations))
            {
                operations = new List <OpenApiOperation>();
                Index[tag] = operations;
            }

            operations.Add(operation);
        }
        public static OpenApiTag LoadTag(ParseNode n)
        {
            var mapNode = n.CheckMapNode("tag");

            var domainObject = new OpenApiTag();

            foreach (var propertyNode in mapNode)
            {
                propertyNode.ParseField(domainObject, _tagFixedFields, _tagPatternFields);
            }

            return(domainObject);
        }
示例#11
0
    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
    {
        swaggerDoc.Tags ??= new List <OpenApiTag>();

        var tag = new OpenApiTag
        {
            Name        = "Workflow Endpoints",
            Description = "A collection of HTTP endpoints exposed by workflows",
        };

        var schemaRepository = context.SchemaRepository;

        swaggerDoc.Tags.Add(tag);

        var httpEndpoints = FindHttpEndpointsAsync(CancellationToken.None).ToLookupAsync(x => x.Path).Result;

        foreach (var grouping in httpEndpoints)
        {
            var path  = grouping.Key;
            var first = grouping.First();

            swaggerDoc.Paths.Add(path, new OpenApiPathItem
            {
                Description = first.Description,
                Operations  = grouping.ToDictionary(GetOperationType, httpEndpoint =>
                {
                    var operation = new OpenApiOperation
                    {
                        Tags = { tag },
                    };

                    if (httpEndpoint.TargetType != null || httpEndpoint.JsonSchema != null)
                    {
                        operation.RequestBody = new OpenApiRequestBody
                        {
                            Required = true,
                            Content  =
                            {
                                ["Unspecified"] = new OpenApiMediaType
                                {
                                Schema = httpEndpoint.TargetType != null ? _schemaGenerator.GenerateSchema(httpEndpoint.TargetType, schemaRepository) : new OpenApiSchema()     // TODO: Convert JSON schema into OpenAPI schema.
                                }
                            }
                        };
                    }

                    return(operation);
                })
            });
        }
    }
        /// <summary>
        /// Enrichment of the Filter used by swagger in order to add every dynamically load peripheral and their methods
        /// </summary>
        /// <param name="swaggerDoc">OpenApiDocument generated by swagger to enrich </param>
        /// <param name="context">The current DocumentFilterContext</param>
        void IDocumentFilter.Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {
            //Removing path that are generated automatically since it's irrelevant
            swaggerDoc.Paths.Clear();


            List <MethodData> allMethodInfos = generateAllMethodInfos();

            int counter = 0;

            //Tag Handling
            OpenApiTag tag = new OpenApiTag {
                Name = DEFAULT_API_TAG_NAME
            };
            List <OpenApiTag> tagList = new List <OpenApiTag>();

            tagList.Add(tag);


            //Response handling

            //Creating the responses indidually
            OpenApiResponse positiveAnswer = new OpenApiResponse {
                Description = SUCCESS_DESCRIPTION
            };
            OpenApiResponse negativeAnswer = new OpenApiResponse {
                Description = FAILURE_DESCRIPTION
            };

            //Generating the list of answers
            OpenApiResponses allPossibleAnswers = new OpenApiResponses();

            allPossibleAnswers.Add(SUCCESS_HTTP_CODE, positiveAnswer);
            allPossibleAnswers.Add(FAILURE_HTTP_CODE, negativeAnswer);


            foreach (MethodData methodInfo in allMethodInfos)
            {
                Dictionary <OperationType, OpenApiOperation> operationDictionnary = new Dictionary <OperationType, OpenApiOperation>();

                OpenApiOperation currentOperation = new OpenApiOperation {
                    OperationId = UID + counter, Tags = tagList, Responses = allPossibleAnswers, Parameters = methodInfo.parameters
                };
                ++counter;

                operationDictionnary.Add(OperationType.Get, currentOperation);
                swaggerDoc.Paths.Add(methodInfo.route, new OpenApiPathItem {
                    Operations = operationDictionnary
                });
            }
        }
        /// <summary>
        /// Append tag.
        /// </summary>
        /// <param name="tagItem">The tag item.</param>
        public void AppendTag(OpenApiTag tagItem)
        {
            if (Tags == null)
            {
                Tags = new List <OpenApiTag>();
            }

            if (Tags.Any(c => c.Name == tagItem.Name))
            {
                return;
            }

            Tags.Add(tagItem);
        }
示例#14
0
        /// <inheritdoc/>
        protected override void SetTags(OpenApiOperation operation)
        {
            string     value = EdmOperation.IsAction() ? "Actions" : "Functions";
            OpenApiTag tag   = new OpenApiTag
            {
                Name = NavigationSource.Name + "." + value,
            };

            tag.Extensions.Add(Constants.xMsTocType, new OpenApiString("container"));
            operation.Tags.Add(tag);

            Context.AppendTag(tag);

            base.SetTags(operation);
        }
示例#15
0
        private static OpenApiTag LoadTagByReference(
            ParsingContext context,
            string tagName)
        {
            var tagObject = new OpenApiTag()
            {
                UnresolvedReference = true,
                Reference           = new OpenApiReference()
                {
                    Id = tagName, Type = ReferenceType.Tag
                }
            };

            return(tagObject);
        }
示例#16
0
        /// <inheritdoc/>
        protected override void SetTags(OpenApiOperation operation)
        {
            OpenApiTag tag = new OpenApiTag
            {
                Name = EntitySet.Name + "." + EntitySet.EntityType().Name,
            };

            tag.Extensions.Add(Constants.xMsTocType, new OpenApiString("page"));

            operation.Tags.Add(tag);

            Context.AppendTag(tag);

            base.SetTags(operation);
        }
示例#17
0
        private void DocumentControllerSummaries(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {
            foreach (var description in context.ApiDescriptions)
            {
                if (!(description.ActionDescriptor is ControllerActionDescriptor descriptor))
                {
                    continue;
                }

                var controllerType = descriptor.ControllerTypeInfo;
                if (!controllerType.TryGetAttribute <DisplayAttribute>(true, out var display))
                {
                    if (controllerType.ImplementsGeneric(typeof(ResourceController <>)))
                    {
                        // look for a DisplayAttribute on the underlying resource type
                        controllerType = controllerType.AsType().GetGenericArguments()[0].GetTypeInfo();
                        if (!controllerType.TryGetAttribute(true, out display) || display == null)
                        {
                            continue;
                        }
                    }
                    else
                    {
                        throw new InvalidOperationException(
                                  _localizer.GetString("All surfaced controllers must provide a DisplayAttribute, but '{ControllerType}' does not.", controllerType.Name));
                    }
                }

                var tag = new OpenApiTag();

                var name = display.GetGroupName() ?? GetSubstituteGroupName(descriptor);
                if (!string.IsNullOrWhiteSpace(name))
                {
                    tag.Name = _localizer.GetString(name);
                }

                var summary = display.GetDescription();
                if (!string.IsNullOrWhiteSpace(summary))
                {
                    tag.Description = _localizer.GetString(summary);
                }

                if (!swaggerDoc.Tags.Any(x => x.Name.Equals(tag.Name, StringComparison.OrdinalIgnoreCase)))
                {
                    swaggerDoc.Tags.Add(tag);
                }
            }
        }
        /// <summary>Initializes a new instance of the <see cref="CSharpRefitTemplateModel" /> class.</summary>
        /// <param name="controllerName">Name of the controller.</param>
        /// <param name="operations">The operations.</param>
        /// <param name="document">The document.</param>
        /// <param name="settings">The settings.</param>
        public CSharpRefitTemplateModel(
            string controllerName,
            IEnumerable <CSharpOperationModel> operations,
            OpenApiDocument document,
            CSharpRefitGeneratorSettings settings, OpenApiTag tag)
            : base(controllerName, settings)
        {
            _document = document;
            _settings = settings;

            Class      = controllerName;
            Operations = operations;

            BaseClass      = _settings.ControllerBaseClass?.Replace("{controller}", controllerName);
            NameSpace      = _settings.CSharpGeneratorSettings.Namespace;
            TagDescription = tag?.Description;
        }
        /// <inheritdoc/>
        protected override void SetTags(OpenApiOperation operation)
        {
            IList <string> items = new List <string>
            {
                NavigationSource.Name
            };

            foreach (var segment in Path.Segments.Skip(1))
            {
                ODataNavigationPropertySegment npSegment = segment as ODataNavigationPropertySegment;
                if (npSegment != null)
                {
                    if (npSegment.NavigationProperty == NavigationProperty)
                    {
                        items.Add(NavigationProperty.ToEntityType().Name);
                        break;
                    }
                    else
                    {
                        if (items.Count >= Context.Settings.TagDepth - 1)
                        {
                            items.Add(npSegment.NavigationProperty.ToEntityType().Name);
                            break;
                        }
                        else
                        {
                            items.Add(npSegment.NavigationProperty.Name);
                        }
                    }
                }
            }

            string     name = string.Join(".", items);
            OpenApiTag tag  = new OpenApiTag
            {
                Name = name
            };

            tag.Extensions.Add(Constants.xMsTocType, new OpenApiString("page"));
            operation.Tags.Add(tag);

            Context.AppendTag(tag);

            base.SetTags(operation);
        }
        public void OpenApiTagServerVariableComparerShouldSucceed(
            string testCaseName,
            OpenApiTag source,
            OpenApiTag target,
            List<OpenApiDifference> expectedDifferences)
        {
            _output.WriteLine(testCaseName);

            var comparisonContext = new ComparisonContext(new OpenApiComparerFactory(), _sourceDocument,
                _targetDocument);
            var comparer = new OpenApiTagComparer();
            comparer.Compare(source, target, comparisonContext);

            var differences = comparisonContext.OpenApiDifferences.ToList();
            differences.Count().ShouldBeEquivalentTo(expectedDifferences.Count);

            differences.ShouldBeEquivalentTo(expectedDifferences);
        }
        private static OpenApiTag LoadTagByReference(
            ParsingContext context,
            OpenApiDiagnostic diagnostic,
            string tagName)
        {
            var tagObject = (OpenApiTag)context.GetReferencedObject(
                diagnostic,
                ReferenceType.Tag,
                tagName);

            if (tagObject == null)
            {
                tagObject = new OpenApiTag {
                    Name = tagName
                };
            }

            return(tagObject);
        }
示例#22
0
        /// <inheritdoc/>
        protected override void SetTags(OpenApiOperation operation)
        {
            // In this SDK, we use "[Singleton Name].[Singleton Entity Type Name]
            // For example: "Me.User"
            OpenApiTag tag = new OpenApiTag
            {
                Name = Singleton.Name + "." + Singleton.EntityType().Name,
            };

            // Use an extension for TOC (Table of Content)
            tag.Extensions.Add(Constants.xMsTocType, new OpenApiString("page"));

            operation.Tags.Add(tag);

            Context.AppendTag(tag);

            // Call base.SetTags() at the end of this method.
            base.SetTags(operation);
        }
        public void ValidateNameIsRequiredInTag()
        {
            // Arrange
            IEnumerable <ValidationError> errors;
            OpenApiTag tag = new OpenApiTag();

            // Act
            var validator = new OpenApiValidator();

            validator.Visit(tag);
            errors = validator.Errors;
            bool result = !errors.Any();

            // Assert
            Assert.False(result);
            Assert.NotNull(errors);
            ValidationError error = Assert.Single(errors);

            Assert.Equal(String.Format(SRResource.Validation_FieldIsRequired, "name", "tag"), error.ErrorMessage);
        }
        /// <summary>
        /// Replace references to tags with either tag objects declared in components, or inline tag object
        /// </summary>
        private void ResolveTags(IList <OpenApiTag> tags)
        {
            for (int i = 0; i < tags.Count; i++)
            {
                var tag = tags[i];
                if (IsUnresolvedReference(tag))
                {
                    var resolvedTag = ResolveReference <OpenApiTag>(tag.Reference);

                    if (resolvedTag == null)
                    {
                        resolvedTag = new OpenApiTag()
                        {
                            Name = tag.Reference.Id
                        };
                    }
                    tags[i] = resolvedTag;
                }
            }
        }
        /// <summary>Generates the client class.</summary>
        /// <param name="controllerName">Name of the controller.</param>
        /// <param name="controllerClassName">Name of the controller class.</param>
        /// <param name="operations">The operations.</param>
        /// <returns>The code.</returns>
        protected override IEnumerable <CodeArtifact> GenerateClientTypes(string controllerName,
                                                                          string controllerClassName, IEnumerable <CSharpOperationModel> operations)
        {
            var        cSharpOperationModels = operations as CSharpOperationModel[] ?? operations.ToArray();
            OpenApiTag tag         = null;
            var        currentPath = cSharpOperationModels.FirstOrDefault()?.Path;

            if (!string.IsNullOrWhiteSpace(currentPath))
            {
                var tagName = _document?.Operations?.FirstOrDefault(x => x.Path.EndsWith(currentPath))
                              ?.Operation?.Tags
                              ?.FirstOrDefault();
                tag = _document?.Tags.FirstOrDefault(x => x.Name == tagName);
            }

            var model = new CSharpRefitTemplateModel(controllerClassName, cSharpOperationModels, _document, Settings, tag);

            var template = Settings.CodeGeneratorSettings.TemplateFactory.CreateTemplate("CSharp", "Refit", model);
            var data     = new CodeArtifact(model.Class, CodeArtifactType.Class, CodeArtifactLanguage.CSharp,
                                            CodeArtifactCategory.Client, template);

            yield return(data);
        }
示例#26
0
        public static OpenApiTag LoadTag(ParseNode n)
        {
            var mapNode = n.CheckMapNode("tag");

            var obj = new OpenApiTag();

            foreach (var node in mapNode)
            {
                var key = node.Name;
                switch (key)
                {
                case "description":
                    obj.Description = node.Value.GetScalarValue();
                    break;

                case "name":
                    obj.Name = node.Value.GetScalarValue();
                    break;
                }
            }

            return(obj);
        }
示例#27
0
        /// <inheritdoc/>
        protected override void SetTags(OpenApiOperation operation)
        {
            if (IsNavigationPropertyPath)
            {
                base.SetTags(operation);
            }
            else
            {
                string tagIdentifier = EntitySet.Name + "." + EntitySet.EntityType().Name;

                OpenApiTag tag = new OpenApiTag
                {
                    Name = tagIdentifier
                };

                // Use an extension for TOC (Table of Content)
                tag.Extensions.Add(Constants.xMsTocType, new OpenApiString("page"));

                operation.Tags.Add(tag);

                Context.AppendTag(tag);
            }
        }
示例#28
0
        public OpenApiTagInjectingDocumentFilter(Assembly resourceAssembly, string resourceName, string documentRoute)
        {
            var manifestResourceName = $"{resourceAssembly.GetName().Name}.{resourceName}";
            var content      = LoadResourceFromAssembly(resourceAssembly, manifestResourceName);
            var deserializer = new DeserializerBuilder().WithNamingConvention(CamelCaseNamingConvention.Instance).Build();

            try
            {
                _tag = deserializer.Deserialize <OpenApiTag>(content);
            }
            catch (Exception e)
            {
                throw new InvalidDataException($"{resourceName}: {e.Message}");
            }

            if (_tag.Description.StartsWith("import:"))
            {
                manifestResourceName = $"{resourceAssembly.GetName().Name}.{_tag.Description.Substring(7).Trim()}";
                content          = LoadResourceFromAssembly(resourceAssembly, manifestResourceName);
                _tag.Description = content;
            }

            _documentRoute = documentRoute;
        }
示例#29
0
 /// <summary>
 /// Visits <see cref="OpenApiTag"/>
 /// </summary>
 public virtual void Visit(OpenApiTag tag)
 {
 }
示例#30
0
 /// <summary>
 /// Visits <see cref="OpenApiTag"/> and child objects
 /// </summary>
 /// <param name="tag"></param>
 internal void Walk(OpenApiTag tag)
 {
     _visitor.Visit(tag);
     _visitor.Visit(tag.ExternalDocs);
     _visitor.Visit(tag as IOpenApiExtensible);
 }