private static void AddCodeFixWithNewPublicConstructor(CodeFixContext context, SyntaxNode root,
      Diagnostic diagnostic, ClassDeclarationSyntax classNode)
    {
      // Generated from http://roslynquoter.azurewebsites.net/
      var constructor = SyntaxFactory.ConstructorDeclaration(classNode.Identifier)
        .WithModifiers(
          SyntaxFactory.TokenList(
            SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
        .WithParameterList(SyntaxFactory.ParameterList()
          .WithOpenParenToken(
            SyntaxFactory.Token(SyntaxKind.OpenParenToken))
          .WithCloseParenToken(
            SyntaxFactory.Token(
              SyntaxKind.CloseParenToken)))
        .WithBody(SyntaxFactory.Block()
          .WithOpenBraceToken(
            SyntaxFactory.Token(
              SyntaxKind.OpenBraceToken))
          .WithCloseBraceToken(
            SyntaxFactory.Token(
              SyntaxKind.CloseBraceToken))).NormalizeWhitespace().WithAdditionalAnnotations(Formatter.Annotation);
      var newClassNode = classNode.AddMembers(constructor);
      var newRoot = root.ReplaceNode(classNode, newClassNode);

      context.RegisterCodeFix(
        CodeAction.Create(
          CheckConstructorsAnalyzerPublicConstructorCodeFixConstants.AddPublicConstructorDescription,
          _ => Task.FromResult(context.Document.WithSyntaxRoot(newRoot)),
          CheckConstructorsAnalyzerPublicConstructorCodeFixConstants.AddPublicConstructorDescription), diagnostic);
    }
Пример #2
0
 public static ClassDeclarationSyntax AddField(ClassDeclarationSyntax classDeclaration, string type, string name)
 {
     return classDeclaration.AddMembers(
         SF.FieldDeclaration(SF.VariableDeclaration(SF.ParseTypeName(type),
         SF.SeparatedList(new[] { SF.VariableDeclarator(SF.Identifier(name)) })))
             .AddModifiers(SF.Token(SyntaxKind.PrivateKeyword)));
 }
Пример #3
0
        public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            TypeName = node.Identifier.ValueText;

            TypeSyntax clientContextInterface = SyntaxFactory.ParseTypeName(string.Format("I{0}ClientContext", _edmxName));
            var value =  node.AddMembers(
                SyntaxFactory.FieldDeclaration(
                    attributeLists: default(SyntaxList<AttributeListSyntax>),
                    modifiers: SyntaxFactory.TokenList(
                        SyntaxFactory.Token(SyntaxKind.PrivateKeyword)),
                    declaration: SyntaxFactory.VariableDeclaration(
                        clientContextInterface,
                        SyntaxFactory.SeparatedList(
                            new[] { SyntaxFactory.VariableDeclarator(
                                SyntaxFactory.Identifier("_context")) }))),
                SyntaxFactory.ConstructorDeclaration(SyntaxFactory.Identifier(node.Identifier.ValueText))
                    .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
                    .AddParameterListParameters(SyntaxFactory.Parameter(SyntaxFactory.Identifier("context")).WithType(clientContextInterface))
                    .WithInitializer(SyntaxFactory.ConstructorInitializer(
                        kind: SyntaxKind.BaseConstructorInitializer,
                        argumentList: SyntaxFactory.ArgumentList(
                            arguments: SyntaxFactory.SeparatedList(
                                new[] { SyntaxFactory.Argument(
                                    expression: SyntaxFactory.IdentifierName("context")) })))
                        .WithThisOrBaseKeyword(SyntaxFactory.Token(SyntaxKind.BaseKeyword)))
                    .WithBody(SyntaxFactory.Block(SyntaxFactory.ParseStatement("_context = context;"))))
                .AddBaseListTypes(SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName("ViewModelBase")));
            if (!value.Modifiers.Any(m => m.Kind() == SyntaxKind.PublicKeyword || m.Kind() == SyntaxKind.InternalKeyword))
                value = value.AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword));
            return value;
        }
Пример #4
0
        public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            var yieldClasses = new List<ClassDeclarationSyntax>();
            foreach (var method in node.Members.OfType<MemberDeclarationSyntax>().Where(j=>j is MethodDeclarationSyntax || j is PropertyDeclarationSyntax).Where(x => YieldChecker.HasYield(x)))
            {
                var yieldGenerator = new YieldClassGenerator(compilation, node, method);
                var enumerator = yieldGenerator.CreateEnumerator();
                yieldClasses.Add(enumerator);
            }

            if (yieldClasses.Any())
            {
                return node.AddMembers(yieldClasses.ToArray());
            }
            else
            {
                return base.VisitClassDeclaration(node);
            }
        }
        private async Task<Document> AddSuppDiagAsync(Document document, ClassDeclarationSyntax declaration, CancellationToken c)
        {
            SyntaxList<MemberDeclarationSyntax> members = declaration.Members;
            MethodDeclarationSyntax insertPoint = null;

            foreach (MemberDeclarationSyntax member in members)
            {
                insertPoint = member as MethodDeclarationSyntax;
                if (insertPoint == null || insertPoint.Identifier.Text != "Initialize")
                {
                    continue;
                }
                else
                {
                    break;
                }
            }

            SyntaxNode insertPointNode = insertPoint as SyntaxNode;

            SyntaxGenerator generator = SyntaxGenerator.GetGenerator(document);
            var semanticModel = await document.GetSemanticModelAsync();

            INamedTypeSymbol notImplementedException = semanticModel.Compilation.GetTypeByMetadataName("System.NotImplementedException");
            PropertyDeclarationSyntax propertyDeclaration = CodeFixNodeCreator.CreateSupportedDiagnostics(generator, notImplementedException);

            var newNodes = new SyntaxList<SyntaxNode>();
            newNodes = newNodes.Add(propertyDeclaration);

            var root = await document.GetSyntaxRootAsync();
            if (insertPoint != null)
            {
                var newRoot = root.InsertNodesBefore(insertPointNode, newNodes);
                var newDocument = document.WithSyntaxRoot(newRoot);
                return newDocument;
            }
            else
            {
                var newRoot = root.ReplaceNode(declaration, declaration.AddMembers(propertyDeclaration));
                var newDocument = document.WithSyntaxRoot(newRoot);
                return newDocument;
            }
        }
        private async Task<Document> AddRuleAsync(Document document, ClassDeclarationSyntax declaration, CancellationToken c)
        {
            SyntaxGenerator generator = SyntaxGenerator.GetGenerator(document);

            SyntaxList<MemberDeclarationSyntax> members = declaration.Members;
            PropertyDeclarationSyntax insertPoint = null;

            foreach (MemberDeclarationSyntax member in members)
            {
                insertPoint = member as PropertyDeclarationSyntax;
                if (insertPoint == null || insertPoint.Identifier.Text != "SupportedDiagnostics")
                {
                    insertPoint = null;
                    continue;
                }
                else
                {
                    break;
                }
            }

            SyntaxNode insertPointNode = insertPoint as SyntaxNode;

            FieldDeclarationSyntax fieldDeclaration = CodeFixNodeCreator.CreateEmptyRule(generator);

            var newNode = new SyntaxList<SyntaxNode>();
            newNode = newNode.Add(fieldDeclaration.WithLeadingTrivia(SyntaxFactory.TriviaList(SyntaxFactory.Whitespace("        "), SyntaxFactory.ParseLeadingTrivia("// If the analyzer finds an issue, it will report the DiagnosticDescriptor rule").ElementAt(0), SyntaxFactory.EndOfLine("\r\n"), SyntaxFactory.Whitespace("        "))));

            var root = await document.GetSyntaxRootAsync();
            if (insertPointNode != null)
            {
                var newRoot = root.InsertNodesBefore(insertPointNode, newNode);
                var newDocument = document.WithSyntaxRoot(newRoot);
                return newDocument;
            }
            else
            {
                var newRoot = root.ReplaceNode(declaration, declaration.AddMembers(fieldDeclaration.WithLeadingTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ParseLeadingTrivia("// If the analyzer finds an issue, it will report the DiagnosticDescriptor rule").ElementAt(0), SyntaxFactory.EndOfLine("\r\n")))));
                var newDocument = document.WithSyntaxRoot(newRoot);
                return newDocument;
            }
        }
		private ClassDeclarationSyntax addType(PropertyWithName p, ClassDeclarationSyntax @class)
		{
			var tn = ParseTypeName(p.PropertyName);
			var pi = p.Type.GetProperties();
			var method = createGetMethod(p.Type, pi)
				.WithLeadingTrivia(Trivia(RegionDirectiveTrivia(true)
					.WithEndOfDirectiveToken(
						Token(TriviaList().Add(PreprocessingMessage(p.PropertyName)),
							SyntaxKind.EndOfDirectiveToken,
							TriviaList())
					)
				));

			method = method.WithTrailingTrivia(
				Trivia(
					EndRegionDirectiveTrivia(true)
				)
			);

			return @class.AddMembers(method);
		}
Пример #8
0
        private static ClassDeclarationSyntax DecorateClassWithWrapperFunction(MethodDeclarationSyntax methodDeclaration,
            IdentifierNameSyntax invokeMethodIdentifier,
            ClassDeclarationSyntax classDeclaration)
        {
            if (classDeclaration.Members
                .OfType<MethodDeclarationSyntax>()
                .Any(x => x.Identifier.Text == invokeMethodIdentifier.Identifier.Text))
            {
                return classDeclaration;
            }

            var dllImport = methodDeclaration.AttributeLists
                .First(x => x.OpenBracketToken.HasLeadingTrivia);
            var arguments = methodDeclaration.ParameterList
                .Parameters
                .Select((x, i) =>
                {
                    var identifierName = SyntaxFactory.Argument(
                        null,
                        x.Modifiers
                            .FirstOrDefault(z => z.IsKind(SyntaxKind.RefKeyword) || z.IsKind(SyntaxKind.OutKeyword))
                            .WithLeadingTrivia(),
                        SyntaxFactory.IdentifierName(x.Identifier));
                    if (i > 0)
                    {
                        identifierName = identifierName.WithLeadingTrivia(WhitespaceCharacter);
                    }

                    return identifierName;
                });

            var arrowBody = SyntaxFactory.ArrowExpressionClause(
                SyntaxFactory.Token(SyntaxKind.EqualsGreaterThanToken)
                    .WithLeadingTrivia(
                        NewLineCharacter,
                        TabCharacter,
                        TabCharacter,
                        TabCharacter)
                    .WithTrailingTrivia(WhitespaceCharacter),
                SyntaxFactory.InvocationExpression(
                    SyntaxFactory.IdentifierName(methodDeclaration.Identifier),
                    SyntaxFactory.ArgumentList(
                        SyntaxFactory.SeparatedList(arguments))));

            var wrapperMethodDeclaration = SyntaxFactory.MethodDeclaration(
                SyntaxFactory.List(new[] {
                    GetCompilerGeneratedAttribute()
                        .WithTrailingTrivia(
                            NewLineCharacter,
                            TabCharacter,
                            TabCharacter)
                }),
                GetModifiersForWrapperFunction(methodDeclaration)
                    .Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword)
                        .WithTrailingTrivia(WhitespaceCharacter)),
                methodDeclaration.ReturnType,
                default(ExplicitInterfaceSpecifierSyntax),
                invokeMethodIdentifier.Identifier,
                methodDeclaration.TypeParameterList,
                methodDeclaration.ParameterList,
                methodDeclaration.ConstraintClauses,
                default(BlockSyntax),
                arrowBody,
                SyntaxFactory.Token(SyntaxKind.SemicolonToken));

            classDeclaration = classDeclaration
                .AddMembers(
                    wrapperMethodDeclaration
                        .WithTrailingTrivia(
                            NewLineCharacter,
                            TabCharacter)
                        .WithLeadingTrivia(dllImport.OpenBracketToken.LeadingTrivia));
            return classDeclaration;
        }
Пример #9
0
		private ClassDeclarationSyntax addType(PropertyWithName pwn, ClassDeclarationSyntax @class)
		{
			var tn = ParseTypeName(pwn.Type.Name);
			var pi = pwn.Type.GetProperties();

			var method = createGetMethod(pwn.Type, pi)
				.WithLeadingTrivia(Trivia(RegionDirectiveTrivia(true)
					.WithEndOfDirectiveToken(
						Token(TriviaList().Add(PreprocessingMessage(pwn.Type.Name)),
							SyntaxKind.EndOfDirectiveToken,
							TriviaList())
					)
				));

			method = method.WithTrailingTrivia(
				Trivia(
					EndRegionDirectiveTrivia(true)
				)
				);

			return @class.AddMembers(method);

			/*cu.NormalizeWhitespace("\t", true).WriteTo(writer);
			writer.WriteLine();
			writer.WriteLine();*/

		}
Пример #10
0
        private void FinalizeSyntax()
        {
            // Dispose method handling
            var disposeFound = false;
            // For empty dispose we dont want to merge it really
            for (var i = 0; i < m_methodDeclarations.Count; i++)
            {
                if (m_methodDeclarations[i].Identifier.ToString() == m_disposeMethod.Identifier.ToString())
                {
                    // Dont add empty body to the already created one
                    if(m_disposeMethod.Body.Statements.Count > 0)
                    {
                        m_methodDeclarations[i] = m_methodDeclarations[i].AddBodyStatements(m_disposeMethod.Body);
                    }
                    disposeFound = true;
                    break;
                }
            }

            if(!disposeFound)
                m_methodDeclarations.Add(m_disposeMethod);

            AddMissingInterfaceMethods();

            // if the interface type is objective logic script we need to hack in the rest of the interface methods
            if(m_baseType == typeof(IMyStateMachineScript))
                AddMissionLogicScriptMethods();

            m_scriptClassDeclaration = m_scriptClassDeclaration.AddMembers(m_fieldDeclarations.ToArray());
            m_scriptClassDeclaration = m_scriptClassDeclaration.AddMembers(m_constructor);
            m_scriptClassDeclaration = m_scriptClassDeclaration.AddMembers(m_methodDeclarations.ToArray());

            m_namespaceDeclaration = m_namespaceDeclaration.AddMembers(m_scriptClassDeclaration);

            var usings = new List<UsingDirectiveSyntax>();
            var usingsUniqueSet = new HashSet<string>();
            var defaultUsing = MySyntaxFactory.UsingStatementSyntax("VRage.Game.VisualScripting");
            usings.Add(defaultUsing);
            usingsUniqueSet.Add(defaultUsing.ToFullString());

            foreach (var node in m_navigator.OfType<MyVisualSyntaxFunctionNode>())
            {
                if(usingsUniqueSet.Add(node.Using.ToFullString()))
                    usings.Add(node.Using);
            }

            foreach (var node in m_navigator.OfType<MyVisualSyntaxVariableNode>())
            {
                if (usingsUniqueSet.Add(node.Using.ToFullString()))
                    usings.Add(node.Using);
            }


            m_compilationUnit = SyntaxFactory.CompilationUnit().WithUsings(SyntaxFactory.List(
                usings
                )).AddMembers(m_namespaceDeclaration).NormalizeWhitespace();
        }
Пример #11
0
        private static ClassDeclarationSyntax AddClass(ClassDeclarationSyntax baseClass, string name, Property[] properties, Configuration config)
        {
            if (name.Equals("object", StringComparison.OrdinalIgnoreCase))
            {
                return baseClass;
            }

            var className = ClassNameNormaliser(name);

            var @class = SyntaxFactory.ClassDeclaration(className)
                .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.PartialKeyword));

            if (config.AddRefactoringEssentialsPartialClassSupression)
            {
                @class = @class.AddAttributeLists(SyntaxFactory.AttributeList(SyntaxFactory.SeparatedList(new[] {
                    SyntaxFactory.Attribute(SyntaxFactory.ParseName("System.Diagnostics.CodeAnalysis.SuppressMessage"))
                    .AddArgumentListArguments(SyntaxFactory.AttributeArgument(SyntaxFactory.ParseExpression("\"\"")),
                                              SyntaxFactory.AttributeArgument(SyntaxFactory.ParseExpression("\"RECS0001:Class is declared partial but has only one part\"")),
                                              SyntaxFactory.AttributeArgument(SyntaxFactory.ParseExpression("Justification = \"This is partial to allow the file to extended in a seperate file if needed. Changes to this file would be lost when the code is regenerated and so supporting a seperate file for this is ideal.\"")))
                })));
            }

            if (properties != null)
            {
                foreach (var property in properties)
                {
                    var propertyType = "";
                    if (!string.IsNullOrWhiteSpace(property.Type))
                    {
                        switch (property.Type.ToUpperInvariant())
                        {
                            case "ARRAY":
                                {
                                    var arrayClass = property.ArrayItemType;
                                    if (arrayClass.StartsWith("#/definitions", StringComparison.OrdinalIgnoreCase))
                                    {
                                        arrayClass = RefToClass(arrayClass);
                                    }
                                    else
                                    {
                                        arrayClass = JsonSchemaToDotNetType(className, property.Name, property);
                                    }

                                    propertyType = arrayClass + "[]";
                                    break;
                                }
                            case "STRING":
                                {
                                    propertyType = JsonSchemaToDotNetType(className, property.Name, property);
                                    if (IsJsonSchemaEnum(property))
                                    {
                                        @class = AddEnum(@class, propertyType, property.Enum);
                                    }

                                    break;
                                }
                            default:
                                {
                                    propertyType = JsonSchemaToDotNetType(className, property.Name, property);
                                    break;
                                }
                        }
                    }
                    else
                    {
                        propertyType = RefToClass(property.Ref);
                    }

                    @class = @class.AddMembers(Property(property.Name, propertyType));
                }
            }

            return baseClass.AddMembers(@class);
        }
Пример #12
0
        private static ClassDeclarationSyntax AddOperation(ClassDeclarationSyntax @class, OperationConfig config, Configuration swaggerConfig)
        {
            if (config.Operation == null)
            {
                return @class;
            }

            var responseClass = "object";
            var authedCall = false;
            var hasBodyParam = false;
            var parameters = new List<SimplifiedParameter>();
            if (config.Operation.Security?[0].Name?.Equals("oauth", StringComparison.OrdinalIgnoreCase) != null)
            {
                authedCall = true;
                parameters.Add(new SimplifiedParameter
                {
                    Name = "oauthToken",
                    Type = "string",
                    Required = true
                });
            }

            var operationName = config.Operation.OperationId;
            if (string.IsNullOrWhiteSpace(operationName))
            {
                var end = config.Path.IndexOf("/", 2, StringComparison.OrdinalIgnoreCase) - 1;
                if (end < 0)
                {
                    end = config.Path.Length - 1;
                }

                operationName = config.HTTPAction + config.Path.Substring(1, end);
            }

            var methodName = $"{operationName.Replace(" ", "").Trim()}Async";

            if (config.Operation.Parameters != null)
            {
                foreach (var @param in config.Operation.Parameters)
                {
                    var name = @param.Name;
                    var type = "";
                    var typeFormat = "";
                    var @default = "";
                    if (@param.GetType() == typeof(BodyParameter))
                    {
                        hasBodyParam = true;
                        var bodyParam = @param as BodyParameter;
                        if (!string.IsNullOrWhiteSpace(bodyParam.Schema.Ref))
                        {
                            type = RefToClass(bodyParam.Schema.Ref);
                        }
                        else
                        {
                            type = bodyParam.Schema.Type;
                            typeFormat = bodyParam.Schema.Format;
                        }

                        @default = bodyParam.Schema.Default;
                    }
                    else
                    {
                        var otherParam = @param as OtherParameter;
                        type = otherParam.Type;
                        typeFormat = otherParam.Format;
                        @default = otherParam.Default;
                    }

                    if (!string.IsNullOrWhiteSpace(name))
                    {
                        parameters.Add(new SimplifiedParameter
                        {
                            Default = @default,
                            Name = name,
                            Type = type.Equals("array", StringComparison.OrdinalIgnoreCase) ? "object[]" : JsonSchemaToDotNetType(type, typeFormat),
                            Location = @param.In,
                            Description = @param.Description,
                            Required = @param.Required
                        });
                    }
                }
            }

            var successResponse = config.Operation.Responses.Where(_ => _.HttpStatusCode >= 200 && _.HttpStatusCode <= 299).OrderBy(_ => _.HttpStatusCode).FirstOrDefault();
            if (successResponse == null)
            {
                return @class;
            }

            if (successResponse.Schema != null)
            {
                if (!string.IsNullOrWhiteSpace(successResponse.Schema.Ref))
                {
                    responseClass = RefToClass(successResponse.Schema.Ref);
                }
                else
                {
                    switch (successResponse.Schema.Type.ToUpperInvariant())
                    {
                        case "OBJECT":
                            {
                                responseClass = ClassNameNormaliser($"{operationName}Out");
                                @class = AddClass(@class, responseClass, successResponse.Schema.Properties, swaggerConfig);
                                break;
                            }
                        case "ARRAY":
                            {
                                var arrayClass = successResponse.Schema.Items[0];
                                var resultClass = "";
                                if (arrayClass.Ref.StartsWith("#/definitions", StringComparison.OrdinalIgnoreCase))
                                {
                                    resultClass = RefToClass(arrayClass.Ref);
                                }
                                else
                                {
                                    resultClass = JsonSchemaToDotNetType(operationName, "Out", arrayClass);
                                }

                                responseClass = resultClass + "[]";
                                break;
                            }
                        default:
                            {
                                responseClass = ClassNameNormaliser(successResponse.Schema.Type);
                                break;
                            }
                    }
                }
            }

            responseClass = ClassNameNormaliser(responseClass);

            var method = SyntaxFactory.MethodDeclaration(SyntaxFactory.ParseTypeName($"Task<APIResponse<{responseClass}>>"), methodName)
                .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.AsyncKeyword));

            if (parameters.Count > 0)
            {
                method = method.AddParameterListParameters(parameters.Select(_ => Parameter(_)).ToArray());
            }

            var httpMethod = "await ";
            switch (config.HTTPAction)
            {
                case HTTPAction.Put:
                    {
                        httpMethod += "httpClient.PutAsync";
                        break;
                    }
                case HTTPAction.Get:
                    {
                        httpMethod += "httpClient.GetAsync";
                        break;
                    }
                case HTTPAction.Post:
                    {
                        httpMethod += "httpClient.PostAsync";
                        break;
                    }
                case HTTPAction.Delete:
                    {
                        httpMethod += "httpClient.DeleteAsync";
                        break;
                    }
                case HTTPAction.Head:
                    {
                        httpMethod += "httpClient.HeadAsync";
                        break;
                    }
                case HTTPAction.Options:
                    {
                        httpMethod += "httpClient.OptionsAsync";
                        break;
                    }
                case HTTPAction.Patch:
                    {
                        httpMethod += "httpClient.PatchAsync";
                        break;
                    }
            }

            var urlPath = config.Path;
            var queryParameterCode = "";
            var addQueryParameterCode = false;
            if (parameters != null)
            {
                var operationParameters = parameters.Where(_ => _.Location != null && (_.Location.Equals("PATH", StringComparison.OrdinalIgnoreCase) || _.Location.Equals("QUERY", StringComparison.OrdinalIgnoreCase))).ToArray();
                if (operationParameters.Any())
                {
                    queryParameterCode = $"var queryParameters = new Dictionary<string,object>({operationParameters.Length});";
                    foreach (var urlParam in operationParameters)
                    {
                        var target = $"{{{urlParam.Name}}}";
                        var value = $"\"+{urlParam.Name}+\"";
                        if (urlPath.Contains(target))
                        {
                            urlPath = urlPath.Replace(target, value);
                        }
                        else
                        {
                            addQueryParameterCode = true;

                            if (urlParam.Nullable)
                            {
                                queryParameterCode += $"if ({urlParam.Name}.HasValue) {{";
                                queryParameterCode += $"queryParameters.Add(\"{urlParam.Name}\", {urlParam.Name}.Value);";
                                queryParameterCode += "}";
                            }
                            else
                            {
                                queryParameterCode += $"queryParameters.Add(\"{urlParam.Name}\",{urlParam.Name});";
                            }
                        }
                    }
                }
            }

            var querySuffix = "";
            if (addQueryParameterCode)
            {
                querySuffix = "+\"?\" + queryParameters.Aggregate(\"\", (curr, next) => (curr.Length > 0 ? \"?\" : \"\") + next.Key + \"=\" + next.Value)";
            }

            httpMethod += $"(new Uri(url + \"{urlPath}\"{querySuffix}, UriKind.Absolute), new SwaggerHTTPClientOptions(TimeSpan.FromSeconds({swaggerConfig.HTTPTimeout.TotalSeconds}))";
            if (hasBodyParam)
            {
                var bodyParam = parameters.SingleOrDefault(_ => _.Location != null && (_.Location.Equals("body", StringComparison.OrdinalIgnoreCase)));
                if (bodyParam != null)
                {
                    httpMethod += $", new StringContent(JsonConvert.SerializeObject({bodyParam.Name}))";
                }

                var formDataParams = parameters.Where(_ => _.Location != null && (_.Location.Equals("formdata", StringComparison.OrdinalIgnoreCase)));
                if (formDataParams.Any())
                {
                    var formDataValue = formDataParams.Aggregate("", (curr, next) => curr + (curr.Length > 0 ? ", " : "") + next.Name);
                    httpMethod += $@", new StringContent(JsonConvert.SerializeObject(new {{{formDataValue}}}))";
                }
            }

            if (authedCall)
            {
                httpMethod += ", token: oauthToken";
            }

            httpMethod += ");";

            var methodBody = $@"
{{
{(addQueryParameterCode ? queryParameterCode : "")}
var response = {httpMethod}
if (response == null)
{{
return new APIResponse<{responseClass}>(false);
}}

 switch ((int)response.StatusCode)
 {{";

            var successId = config.Operation.Responses.First(_ => _.HttpStatusCode >= 200 && _.HttpStatusCode <= 299).HttpStatusCode;
            foreach (var response in config.Operation.Responses)
            {
                methodBody += $@"case {response.HttpStatusCode}:
{{
";
                if (response.HttpStatusCode == successId)
                {
                    if (response.Schema == null || response.Schema.Type == "object")
                    {
                        methodBody += $"return new APIResponse<{responseClass}>(response.StatusCode);";
                    }
                    else
                    {
                        methodBody += $@"var data = JsonConvert.DeserializeObject<{responseClass}>(await response.Content.ReadAsStringAsync());
return new APIResponse<{responseClass}>(data, response.StatusCode);";
                    }
                }
                else
                {
                    if (response.Schema == null || response.Schema.Type == "object")
                    {
                        methodBody += $"return new APIResponse<{responseClass}>(response.StatusCode);";
                    }
                    else
                    {
                        var specialData = string.IsNullOrWhiteSpace(response.Schema.Type) ? RefToClass(response.Schema.Ref) : ClassNameNormaliser(response.Schema.Type);
                        methodBody += $@"var data = JsonConvert.DeserializeObject<{ClassNameNormaliser(specialData)}>(await response.Content.ReadAsStringAsync());
return new APIResponse<{responseClass}>(data, response.StatusCode);";
                    }
                }

                methodBody += "}";
            }

            methodBody += $@"default:
         {{
             return new APIResponse<{responseClass}>(response.StatusCode);
         }}
 }}
}}";

            var xmlComments = new List<SyntaxTrivia>();

            if (!string.IsNullOrWhiteSpace(config.Operation.Summary))
            {
                xmlComments.AddRange(AddXmlComment("summary", CleanXMLComment(config.Operation.Summary)));
            }

            if (!string.IsNullOrWhiteSpace(config.Operation.Description))
            {
                xmlComments.AddRange(AddXmlComment("remarks", CleanXMLComment(config.Operation.Description)));
            }

            if (!string.IsNullOrWhiteSpace(successResponse.Description))
            {
                xmlComments.AddRange(AddXmlComment("returns", CleanXMLComment(successResponse.Description)));
            }

            xmlComments.AddRange(parameters.Select(_ => AddXmlParamComment(_.Name, _.Description)));
            method = method
                .AddBodyStatements(SyntaxFactory.ParseStatement(methodBody))
                .WithLeadingTrivia(SyntaxExtensions.ToSyntaxTriviaList(xmlComments));

            return @class.AddMembers(method);
        }
Пример #13
0
        private static ClassDeclarationSyntax AddEnum(ClassDeclarationSyntax @class, string enumName, string[] enumValues)
        {
            var @enum = SyntaxFactory.EnumDeclaration(enumName)
                .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
                .AddMembers(enumValues.Select(_ => SyntaxFactory.EnumMemberDeclaration(_)).ToArray());

            return @class.AddMembers(@enum);
        }
Пример #14
0
		internal static ClassDeclarationSyntax GetCollectible(ClassDeclarationSyntax classDecl)
		{
			foreach(var c in ClassNames)
			{
				var anyCards = false;
				var className = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(c.ToLower());
				var cCard = ClassDeclaration(className).AddModifiers(Token(PublicKeyword));
				foreach(var card in
					Cards.All.Values.Where(x => x.Collectible && x.Class.ToString().Equals(c)))
				{
					var name = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(card.Name.ToLower());
					name = Regex.Replace(name, @"[^\w\d]", "");
					cCard = cCard.AddMembers(GenerateConst(name, card.Id));
					anyCards = true;
				}
				if(anyCards)
					classDecl = classDecl.AddMembers(cCard);
			}
			return classDecl;
		}
Пример #15
0
        //public SemanticModel Model { get; private set; }
        public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            node = (ClassDeclarationSyntax)base.VisitClassDeclaration(node);
            MethodDeclarationSyntax prector = SyntaxFactory.MethodDeclaration(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), ".prector");
            MethodDeclarationSyntax precctor = SyntaxFactory.MethodDeclaration(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), ".precctor");
            precctor = precctor.AddModifiers(SyntaxFactory.Token(SyntaxKind.StaticKeyword));

            List<StatementSyntax> Initializers = new List<StatementSyntax>();
            List<StatementSyntax> StaticInitializers = new List<StatementSyntax>();
            foreach (MemberDeclarationSyntax member in node.Members)
            {
                if (member.CSharpKind() == SyntaxKind.FieldDeclaration)
                {
                    FieldDeclarationSyntax fds = (FieldDeclarationSyntax)member;

                    foreach (VariableDeclaratorSyntax vds in fds.Declaration.Variables)
                    {
                        if (vds.Initializer != null)
                        {
                            if (fds.Modifiers.ToString().Contains("static"))
                            {
                                StaticInitializers.Add(SyntaxFactory.ExpressionStatement(SyntaxFactory.BinaryExpression(SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName(vds.Identifier), vds.Initializer.Value)));
                            }
                            else
                            {
                                Initializers.Add(SyntaxFactory.ExpressionStatement(SyntaxFactory.BinaryExpression(SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName(vds.Identifier), vds.Initializer.Value)));
                            }
                        }
                    }
                }
            }

            if (Initializers.Count == 0 && StaticInitializers.Count == 0)
                return node;
            SyntaxList<MemberDeclarationSyntax> newMembers = new SyntaxList<MemberDeclarationSyntax>();

            if (Initializers.Count > 0)
            {
                int constructors = node.Members.Count((m) => (m is ConstructorDeclarationSyntax && !((ConstructorDeclarationSyntax)m).Modifiers.ToString().Contains("static")));

                prector = prector.AddBodyStatements(Initializers.ToArray());
                node = node.AddMembers(prector);

                if (constructors == 0)
                {
                    ConstructorDeclarationSyntax ctor = SyntaxFactory.ConstructorDeclaration(node.Identifier);
                    ctor = ctor.AddBodyStatements(SyntaxFactory.ExpressionStatement(SyntaxFactory.InvocationExpression(SyntaxFactory.IdentifierName(".prector"))));
                    ctor = ctor.AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword));

                    newMembers = newMembers.Add(ctor);
                }
               // else
                {

                    foreach (MemberDeclarationSyntax member in node.Members)
                    {
                        if (member.CSharpKind() == SyntaxKind.ConstructorDeclaration && !((ConstructorDeclarationSyntax)member).Modifiers.ToString().Contains("static"))
                        {
                            newMembers = newMembers.Add((MemberDeclarationSyntax)ConstructorPrefixerDeclaration((ConstructorDeclarationSyntax)member));
                        }
                        else
                        {
                            newMembers = newMembers.Add(member);
                        }
                    }
                }
            }
            if (StaticInitializers.Count > 0)
            {
                int constructors = node.Members.Count((m) => (m is ConstructorDeclarationSyntax && ((ConstructorDeclarationSyntax)m).Modifiers.ToString().Contains("static")));

                precctor = precctor.AddBodyStatements(StaticInitializers.ToArray());
                node = node.AddMembers(precctor);

                if (constructors == 0)
                {
                    ConstructorDeclarationSyntax ctor = SyntaxFactory.ConstructorDeclaration(node.Identifier);
                    ctor = ctor.AddModifiers(SyntaxFactory.Token(SyntaxKind.StaticKeyword));
                    ctor = ctor.AddBodyStatements(SyntaxFactory.ExpressionStatement(SyntaxFactory.InvocationExpression(SyntaxFactory.IdentifierName(".precctor"))));
                    ctor = ctor.AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword));

                    newMembers = newMembers.Add(ctor);
                }
                //else
                {

                    foreach (MemberDeclarationSyntax member in node.Members)
                    {
                        if (member.CSharpKind() == SyntaxKind.ConstructorDeclaration && ((ConstructorDeclarationSyntax)member).Modifiers.ToString().Contains("static"))
                        {
                            newMembers = newMembers.Add((MemberDeclarationSyntax)StaticConstructorPrefixerDeclaration((ConstructorDeclarationSyntax)member));
                        }
                        else
                        {
                            newMembers = newMembers.Add(member);
                        }
                    }
                }
            }

            return node.WithMembers(newMembers);
        }
Пример #16
0
        /// <summary>
        /// creates a new class declaration where members are delegated to the mixin
        /// reference
        /// </summary>
        /// <param name="classDeclaration"></param>
        /// <returns></returns>
        public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax classDeclaration)
        {
            var mixinName = _mixin.Name;
            // currently, only three types of member forwardings are possible,
            // there is a strategy for every forwarding implementation
            var implementationStrategies = CreateStrategies(_mixin, _semantic, _settings);
            // needed to evaluate whether type names can be reduced (depends on the using statements in the file)
            var positionOfClassInSourceFile = classDeclaration.GetLocation().SourceSpan.Start;
           
            // generate the members that should be implemented            
            var membersToAdd = _members
                .Select(x => implementationStrategies[x.GetType()].ImplementMember(x, positionOfClassInSourceFile))
                .Where(x => x != null).ToArray();

            // add regions if there is something to generate
            if (_settings.CreateRegions)
            {
                var regionCaption = $" mixin {mixinName}";
                // if there is already a region, add members to this one,
                // otherwise create a new one
                if (classDeclaration.HasRegion(regionCaption))
                    return classDeclaration.AddMembersIntoRegion(regionCaption, membersToAdd);
                else
                    membersToAdd.AddRegionAround(regionCaption);
            }

            // return a new class node with the additional members
            // problem with AddMembers is that it adds the new code
            // after the last syntax node, so when a region exists in the class
            // the code will be added before the region end, this leads to the bug
            // https://github.com/pgenfer/mixinSharp/issues/9
            // where the newly created region is nested into the old one.
            // a solution is to ensure that the members are added after any endregion directive

            // check if there is an end region in the file
            var lastEndRegion = classDeclaration.GetLastElementInClass<EndRegionDirectiveTriviaSyntax>();
            // only interesting if there is an end region directive at all
            if(lastEndRegion != null)
            {
                var lastSyntaxNode = classDeclaration.GetLastElementInClass<SyntaxNode>(false);
                if (lastSyntaxNode != lastEndRegion && lastSyntaxNode.SpanStart < lastEndRegion.Span.End)
                {
                    // special case here: there is an end region directive at the end of the class
                    // so we must add our members AFTER this endregion (by removing it and adding it before the first member)
                    if (membersToAdd.Length > 0)
                    {
                        var newClassDeclaration = classDeclaration.RemoveNode(lastEndRegion, SyntaxRemoveOptions.AddElasticMarker);
                        membersToAdd[0] = membersToAdd[0].WithLeadingTrivia(
                            new SyntaxTriviaList()
                            .Add(Trivia(EndRegionDirectiveTrivia(true)))
                            .Add(EndOfLine(NewLine))
                            .AddRange(membersToAdd[0].GetLeadingTrivia()));
                        return newClassDeclaration.AddMembers(membersToAdd);
                    }
                }
            }

            return classDeclaration.AddMembers(membersToAdd);
        }