Exemple #1
0
        /// <summary>
        /// Creates the proxy syntax tree
        /// </summary>
        /// <param name="interfaceType">Actor interface type</param>
        /// <param name="actorType">Actor type</param>
        /// <param name="actorMachineType">Actor machine type</param>
        /// <returns>SyntaxTree</returns>
        private SyntaxTree CreateProxySyntaxTree(Type interfaceType, Type actorType, Type actorMachineType)
        {
            ClassDeclarationSyntax proxyDecl = this.CreateProxyClassDeclaration(
                interfaceType, actorType, actorMachineType);

            NamespaceDeclarationSyntax namespaceDecl = SyntaxFactory.NamespaceDeclaration(
                SyntaxFactory.IdentifierName(actorType.Namespace + "_PSharpProxy"));

            var usingDirectives = new List <UsingDirectiveSyntax>
            {
                SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName("Microsoft.PSharp.Actors")),
                SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName("Microsoft.PSharp.Actors.Utilities"))
            };

            foreach (var requiredNamespace in this.RequiredNamespaces)
            {
                usingDirectives.Add(SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName(requiredNamespace)));
            }

            namespaceDecl = namespaceDecl.WithUsings(SyntaxFactory.List(usingDirectives))
                            .WithMembers(SyntaxFactory.List(
                                             new List <MemberDeclarationSyntax>
            {
                proxyDecl
            }));

            namespaceDecl = namespaceDecl.NormalizeWhitespace();

            return(namespaceDecl.SyntaxTree);
        }
Exemple #2
0
        public static void Main(string generatorName, FileInfo outputFile, string @namespace, string[] args = null)
        {
            string className = Path.GetFileName(outputFile.Name).Split('.')[0];

            Type codeGeneratorType = Assembly.GetExecutingAssembly().GetTypes().SingleOrDefault(t => t.Name == generatorName) ?? throw new ArgumentException($"Generator '{generatorName} not found");
            var  generator         = (ICodeGenerator)Activator.CreateInstance(codeGeneratorType, new object[] { args });

            (MemberDeclarationSyntax declaration, UsingDirectiveSyntax[] usingDirectives) = generator.Generate(className);

            NamespaceDeclarationSyntax namespaceDeclaration =
                NamespaceDeclaration(IdentifierName(@namespace))
                .AddUsings(usingDirectives)
                .WithMembers(SingletonList(declaration))
                .WithLeadingTrivia(
                    Comment("//------------------------------------------------------------------------------"),
                    Comment("// <auto-generated>"),
                    Comment("//     This code was generated by a tool."),
                    Comment("//"),
                    Comment("//     Changes to this file may cause incorrect behavior and will be lost if"),
                    Comment("//     the code is regenerated."),
                    Comment("// </auto-generated>"),
                    Comment("//------------------------------------------------------------------------------"));

            File.WriteAllText(outputFile.FullName, namespaceDeclaration.NormalizeWhitespace().SyntaxTree.ToString());
        }
Exemple #3
0
        public static void Main(string[] args)
        {
            if (args.Length != 3)
            {
                Console.WriteLine($"Usage: dotnet {typeof(Program).Assembly.GetName().Name}.dll <GeneratorName> <OutputFilePath> <NamespaceName>");
                Environment.Exit(1);
            }

            string generatorName = args[0];
            string outputFile    = args[1];
            string namespaceName = args[2];
            string className     = Path.GetFileName(outputFile).Split('.')[0];

            var generator = (ICodeGenerator)Activator.CreateInstance(Assembly.GetExecutingAssembly().GetTypes().SingleOrDefault(t => t.Name == generatorName) ?? throw new ArgumentException($"Generator '{generatorName} not found"));

            MemberDeclarationSyntax declaration = generator.Generate(className);

            NamespaceDeclarationSyntax namespaceDeclaration =
                NamespaceDeclaration(IdentifierName(namespaceName))
                .WithMembers(SingletonList(declaration))
                .WithLeadingTrivia(
                    Comment("//------------------------------------------------------------------------------"),
                    Comment("// <auto-generated>"),
                    Comment("//     This code was generated by a tool."),
                    Comment("//"),
                    Comment("//     Changes to this file may cause incorrect behavior and will be lost if"),
                    Comment("//     the code is regenerated."),
                    Comment("// </auto-generated>"),
                    Comment("//------------------------------------------------------------------------------"));

            File.WriteAllText(outputFile, namespaceDeclaration.NormalizeWhitespace().SyntaxTree.ToString());
        }
Exemple #4
0
        private void DownloadWSDL()
        {
            NamespaceDeclarationSyntax ns = NamespaceDeclaration(IdentifierName(nameSpace));

            DiscoveryClientDocument = DiscoveryClient.DiscoverAny(_endpointUri.ToString());

            DiscoveryClient.ResolveAll();
            DiscoveryContractReference = DiscoveryClientDocument.References[0] as ContractReference;

            var schemas = new XmlSchemaSet();

            foreach (DictionaryEntry entry in DiscoveryClient.References)
            {
                if (!(entry.Value is SchemaReference discoveryReference))
                {
                    continue;
                }

                foreach (XmlSchemaObject schemaObject in discoveryReference.Schema.Items)
                {
                    DiscoveryClientReferencesElements.Add(schemaObject);
                }

                schemas.Add(discoveryReference.Schema.TargetNamespace, discoveryReference.Ref);
            }

            var headers = DiscoveryContractReference.Contract.Messages["headers"];

            var ms     = new MemoryStream();
            var writer = new StringWriter();

            var generator = new Generator()
            {
                OutputWriter    = new GeneratorOutput(writer),
                CollectionType  = typeof(System.Collections.Generic.List <>),
                Log             = s => Console.Out.WriteLine(s),
                NamespacePrefix = nameSpace,
                NamingScheme    = NamingScheme.Direct,
                UniqueTypeNamesAcrossNamespaces = true,
                GenerateNullables     = true,
                CollectionSettersMode = CollectionSettersMode.PublicWithoutConstructorInitialization,
                EntityFramework       = true,
                TypeVisitor           = (type, model) =>
                {
                    if ((!type.IsClass) && !(type.IsInterface))
                    {
                        return;
                    }

                    foreach (CodeAttributeDeclaration attribute in type.CustomAttributes)
                    {
                        if (attribute.Name != "System.Xml.Serialization.XmlRootAttribute")
                        {
                            continue;
                        }

                        foreach (CodeAttributeArgument argument in attribute.Arguments)
                        {
                            if (argument.Name != "")
                            {
                                continue;
                            }

                            var partname = (argument.Value as CodePrimitiveExpression).Value.ToString();
                            try
                            {
                                headers.FindPartByName(partname);
                                type.BaseTypes.Add(new CodeTypeReference("SimpleSOAPClient.Models.SoapHeader"));

                                return;
                            }
                            catch { }
                        }
                    }
                }
            };

            generator.Generate(schemas);

            var tree = CSharpSyntaxTree.ParseText(writer.ToString());
            var root = tree.GetRoot();

            if (!(root is CompilationUnitSyntax compilationUnit))
            {
                throw new Exception("XmlSchemaClassGenerator did not produce a valid CSharp code file");
            }

            ns = compilationUnit.Members.First() as NamespaceDeclarationSyntax;

            if (ns == null)
            {
                throw new Exception("XmlSchemaClassGenerator did not produce a valid CSharp namespace as the first node");
            }

            DiscoveryContractReference.Contract.Types.Schemas.Compile(null, true);
            foreach (Binding binding in DiscoveryContractReference.Contract.Bindings)
            {
                var portClass = ClassDeclaration(string.Format("{0}Client", binding.Type.Name)).WithModifiers(TokenList(new[] { Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.PartialKeyword) }));

                foreach (OperationBinding operation in binding.Operations)
                {
                    var inputMessage  = DiscoveryContractReference.Contract.Messages[operation.Input.Name];
                    var outputMessage = DiscoveryContractReference.Contract.Messages[operation.Output.Name];

                    var inputPart  = inputMessage.FindPartByName("parameters");
                    var outputPart = outputMessage.FindPartByName("parameters");

                    var inputElement  = DiscoveryClientReferencesElements.Elements[inputPart.Element.Name];
                    var outputElement = DiscoveryClientReferencesElements.Elements[outputPart.Element.Name];

                    var inputType  = string.Format("{0}.{1}", nameSpace, inputElement.SchemaTypeName.Name);
                    var outputType = string.Format("{0}.{1}", nameSpace, outputElement.SchemaTypeName.Name);

                    var methodName      = QualifiedName(IdentifierName("System.Threading.Tasks"), GenericName(Identifier("Task")).WithTypeArgumentList(TypeArgumentList(SingletonSeparatedList <TypeSyntax>(ParseTypeName(GetAliasedType(outputType))))));
                    var operationMethod = MethodDeclaration(methodName, Identifier(operation.Name));

                    var headerCollectionDeclaration = VariableDeclaration(
                        ArrayType(IdentifierName("SimpleSOAPClient.Models.SoapHeader")).WithRankSpecifiers(
                            SingletonList <ArrayRankSpecifierSyntax>(
                                ArrayRankSpecifier(
                                    SingletonSeparatedList <ExpressionSyntax>(
                                        OmittedArraySizeExpression())))));

                    var headerVariable = VariableDeclarator(Identifier("headers"));

                    var headerArrayInitializer = InitializerExpression(SyntaxKind.ArrayInitializerExpression);

                    SyntaxList <StatementSyntax> bodyStatements = new SyntaxList <StatementSyntax>();

                    foreach (ServiceDescriptionFormatExtension extension in operation.Input.Extensions)
                    {
                        ParameterSyntax parameter;
                        if (extension is SoapHeaderBinding header)
                        {
                            var headerMessage = DiscoveryContractReference.Contract.Messages[header.Message.Name];
                            var headerPart    = headerMessage.FindPartByName(header.Part);
                            var headerElement = DiscoveryClientReferencesElements.Elements[headerPart.Element.Name];
                            var headerType    = string.Format("{0}.{1}", nameSpace, headerElement.SchemaTypeName.Name);
                            parameter = Parameter(Identifier(header.Part)).WithType(ParseTypeName(GetAliasedType(headerType)));

                            operationMethod        = operationMethod.AddParameterListParameters(parameter);
                            headerArrayInitializer = headerArrayInitializer.AddExpressions(IdentifierName(header.Part));
                        }
                        else if (extension is SoapBodyBinding body)
                        {
                            parameter = Parameter(Identifier("request")).WithType(ParseTypeName(GetAliasedType(inputType)));

                            operationMethod = operationMethod.AddParameterListParameters(parameter);
                        }
                    }

                    headerVariable = headerVariable.WithInitializer(EqualsValueClause(headerArrayInitializer));

                    headerCollectionDeclaration = headerCollectionDeclaration.AddVariables(headerVariable);

                    var headerCollectionBlock = LocalDeclarationStatement(headerCollectionDeclaration);

                    bodyStatements = bodyStatements.Add(headerCollectionBlock);
                    bodyStatements = bodyStatements.Add(EmptyStatement().WithSemicolonToken(MissingToken(SyntaxKind.SemicolonToken)));

                    var invocationMemberAccessExpression = MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("SimpleSOAPClient.Models"), IdentifierName("SimpleSOAPClientBase"));

                    var memberAccessExpression = MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, invocationMemberAccessExpression, GenericName(Identifier("Send")).WithTypeArgumentList(TypeArgumentList(SeparatedList <TypeSyntax>(new SyntaxNodeOrToken[] { IdentifierName(GetAliasedType(inputType)), Token(SyntaxKind.CommaToken), IdentifierName(GetAliasedType(outputType)) }))));

                    var arguments = ArgumentList(SeparatedList <ArgumentSyntax>(new SyntaxNodeOrToken[] {
                        Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(operation.Name))), Token(SyntaxKind.CommaToken), Argument(IdentifierName("request")), Token(SyntaxKind.CommaToken), Argument(IdentifierName("headers"))
                    }));

                    var invocationExpression = InvocationExpression(memberAccessExpression).WithArgumentList(arguments);

                    var awaitExpression = AwaitExpression(invocationExpression);

                    bodyStatements = bodyStatements.Add(ReturnStatement(awaitExpression));

                    operationMethod = operationMethod.WithBody(Block(bodyStatements));

                    operationMethod = operationMethod.WithModifiers(new SyntaxTokenList(new SyntaxToken[] { Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.AsyncKeyword) }));

                    portClass = portClass.AddMembers(operationMethod);
                }

                ns = ns.AddMembers(portClass);
            }

            var newWriter = new StreamWriter("NewSimpleSoapReference.cs", false, Encoding.UTF8);

            ns.NormalizeWhitespace()
            .WriteTo(newWriter);

            newWriter.Flush();
            newWriter.Close();
        }
Exemple #5
0
        private void DownloadWSDL()
        {
            DiscoveryClientDocument = DiscoveryClient.DiscoverAny(_endpointUri.ToString());

            DiscoveryClient.ResolveAll();
            DiscoveryContractReference = DiscoveryClientDocument.References[0] as ContractReference;
            var contract = DiscoveryContractReference.Contract;

            //contract.Types.Schemas.Compile(null, true);

            foreach (DictionaryEntry entry in DiscoveryClient.References)
            {
                if (!(entry.Value is SchemaReference discoveryReference))
                {
                    continue;
                }

                foreach (XmlSchemaObject schemaObject in discoveryReference.Schema.Items)
                {
                    DiscoveryClientReferencesElements.Add(schemaObject);
                }
                //var reference = discoveryReference as SchemaReference;
                //DiscoveryClientReferencesElements.AddRange(reference.Schema.Elements.GetEnumerator().Current);
            }

            messages = contract.Messages as MessageCollection;

            var xmlSchemas = new XmlSchemaSet();
            var ms         = new MemoryStream();
            var writer     = new StringWriter();
            var generator  = new Generator()
            {
                //OutputFolder = "files",
                OutputWriter      = new GeneratorOutput(writer),
                CollectionType    = typeof(System.Collections.Generic.List <>),
                Log               = s => Console.Out.WriteLine(s),
                NamespacePrefix   = nameSpace,
                UseXElementForAny = true,
            };

            var locations = new List <string>();
            var services  = new List <ServiceDescription>();

            foreach (var document in DiscoveryClient.Documents.Values)
            {
                if (document is XmlSchema schema)
                {
                    if (!string.IsNullOrWhiteSpace(schema.SourceUri))
                    {
                        locations.Add(schema.SourceUri);
                    }
                    xmlSchemas.Add(schema);
                }
                else if (document is ServiceDescription service)
                {
                    services.Add(service);
                }
            }

            generator.Generate(locations.ToArray());

            var tree = CSharpSyntaxTree.ParseText(writer.ToString());
            var root = tree.GetRoot();

            var compilationUnit = root as CompilationUnitSyntax;

            if (compilationUnit is null)
            {
                throw new Exception("XmlSchemaClassGenerator did not produce a valid CSharp code file");
            }

            ns = compilationUnit.Members.First() as NamespaceDeclarationSyntax;

            if (ns == null)
            {
                throw new Exception("XmlSchemaClassGenerator did not produce a valid CSharp namespace as the first node");
            }

            foreach (ServiceDescription serviceDescription in services)
            {
                foreach (Binding binding in serviceDescription.Bindings)
                {
                    //currentMessagesList = serviceDescription.Messages.Cast<Message>().ToList();

                    foreach (OperationBinding operationBinding in binding.Operations)
                    {
                        ParseOperationBinding(operationBinding);
                    }
                }
            }

            var newWriter = new StreamWriter("NewSimpleSoapReference.cs", false, Encoding.UTF8);

            ns.NormalizeWhitespace()
            .WriteTo(newWriter);

            newWriter.Flush();
            newWriter.Close();

            return;

            /*xmlSchemas.Compile(null, true);
             *
             * foreach (XmlSchema schema in xmlSchemas)
             * {
             *  foreach (XmlSchemaElement element in schema.Elements.Values)
             *  {
             *      ParseXmlSchemaElement(element);
             *  }
             *
             *  foreach (var value in schema.Items)
             *  {
             *      if (value is XmlSchemaComplexType cType)
             *      {
             *          //ParseXmlSchemaComplexType(cType);
             *      }
             *      else if (value is XmlSchemaSimpleType sType)
             *      {
             *          //ParseXmlSchemaSimpleType(sType);
             *      }
             *  }
             * }
             *
             * var newWriter = new StreamWriter("NewSimpleSoapReference.cs", false, Encoding.UTF8);
             *
             * ns.NormalizeWhitespace()
             *  .WriteTo(newWriter);
             *
             * newWriter.Flush();
             * newWriter.Close();*/
        }