Esempio n. 1
0
    public static PropertyDeclarationSyntax CreateListAuto(
        string dataType,
        string propertyName,
        bool initializeList = true)
    {
        var propertyDeclaration = SyntaxFactory.PropertyDeclaration(
            SyntaxFactory.GenericName(SyntaxFactory.Identifier(Microsoft.OpenApi.Models.NameConstants.List))
            .WithTypeArgumentList(SyntaxTypeArgumentListFactory.CreateWithOneItem(dataType)),
            SyntaxFactory.Identifier(propertyName))
                                  .AddModifiers(SyntaxTokenFactory.PublicKeyword())
                                  .WithAccessorList(
            SyntaxFactory.AccessorList(
                SyntaxFactory.List(
                    new[]
        {
            SyntaxAccessorDeclarationFactory.Get(),
            SyntaxAccessorDeclarationFactory.Set(),
        })));

        if (initializeList)
        {
            propertyDeclaration = propertyDeclaration.WithInitializer(
                SyntaxFactory.EqualsValueClause(
                    SyntaxFactory.ObjectCreationExpression(
                        SyntaxFactory.GenericName(SyntaxFactory.Identifier(Microsoft.OpenApi.Models.NameConstants.List))
                        .WithTypeArgumentList(SyntaxTypeArgumentListFactory.CreateWithOneItem(dataType)))
                    .WithArgumentList(
                        SyntaxFactory.ArgumentList())))
                                  .WithSemicolonToken(SyntaxTokenFactory.Semicolon());
        }

        return(propertyDeclaration);
    }
 private MemberDeclarationSyntax CreateConstructor()
 => SyntaxFactory.ConstructorDeclaration(
     SyntaxFactory.Identifier(EndpointTypeName))
 .WithModifiers(
     SyntaxFactory.TokenList(
         SyntaxTokenFactory.PublicKeyword()))
 .WithParameterList(
     SyntaxFactory.ParameterList(
         SyntaxFactory.SeparatedList <ParameterSyntax>(
             new SyntaxNodeOrToken[]
 {
     SyntaxFactory.Parameter(SyntaxFactory.Identifier("factory"))
     .WithType(SyntaxFactory.IdentifierName(nameof(IHttpClientFactory))),
     SyntaxTokenFactory.Comma(), SyntaxFactory
     .Parameter(SyntaxFactory.Identifier("httpMessageFactory"))
     .WithType(SyntaxFactory.IdentifierName(nameof(IHttpMessageFactory))),
 })))
 .WithBody(
     SyntaxFactory.Block(
         SyntaxFactory.ExpressionStatement(
             SyntaxFactory.AssignmentExpression(
                 SyntaxKind.SimpleAssignmentExpression,
                 SyntaxFactory.MemberAccessExpression(
                     SyntaxKind.SimpleMemberAccessExpression,
                     SyntaxFactory.ThisExpression(),
                     SyntaxFactory.IdentifierName("factory")),
                 SyntaxFactory.IdentifierName("factory"))),
         SyntaxFactory.ExpressionStatement(
             SyntaxFactory.AssignmentExpression(
                 SyntaxKind.SimpleAssignmentExpression,
                 SyntaxFactory.MemberAccessExpression(
                     SyntaxKind.SimpleMemberAccessExpression,
                     SyntaxFactory.ThisExpression(),
                     SyntaxFactory.IdentifierName("httpMessageFactory")),
                 SyntaxFactory.IdentifierName("httpMessageFactory")))));
Esempio n. 3
0
    private MethodDeclarationSyntax CreateMembersForEndpoints(
        KeyValuePair <OperationType, OpenApiOperation> apiOperation,
        string urlPath,
        string area,
        bool hasRouteParameters)
    {
        var operationName     = apiOperation.Value.GetOperationName();
        var interfaceName     = "I" + operationName + NameConstants.ContractHandler;
        var methodName        = operationName + "Async";
        var helperMethodName  = $"Invoke{operationName}Async";
        var parameterTypeName = operationName + NameConstants.ContractParameters;

        // Create method # use CreateParameterList & CreateCodeBlockReturnStatement
        var methodDeclaration = SyntaxFactory.MethodDeclaration(
            SyntaxFactory.GenericName(SyntaxFactory.Identifier(nameof(Task)))
            .WithTypeArgumentList(SyntaxTypeArgumentListFactory.CreateWithOneItem(nameof(ActionResult))),
            SyntaxFactory.Identifier(methodName))
                                .AddModifiers(SyntaxTokenFactory.PublicKeyword())
                                .WithParameterList(CreateParameterList(apiOperation.Value.HasParametersOrRequestBody() || hasRouteParameters, parameterTypeName, interfaceName, true))
                                .WithBody(
            SyntaxFactory.Block(
                SyntaxIfStatementFactory.CreateParameterArgumentNullCheck("handler", false),
                CreateCodeBlockReturnStatement(helperMethodName, apiOperation.Value.HasParametersOrRequestBody() || hasRouteParameters)));

        // Create and add Http-method-attribute
        var httpAttributeRoutePart = GetHttpAttributeRoutePart(urlPath);

        methodDeclaration = string.IsNullOrEmpty(httpAttributeRoutePart)
            ? methodDeclaration.AddAttributeLists(
            SyntaxAttributeListFactory.Create($"Http{apiOperation.Key}"))
            : methodDeclaration.AddAttributeLists(
            SyntaxAttributeListFactory.CreateWithOneItemWithOneArgument(
                $"Http{apiOperation.Key}",
                httpAttributeRoutePart));

        // Create and add RequestFormLimits-attribute
        if (apiOperation.Value.HasRequestBodyWithAnythingAsFormatTypeBinary())
        {
            methodDeclaration = methodDeclaration.AddAttributeLists(
                SyntaxAttributeListFactory.Create(
                    "RequestFormLimits(MultipartBodyLengthLimit = long.MaxValue)"));
        }

        // Create and add producesResponseTypes-attributes
        var producesResponseAttributeParts = apiOperation.Value.Responses.GetProducesResponseAttributeParts(
            OperationSchemaMappings,
            area,
            ApiProjectOptions.ProjectName,
            ApiProjectOptions.ApiOptions.Generator.Response.UseProblemDetailsAsDefaultBody,
            apiOperation.Value.HasParametersOrRequestBody(),
            includeIfNotDefinedAuthorization: false,
            includeIfNotDefinedInternalServerError: false);

        return(producesResponseAttributeParts
               .Aggregate(
                   methodDeclaration,
                   (current, producesResponseAttributePart) => current.AddAttributeLists(
                       SyntaxAttributeListFactory.Create(producesResponseAttributePart))));
    }
        public static PropertyDeclarationSyntax CreateAuto(string dataType, string propertyName)
        {
            var propertyDeclaration = SyntaxFactory
                                      .PropertyDeclaration(SyntaxFactory.ParseTypeName(dataType), propertyName)
                                      .AddModifiers(SyntaxTokenFactory.PublicKeyword())
                                      .AddAccessorListAccessors(
                SyntaxAccessorDeclarationFactory.Get(),
                SyntaxAccessorDeclarationFactory.Set());

            return(propertyDeclaration);
        }
    public static EnumDeclarationSyntax Create(
        string title,
        IList <IOpenApiAny> apiSchemaEnums)
    {
        ArgumentNullException.ThrowIfNull(title);
        ArgumentNullException.ThrowIfNull(apiSchemaEnums);

        // Create an enum
        var enumDeclaration = SyntaxFactory.EnumDeclaration(title)
                              .AddModifiers(SyntaxTokenFactory.PublicKeyword());

        // Find values to the enum
        var containTypeName = false;
        var lines           = new List <string>();
        var intValues       = new List <int>();

        foreach (var item in apiSchemaEnums)
        {
            if (item is not OpenApiString openApiString)
            {
                continue;
            }

            lines.Add(openApiString.Value.Trim());

            if (!openApiString.Value.Contains('=', StringComparison.Ordinal))
            {
                continue;
            }

            var sa = openApiString.Value.Split('=', StringSplitOptions.RemoveEmptyEntries);
            var s  = sa.Last().Trim();
            if (int.TryParse(s, NumberStyles.Integer, GlobalizationConstants.EnglishCultureInfo, out var val))
            {
                intValues.Add(val);
            }
        }

        // Add values to the enum
        foreach (var line in lines)
        {
            enumDeclaration = enumDeclaration.AddMembers(SyntaxFactory.EnumMemberDeclaration(line));

            var sa = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
            if (sa.Length > 0 &&
                sa.First().Equals("Object", StringComparison.Ordinal))
            {
                containTypeName = true;
            }
        }

        enumDeclaration = enumDeclaration
                          .AddSuppressMessageAttribute(CodeAnalysis.CSharp.Factories.SuppressMessageAttributeFactory.CreateStyleCopSuppression(1413, justification: null));

        // Add SuppressMessageAttribute
        if (containTypeName)
        {
            enumDeclaration = enumDeclaration
                              .AddSuppressMessageAttribute(CodeAnalysis.CSharp.Factories.SuppressMessageAttributeFactory.CreateCodeAnalysisSuppression(1720, justification: null));
        }

        // Add FlagAttribute
        if (intValues.Count > 0)
        {
            var isAllValidBinarySequence = intValues
                                           .Where(x => x != 0)
                                           .All(x => x.IsBinarySequence());
            if (isAllValidBinarySequence)
            {
                enumDeclaration = enumDeclaration.AddFlagAttribute();
            }
        }

        return(enumDeclaration);
    }
Esempio n. 6
0
        public static EnumDeclarationSyntax Create(string title, IList <IOpenApiAny> apiSchemaEnums)
        {
            if (title == null)
            {
                throw new ArgumentNullException(nameof(title));
            }

            if (apiSchemaEnums == null)
            {
                throw new ArgumentNullException(nameof(apiSchemaEnums));
            }

            // Create an enum
            var enumDeclaration = SyntaxFactory.EnumDeclaration(title)
                                  .AddModifiers(SyntaxTokenFactory.PublicKeyword());

            // Find values to the enum
            var containTypeName = false;
            var lines           = new List <string>();
            var intValues       = new List <int>();

            foreach (var item in apiSchemaEnums)
            {
                if (!(item is OpenApiString openApiString))
                {
                    continue;
                }

                lines.Add(openApiString.Value.Trim());

                if (!openApiString.Value.Contains("=", StringComparison.Ordinal))
                {
                    continue;
                }

                var sa = openApiString.Value.Split('=', StringSplitOptions.RemoveEmptyEntries);
                var s  = sa.Last().Trim();
                if (int.TryParse(s, out int val))
                {
                    intValues.Add(val);
                }
            }

            // Add values to the enum
            foreach (var line in lines)
            {
                enumDeclaration = enumDeclaration.AddMembers(SyntaxFactory.EnumMemberDeclaration(line));

                var sa = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
                if (sa.Length > 0 && sa.First().Equals("Object", StringComparison.Ordinal))
                {
                    containTypeName = true;
                }
            }

            // Add SuppressMessageAttribute
            if (containTypeName)
            {
                enumDeclaration = enumDeclaration
                                  .AddSuppressMessageAttribute(SuppressMessageAttributeFactory.Create(1720, null));
            }

            // Add FlagAttribute
            if (intValues.Count > 0)
            {
                bool isAllValidBinarySequence = intValues
                                                .Where(x => x != 0)
                                                .All(x => x.IsBinarySequence());
                if (isAllValidBinarySequence)
                {
                    enumDeclaration = enumDeclaration.AddFlagAttribute();
                }
            }

            return(enumDeclaration);
        }