Beispiel #1
0
        public void GenerateCode_InputIsEmpty_NotSuccessful()
        {
            #region Arrange

            string input = null;

            #endregion

            #region Act

            CodeGeneratorService service = new CodeGeneratorService {
            };
            CodeGenerationResult result  = service.GenerateCode(input);

            #endregion

            #region Assert

            Assert.IsNotNull(result);
            Assert.IsFalse(result.IsSuccessful);
            Assert.IsNotNull(result.Error);
            Assert.IsTrue(result.Error.ToLower().Contains("empty"));
            Assert.IsNull(result.Code);

            #endregion
        }
        public CodeGenerationResult Generate(string jsonSchema, string jsonFileName, string targetNamespace)
        {
            if (string.IsNullOrEmpty(jsonSchema))
            {
                throw new ArgumentException("json schema was not provided", nameof(jsonSchema));
            }

            var rootname    = GetDefaultRootItemNameFromFileName(jsonFileName);
            var typeNameGen = new CustomTypeNameGenerator(rootname);
            var schema      = JsonSchema4.FromJson(jsonSchema);
            var generator   = new CSharpGenerator(schema, new CSharpGeneratorSettings()
            {
                Namespace = targetNamespace, ClassStyle = CSharpClassStyle.Poco, RequiredPropertiesMustBeDefined = false, TypeNameGenerator = typeNameGen, ArrayType = "List"
            });

            var result = new CodeGenerationResult {
                Code = generator.GenerateFile()
            };

            AddAssemblyVersionAttributes(result, targetNamespace);

            // this calling back to the TypeGenerator sure gives these a 'bas type/sub-type' kind of vibe.
            TypeGenerator.BuildGeneratedCode(result, rootname, CreateMetadataReferences());

            result.RootTypeName = typeNameGen.AssignedRootTypeName;

            return(result);
        }
        private static void GenerateQueryType(
            CodeGenerationResult result,
            DataGeneratorContext dataContext,
            CodeGeneratorContext generatorContext,
            IReadOnlyList <IObjectType> objectTypes)
        {
            ClassDeclarationSyntax queryDeclaration =
                ClassDeclaration("Query") // todo : we need to read the name from the config
                .AddModifiers(
                    Token(SyntaxKind.PublicKeyword),
                    Token(SyntaxKind.PartialKeyword))
                .AddGeneratedAttribute()
                .AddExtendObjectTypeAttribute("Query");

            foreach (IObjectType?objectType in objectTypes)
            {
                queryDeclaration = queryDeclaration.AddMembers(
                    CreateQueryResolver(dataContext, generatorContext, objectType));

                GenerateObjectType(result, generatorContext.Namespace !, objectType);
            }

            NamespaceDeclarationSyntax namespaceDeclaration =
                NamespaceDeclaration(IdentifierName(generatorContext.Namespace !))
                .AddMembers(queryDeclaration);

            CompilationUnitSyntax compilationUnit =
                CompilationUnit()
                .AddMembers(namespaceDeclaration);

            compilationUnit = compilationUnit.NormalizeWhitespace(elasticTrivia: true);

            result.AddSource(generatorContext.Namespace !+".Query.cs", compilationUnit.ToFullString());
        }
 /// <summary>
 /// Constructs a new mapping entry.
 /// </summary>
 /// <param name="mapping">The parent mapping.</param>
 /// <param name="mappingKey">The current mapping key.</param>
 /// <param name="codeGenerationResult">
 /// The intermediate code-generation result.
 /// </param>
 public MappingEntry(
     IntrinsicMapping <TDelegate> mapping,
     IntrinsicMapping.MappingKey mappingKey,
     CodeGenerationResult codeGenerationResult)
 {
     Mapping              = mapping;
     MappingKey           = mappingKey;
     CodeGenerationResult = codeGenerationResult;
 }
        private static void GenerateDependencyInjectionCode(
            CodeGenerationResult result,
            CodeGeneratorContext generatorContext)
        {
            var typeName = generatorContext.Name + "RequestExecutorBuilderExtensions";

            ClassDeclarationSyntax dependencyInjectionCode =
                ClassDeclaration(typeName)
                .AddModifiers(
                    Token(SyntaxKind.PublicKeyword),
                    Token(SyntaxKind.StaticKeyword),
                    Token(SyntaxKind.PartialKeyword))
                .AddGeneratedAttribute();

            var statements = new List <StatementSyntax>
            {
                AddTypeExtension(Global(generatorContext.Namespace + ".Query")),
                AddNeo4JFiltering(),
                AddNeo4JSorting(),
                AddNeo4JProjections(),
                ReturnStatement(IdentifierName("builder"))
            };

            MethodDeclarationSyntax addTypes =
                MethodDeclaration(
                    IdentifierName(Global(IRequestExecutorBuilder)),
                    Identifier("Add" + generatorContext.Name + "Types"))
                .WithModifiers(
                    TokenList(
                        Token(SyntaxKind.PublicKeyword),
                        Token(SyntaxKind.StaticKeyword)))
                .WithParameterList(
                    ParameterList(
                        SingletonSeparatedList(
                            Parameter(Identifier("builder"))
                            .WithModifiers(TokenList(Token(SyntaxKind.ThisKeyword)))
                            .WithType(IdentifierName(Global(IRequestExecutorBuilder))))))
                .WithBody(Block(statements));

            dependencyInjectionCode =
                dependencyInjectionCode.AddMembers(addTypes);

            NamespaceDeclarationSyntax namespaceDeclaration =
                NamespaceDeclaration(IdentifierName(DependencyInjection))
                .AddMembers(dependencyInjectionCode);

            CompilationUnitSyntax compilationUnit =
                CompilationUnit()
                .AddMembers(namespaceDeclaration);

            compilationUnit = compilationUnit.NormalizeWhitespace(elasticTrivia: true);

            result.AddSource(DependencyInjection + $".{typeName}.cs", compilationUnit.ToFullString());
        }
        private static void GenerateObjectType(
            CodeGenerationResult result,
            string @namespace,
            IObjectType objectType)
        {
            TypeNameDirective?typeNameDirective =
                objectType.GetFirstDirective <TypeNameDirective>("typeName");
            var typeName = typeNameDirective?.Name ?? objectType.Name.Value;

            ClassDeclarationSyntax modelDeclaration =
                ClassDeclaration(typeName)
                .AddModifiers(
                    Token(SyntaxKind.PublicKeyword),
                    Token(SyntaxKind.PartialKeyword))
                .AddGeneratedAttribute();

            foreach (IObjectField field in objectType.Fields.Where(t => !t.IsIntrospectionField))
            {
                RelationshipDirective?relationship =
                    field.GetFirstDirective <RelationshipDirective>("relationship");

                modelDeclaration =
                    modelDeclaration.AddProperty(
                        field.GetPropertyName(),
                        IdentifierName(field.GetTypeName(@namespace)),
                        field.Description,
                        setable: true,
                        configure: p =>
                {
                    if (relationship is not null)
                    {
                        p = p.AddNeo4JRelationshipAttribute(
                            relationship.Name,
                            relationship.Direction);
                    }

                    return(p);
                });
            }

            NamespaceDeclarationSyntax namespaceDeclaration =
                NamespaceDeclaration(IdentifierName(@namespace))
                .AddMembers(modelDeclaration);

            CompilationUnitSyntax compilationUnit =
                CompilationUnit()
                .AddMembers(namespaceDeclaration);

            compilationUnit = compilationUnit.NormalizeWhitespace(elasticTrivia: true);

            result.AddSource(@namespace + $".{typeName}.cs", compilationUnit.ToFullString());
        }
        public CodeGenerationResult Generate(CodeGeneratorContext context)
        {
            var result = new CodeGenerationResult();

            ISchema schema = SchemaHelper.CreateSchema(context.Documents);

            GenerateTypes(
                result,
                DataGeneratorContext.FromSchema(schema),
                context,
                schema);

            return(result);
        }
        public CodeGenerationResult GenerateCode(string input)
        {
            CodeGenerationResult result = new CodeGenerationResult {
            };

            if (string.IsNullOrEmpty(input))
            {
                result.IsSuccessful = false;
                result.Error        = "Input cannot be null or empty";

                return(result);
            }

            if (input.Length < 3)
            {
                result.IsSuccessful = false;
                result.Error        = "Input cannot be less than 3 characters";

                return(result);
            }

            // Generazione PREFIX
            string prefix = string.Empty;

            if (IsVowel(input[0]))
            {
                prefix = "VC";
            }
            else
            {
                prefix = "OT";
            }

            // Generazione BODY
            string bodyEnding = IsVowel(input[2]) ? "00--" : "000:";
            string body       = "B" + input.Length + bodyEnding;

            // Generazione SUFFIX
            string suffix = input.Length % 2 == 0 ? "$PR" : "$DS";

            result.Code         = $"{prefix}{body}{suffix}";
            result.IsSuccessful = true;

            return(result);
        }
        private static void GenerateTypes(
            CodeGenerationResult result,
            DataGeneratorContext dataContext,
            CodeGeneratorContext generatorContext,
            ISchema schema)
        {
            GenerateQueryType(
                result,
                dataContext,
                generatorContext,
                schema.Types
                .OfType <ObjectType>()
                .Where(type => !IntrospectionTypes.IsIntrospectionType(type))
                .ToList());

            GenerateDependencyInjectionCode(
                result,
                generatorContext);
        }
Beispiel #10
0
        internal static CodeGenerationResult BuildGeneratedCode(CodeGenerationResult result, string assemblyName, MetadataReference[] references)
        {
            var st = CSharpSyntaxTree.ParseText(result.Code);

            var fileName = assemblyName;
            var options  = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            CSharpCompilation compilation = CSharpCompilation.Create(
                fileName,
                syntaxTrees: new[] { st },
                references: references,
                options: options);

            result.AssemblyBytes = new MemoryStream();
            EmitResult emitted = compilation.Emit(result.AssemblyBytes);

            if (!emitted.Success)
            {
                result.Errors = new List <string>();

                IEnumerable <Diagnostic> failures = emitted.Diagnostics.Where(diagnostic =>
                                                                              diagnostic.IsWarningAsError ||
                                                                              diagnostic.Severity == DiagnosticSeverity.Error);

                foreach (Diagnostic diagnostic in failures)
                {
                    result.Errors.Add(string.Format("{0}: {1}", diagnostic.Id, diagnostic.GetMessage()));
                }
            }
            else
            {
                result.AssemblyBytes.Seek(0, SeekOrigin.Begin);
                result.Assembly = Assembly.Load(result.AssemblyBytes.ToArray());
                result.AssemblyBytes.Seek(0, SeekOrigin.Begin);
            }


            result.AssemblyName = fileName + ".dll";
            return(result);
        }
        public CodeGenerationResult Generate(PhysicalSchema schema /* Maybe this should take a logical schema instead to help work out the root elements? */, string targetNamespace)
        {
            var code = CreateCodeNamespace(schema, targetNamespace);

            var provider = new Microsoft.CSharp.CSharpCodeProvider();

            var sb = new StringBuilder();

            using (StringWriter sw = new StringWriter(sb))
            {
                provider.CreateGenerator().GenerateCodeFromNamespace(code.Code, sw, new CodeGeneratorOptions());
            }

            var result = new CodeGenerationResult()
            {
                Code = sb.ToString()
            };

            TypeGenerator.BuildGeneratedCode(result, schema.Files[0].FileName /* TODO */, CreateMetadataReferences());
            result.RootTypeName = code.RootElementName;
            return(result);
        }
 private IEnumerable<PropertyInfo> AllPropertiesExceptMetaData(CodeGenerationResult infos)
 {
     return (from p in infos.DataContext.GetProperties()
             where p.Name!="MetaData"
             select p);
 }
        private void AddAssemblyVersionAttributes(CodeGenerationResult result, string targetNamespace)
        {
            var ns = "namespace " + targetNamespace;

            result.Code = result.Code.Replace(ns, VersionInfo + ns); // pretty horrible
        }
Beispiel #14
0
 private IEnumerable <PropertyInfo> AllPropertiesExceptMetaData(CodeGenerationResult infos)
 {
     return(from p in infos.DataContext.GetProperties()
            where p.Name != "MetaData"
            select p);
 }