Ejemplo n.º 1
0
        public void SetUp()
        {
            string namespaceStr = "Namespace.SubNamespace";
            string nameStr      = "ClassName";
            List <PropertyDescription> properties = new List <PropertyDescription>
            {
                new PropertyDescription("Property1", "long", false),
                new PropertyDescription("Property2", "string", true),
                new PropertyDescription("Property3", "bool", true)
            };

            List <FunctionDescription> functions = new List <FunctionDescription>
            {
                new FunctionDescription("Method1", "Object", new List <string>()),
                new FunctionDescription("Method2", "void", new List <string>
                {
                    "string",
                    "int",
                    "bool"
                }),
            };

            ClassDescription cd = new ClassDescription(
                nameStr,
                namespaceStr,
                properties,
                functions);

            _classGenerator = new ClassGenerator(cd);
        }
Ejemplo n.º 2
0
        public static string GeneratePlayerDataGetterScript(List <PlayerDataEditorData> datas)
        {
            ClassGenerationData classData = new ClassGenerationData
            {
                m_ClassName = "PlayerDataGetter",
                m_Namespace = PlayerDataCodeGeneratorConstants.NAMESPACE_GAME,
                m_Usings    = new string[] { "UniRx", "System", "System.Collections.Generic", PlayerDataCodeGeneratorConstants.NAMESPACE_FRAMEWORK },
                m_ClassType = ClassType.Partial
            };

            for (int i = 0; i < datas.Count; i++)
            {
                if (!datas[i].shouldGenerateGetter)
                {
                    continue;
                }

                classData.m_MethodGenerationDatas.AddRange(PlayerDataMethodGenerator.GenerateGetterMethods(datas[i]));
            }


            string code = ClassGenerator.CreateClass(classData);

            return(code);
        }
Ejemplo n.º 3
0
        private void ExpectGeneratedClassContainsExtension <TMemberInfo>
        (
            Type targetType,
            Func <Type, string, BindingFlags, TMemberInfo> memberGetter,
            Func <TMemberInfo, string> extensionGenerator,
            string memberName,
            bool shouldContain = true
        )
        {
            var bindingFlags =
                BindingFlags.Public |
                BindingFlags.NonPublic |
                BindingFlags.Instance;

            TMemberInfo memberInfo = memberGetter(targetType, memberName, bindingFlags);

            string expectedMethod = extensionGenerator(memberInfo)
                                    .NormalizeWhitespace();

            string generatedClass = ClassGenerator
                                    .Generate("dontcare", targetType)
                                    .NormalizeWhitespace();

            Assert.Equal(generatedClass.Contains(expectedMethod), shouldContain);
        }
Ejemplo n.º 4
0
        private void GenerateViewModels(Domain domain)
        {
            var generator = new ClassGenerator();
            var files     = generator.GenerateEditModels(domain);

            _fileWriter.ApplyCodeFiles(files, "Models");
        }
Ejemplo n.º 5
0
        public static IMRM CreateMRM(MemberInfo member)
        {
            Type type = ClassGenerator.CreateMRMType(member);
            IMRM obj  = (IMRM)type.GetConstructor(Type.EmptyTypes).Invoke(null);

            return(obj);
        }
Ejemplo n.º 6
0
    public void TestGenerateDelegateEvents()
    {
        var gen         = new CodeUnitGenerator("TestCodeGen");
        var classGen    = new ClassGenerator("TestClass");
        var delegateGen = new DelegateGenerator("MyEventHandler")
                          .AddParameter("TestClass", "myRef")
                          .AddReturnType(typeof(bool));

        var eventGen = new EventGenerator("OnSomeTrigger", delegateGen.delegateType);

        classGen.AddEvent(eventGen);
        var fireEventMethod = new MethodGenerator("FireEvent")
                              .AddStatement(new StatementBuilder()
                                            //.AddSnippetExpression("Debug.Log();DoMoreStuff();"));
                                            .InvokeEvent(eventGen, new ParamBuilder()
                                                         .AddPrimitiveExpression("new TestClass()")));

        classGen.AddMethod(fireEventMethod);

        gen.AddType(delegateGen);
        gen.AddType(classGen);

        var classSubscriber = new ClassGenerator("MySubscribeClass");
        var field           = new FieldGenerator("TestClass", "eventSource");

        classSubscriber.AddField(field);

        var constructor = new ConstructorGenerator(classSubscriber.classType);

        classSubscriber.AddMethod(constructor);

        var eventHandler = new MethodGenerator("OnSomeTrigger", delegateGen)
                           .AddStatement(new StatementBuilder()
                                         .AddSnippet("Debug.Log(\"Expression1\");")
                                         .AddSnippet("Debug.Log(\"Expression2\");"));

        var subscribeMethod = new MethodGenerator("AddListener")
                              .AddStatement(new StatementBuilder()
                                            .AttachEvent(eventHandler, new FieldTarget(field), eventGen));

        classSubscriber.AddMethod(
            new MethodGenerator("Unsubscribe").AddStatement(
                new StatementBuilder()
                .DetachEvent(eventHandler, new FieldTarget(field), eventGen)));
        classSubscriber.AddMethod(eventHandler);
        classSubscriber.AddMethod(subscribeMethod);
        gen.AddType(classSubscriber);

        var ccu = gen.GenerateCompileUnit();

        var output = StringCompiler.CompileToString(ccu);

        //Debug.Log(output);
        Assert.IsTrue(output.Contains("OnSomeTrigger"));
        Assert.IsTrue(output.Contains("FireEvent"));
        Assert.IsTrue(output.Contains("+="));
        Assert.IsTrue(output.Contains("-="));
        Assert.IsTrue(output.Contains("delegate"));
        Assert.IsTrue(output.Contains("event"));
    }
        public async Task <ClassTypeDto> Handle(DeleteClassTypeCommand request, CancellationToken cancellationToken)
        {
            var classTypeEntity = await _dbContext
                                  .ClassTypes
                                  .SingleOrDefaultAsync(m => m.ClassTypeId == request.ClassTypeId, cancellationToken);

            classTypeEntity.IsDeleted = true;
            _ = await _dbContext.SaveChangesAsync(cancellationToken);

            var timetablesList = await _dbContext
                                 .Timetables
                                 .Where(x => x.ClassTypeId == request.ClassTypeId && x.EndingDate > DateTime.Today)
                                 .ToListAsync(cancellationToken);

            var classGenerator = new ClassGenerator(_dbContext);

            foreach (var timetable in timetablesList)
            {
                await classGenerator.DeleteAllFutureClassesByTimetableIdAsync(timetable, cancellationToken);

                timetable.EndingDate = DateTime.Today;
            }

            await _dbContext.SaveChangesAsync(cancellationToken);

            var classTypeDto = classTypeEntity.Adapt <ClassTypeDto>();

            return(classTypeDto);
        }
Ejemplo n.º 8
0
    public void TestGenerateAttributes()
    {
        var gen = new CodeUnitGenerator("TestCodeGen");

        var attributeGen = new ClassGenerator("MyAttribute")
                           .AddBaseType("Attribute");

        var classGen = new ClassGenerator("TestClass");

        classGen.SetCustomAttribute("MyAttribute", new ParamBuilder());

        var field = new FieldGenerator(typeof(int), "MyField");

        field.SetCustomAttribute("MyAttribute", new ParamBuilder());
        var property = new AutoPropertyGenerator("TestClass", "MyProp");

        property.SetCustomAttribute("MyAttribute", new ParamBuilder());


        classGen.AddAutoProperty(property);
        classGen.AddField(field);
        gen.AddType(attributeGen);
        gen.AddType(classGen);
        var ccu = gen.GenerateCompileUnit();

        var output = StringCompiler.CompileToString(ccu);

        Debug.Log(output);
        Assert.IsTrue(output.Contains("MyAttribute"));
    }
Ejemplo n.º 9
0
        private void GenerateMethods(ClassGenerator classGenerator, Type contract)
        {
            MethodInfo[] methods = ContractDefinition.GetEffectiveMethods(contract).ToArray();

            foreach (MethodInfo method in methods)
            {
                MethodDescriptor descriptor = MetadataProvider.GetMethodDescriptor(ContractDefinition, method);

                GenerateMethod(classGenerator, descriptor, false);

                bool generateAsync = ShouldBeAsync(method, ForceAsync);
                if (generateAsync)
                {
                    WriteLine();
                }
                else
                {
                    if (!Equals(method, methods.Last()))
                    {
                        WriteLine();
                    }
                }

                if (generateAsync)
                {
                    GenerateMethod(classGenerator, descriptor, true);
                    WriteLine();
                }
            }
        }
Ejemplo n.º 10
0
        private void InstallDtmlXsd()
        {
            //string assemblyName = GetCodeBuilderAssemblyName();
            //Assembly assembly = Assembly.Load(assemblyName);

            //it seems that it runs this before the GAC is deployed, so the above code deosn't work
            //I have to embed the XSD in this assembly instead
            var assembly = Assembly.GetExecutingAssembly();

            // Load the XSD for DocTypeML.
            string xsd;

            using (Stream s = ClassGenerator.GetXsd())
            {
                using (StreamReader sr = new StreamReader(s))
                {
                    xsd = sr.ReadToEnd();
                }
            }

            // Write the XSD to the Visual Studio folder with XML schemas.
            using (StreamWriter sw = File.CreateText(GetDtmlXsdPath()))
            {
                sw.Write(xsd);
            }
        }
Ejemplo n.º 11
0
        public void GetClassContent_Method_TwoParameters_NoStatements()
        {
            Method MoveMouse = new Method()
            {
                Name           = "DoMoveMouse",
                AccessModifier = AccessModifierEnum.INTERNAL,
                ReturnType     = null,
                Parameters     = new List <MethodParameter>()
                {
                    new MethodParameter()
                    {
                        Name = "xPos", ParamType = typeof(int)
                    },
                    new MethodParameter()
                    {
                        Name = "yPos", ParamType = typeof(int)
                    }
                }
            };
            PluginClass testClass = new PluginClass()
            {
                Name      = "Heippa",
                Namespace = "Joel.Testar",
                Methods   = new List <Method>()
                {
                    MoveMouse
                }
            };

            var expected = "namespace Joel.Testar\n{\n\tpublic class Heippa\n\t{\n\t\tinternal void DoMoveMouse(int xPos,int yPos)\n\t\t{\n\t\t}\n\t}\n}\n";

            var actual = ClassGenerator.GetClassAsString(testClass);

            Assert.AreEqual(expected, actual);
        }
Ejemplo n.º 12
0
        public void GetClassContent_Name_Namespace_TwoUsingClauses()
        {
            PluginClass testClass = new PluginClass()
            {
                Name         = "Heippa",
                Namespace    = "Joel.Testar",
                UsingClauses = new List <UsingClause>()
                {
                    new UsingClause()
                    {
                        Name = "System"
                    },
                    new UsingClause()
                    {
                        Name = "System.Collections.Generic"
                    },
                }
            };

            var expected = "using System;\nusing System.Collections.Generic;\nnamespace Joel.Testar\n{\n\tpublic class Heippa\n\t{\n\t}\n}\n";

            var actual = ClassGenerator.GetClassAsString(testClass);

            Assert.AreEqual(expected, actual);
        }
Ejemplo n.º 13
0
        public async Task ExecuteToFileTest()
        {
            var fileName = ".\\test-project.mdj";
            var project  = await DVDpro.StarUML.FileFormat.Project.LoadAsync(fileName);

            var tmpFile = System.IO.Path.GetTempFileName();

            try
            {
                var generator = new ClassGenerator();
                using (var outStream = new CSharpWriter(tmpFile))
                {
                    foreach (var model in project.GetChildrenByType <DVDpro.StarUML.FileFormat.Nodes.UmlModelNode>())
                    {
                        var node = model.GetChildrenByType <DVDpro.StarUML.FileFormat.Nodes.UmlClassNode>().First(r => r.Name == "Engine");
                        generator.Generate(outStream, node);
                    }
                }
                var output = await System.IO.File.ReadAllTextAsync(tmpFile);

                Assert.Equal("public partial class Engine : Interface1\r\n{\r\n    public string UniqueId { get; set; }\r\n}\r\n", output);
            }
            finally
            {
                System.IO.File.Delete(tmpFile);
            }
        }
Ejemplo n.º 14
0
        public void GetClassContent_Name_Namespace_BaseClass_TwoInterfaces()
        {
            PluginClass testClass = new PluginClass()
            {
                Name          = "Heippa",
                Namespace     = "Joel.Testar",
                BaseClassName = "TestClassBase",
                Interfaces    = new List <Interface>()
                {
                    new Interface()
                    {
                        Name = "FirstInterface"
                    },
                    new Interface()
                    {
                        Name = "SecondInterface"
                    }
                }
            };

            var expected = "namespace Joel.Testar\n{\n\tpublic class Heippa:TestClassBase,FirstInterface,SecondInterface\n\t{\n\t}\n}\n";

            var actual = ClassGenerator.GetClassAsString(testClass);

            Assert.AreEqual(expected, actual);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Returns a random field for a given class.
        /// </summary>
        /// <param name="generator"> </param>
        /// <param name="isStatic">
        /// @return </param>
        public static Field getRandomField(ClassGenerator generator, bool isStatic)
        {
            Field  field;
            Random rand = new Random();

            // if no fields for this class is available
            if (generator.Fields.size() == 0)
            {
                return(null);
            }

            field = generator.Fields.get(rand.Next(generator.Fields.size()));
            int count = 5000;

            while (field.Static != isStatic && count > 0)
            {
                field = generator.Fields.get(rand.Next(generator.Fields.size()));
                count--;
            }

            if (field.Static == isStatic && count > 0)
            {
                // adding to the used variable Set
                generator.UsedFields.add(field);
                return(field);
            }

            return(null);
        }
Ejemplo n.º 16
0
        //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
        //ORIGINAL LINE: @SuppressWarnings("unchecked") private static java.util.ArrayList getClassByMethodReturnType(java.util.ArrayList<edu.uta.cse.proggen.classLevelElements.Field> objList, edu.uta.cse.proggen.classLevelElements.Type.Primitives returnType, java.util.ArrayList<edu.uta.cse.proggen.packageLevelElements.ClassGenerator> classList)
        private static ArrayList getClassByMethodReturnType(List <Field> objList, Type.Primitives returnType, List <ClassGenerator> classList)
        {
            Field  field;
            int    counter = 500;
            Random random  = new Random();

            field = objList[random.Next(objList.Count)];
            ClassGenerator classObj = getClassByName(classList, field.Type.ToString());

            while (counter > 0 && !classObj.ReturnTypeSet.Contains(returnType))
            {
                field    = objList[random.Next(objList.Count)];
                classObj = getClassByName(classList, field.Type.ToString());
                counter--;
            }

            if (counter > 0 && classObj.ReturnTypeSet.Contains(returnType))
            {
                ArrayList list = new ArrayList();
                list.Add(field);
                list.Add(classObj);
                return(list);
            }

            return(null);
        }
Ejemplo n.º 17
0
        public async Task <TimetableDto> Handle(AddTimetableCommand request, CancellationToken cancellationToken)
        {
            var timetableEntity = request.NewTimetableDto.Adapt <Timetable>();

            _ = await _dbContext.AddAsync(timetableEntity, cancellationToken);

            _ = await _dbContext.SaveChangesAsync(cancellationToken);

            var newTimetable = _dbContext
                               .Timetables
                               .Where(m => m.ClassTypeId == request.NewTimetableDto.ClassTypeId)
                               .AsEnumerable()
                               .LastOrDefault();

            if (newTimetable is null)
            {
                throw new NullReferenceException("Failed to add timetable. Try again");
            }

            var classGenerator = new ClassGenerator(_dbContext);
            await classGenerator.AddClassesForTimetableAsync(timetableEntity, cancellationToken);

            var newTimetableDto = newTimetable.Adapt <TimetableDto>();

            return(newTimetableDto);
        }
Ejemplo n.º 18
0
    public void TestGenerateClassImplementation()
    {
        var gen      = new CodeUnitGenerator("TestCodeGen");
        var classGen = new ClassGenerator("TestClass")
                       .SetIsPartial(true)
                       .SetIsAbstract(true)
                       .AddBaseType("IComponent");
        var field       = new FieldGenerator(typeof(int), "MyField");
        var property    = new AutoPropertyGenerator("TestClass", "MyProp");
        var constructor = new ConstructorGenerator()
                          .AddBaseCall("BaseArg")
                          .AddParameter(field.FieldType, field.Name)
                          .AddParameter(property.Name, property.PropertyType)
                          .AddStatement(new StatementBuilder()
                                        .AddConstructorFieldAssignement(field.Name, field.Name)
                                        .AddConstructorPropertyAssignement(property.Name, property.Name));

        classGen.AddAutoProperty(property);
        classGen.AddField(field);
        classGen.AddMethod(constructor);
        gen.AddType(classGen);
        var ccu = gen.GenerateCompileUnit();

        var output = StringCompiler.CompileToString(ccu);

        Debug.Log(output);
        Assert.IsTrue(output.Contains("base("));
        Assert.IsTrue(output.Contains("BaseArg"));
    }
Ejemplo n.º 19
0
    public void TestGenerateForLoop()
    {
        var gen      = new CodeUnitGenerator("TestCodeGen");
        var classGen = new ClassGenerator("TestClass")
                       .SetIsSealed(true);
        var method = new MethodGenerator("IterateStuff");

        method.AddStatement(new StatementBuilder()
                            .AddVariable(typeof(string[]), "myStuff", true)
                            .AddVariable(typeof(bool), "myBool", true)
                            .AddVariable(typeof(int), "myInt", 1)
                            .AddSnippet("//Snippet")
                            .AddForLoop("i", 10, new StatementBuilder()
                                        .AddSnippet("Debug.Log()")
                                        .AddAssignement(new VariableTarget("myInt"), new VariableTarget("i"))
                                        .InvokeMethod(new VariableTarget("myStuff"),
                                                      new ClassTarget("UnityEngine"),
                                                      "GetAllStuff",
                                                      new ParamBuilder()
                                                      .AddVariable("myInt"))));
        classGen.AddMethod(method);
        gen.AddType(classGen);
        var ccu = gen.GenerateCompileUnit();

        var output = StringCompiler.CompileToString(ccu);

        Debug.Log(output);
        Assert.IsTrue(output.Contains("for (i = 0"));
        Assert.IsTrue(output.Contains("(i < 10"));
        Assert.IsTrue(output.Contains("myStuff = UnityEngine.GetAllStuff("));
    }
Ejemplo n.º 20
0
        private void GenerateWebApi(Domain domain)
        {
            var generator = new ClassGenerator();
            var files     = generator.GenerateWebApiControllers(domain);

            _fileWriter.ApplyCodeFiles(files, "Controllers");
        }
        private static async Task GenerateClass(KernelInvocationContext context,
                                                IFileReader fileReader,
                                                IGeneratorConfiguration config)
        {
            var classGenerator = new ClassGenerator();
            var className      = Path.GetFileNameWithoutExtension(fileReader.FileName);

            className = char.ToUpper(className[0]) + className.Substring(1);
            context.Display($"Generating class {className}", new[] { "text/html" });
            var source = classGenerator.GenerateFile(fileReader.FileMetaData, config);
            var result = await context.HandlingKernel.SubmitCodeAsync(source);

            result.KernelEvents.Subscribe((ev) => { }, (ex) =>
            {
                context.Display(ex.Message, new[] { "text/plain" });
            });
            result.KernelEvents.Subscribe((ev) =>
            {
                if (ev is ErrorProduced error)
                {
                    context.Fail(context.Command, null, error.Message);
                }
                if (ev is CommandFailed failure)
                {
                    context.Fail(context.Command, null, failure.Message);
                }
            });
        }
Ejemplo n.º 22
0
        public static void GenerateCode1()
        {
            MethodGenerator method = new MethodGenerator("Test");

            method.SetAuthority(MethodAuthorityType.Internal);
            method.SetDecorate(MethodDecorateType.Virtual);
            method.SetParms(new string[] { "int", "string" });
            method.SetReturn("bool");
            MethodGenerator method1 = new MethodGenerator("Test1");

            method1.SetAuthority(MethodAuthorityType.Internal);
            method1.SetDecorate(MethodDecorateType.Virtual);
            method1.SetParms(new string[] { "int", "string" });
            method1.SetReturn("bool");
            ClassGenerator textClass = new ClassGenerator("TestClass");

            textClass.SetUsingName(new string[] { "xxxx", "aaaa" });
            textClass.SetBaseClass("xxcvsdf");
            textClass.SetDecorate(ClassDecorateType.Abstract);
            textClass.SetAuthority(AuthorityType.Public);
            textClass.SetInterfaces(new string[] { "asdfsadf", "asdfasdf" });
            textClass.SetNamespace("masdjf");
            textClass.AddMethod(method);
            textClass.AddMethod(method1);
            string classValue = textClass.ToString();

            TxtUtility.StringToFile(classValue);
        }
Ejemplo n.º 23
0
        public static MRMTuple CreateMRMTuple(MemberInfo member, MappingType mappingType)
        {
            MRMTuple mrmTuple = new MRMTuple();

            mrmTuple.StrongMRM = new Lazy <IMRM>(() =>
            {
                Type type      = ClassGenerator.CreateMRMType(member);
                IMRM strongMrm = (IMRM)type.GetDefaultConstructor().Invoke(null);
                return(strongMrm);
            }, LazyThreadSafetyMode.ExecutionAndPublication);

            if (member.GetMemberType().GetUnderlyingType().IsEnum /* 枚举比较特殊 */)
            {
                mrmTuple.SafeMRM = mrmTuple.StrongMRM;
            }
            else
            {
                mrmTuple.SafeMRM = new Lazy <IMRM>(() =>
                {
                    return(new MRM2(member, mappingType));
                }, LazyThreadSafetyMode.ExecutionAndPublication);
            }

            return(mrmTuple);
        }
Ejemplo n.º 24
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldVerifyBytecode() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldVerifyBytecode()
        {
            // given
            CodeGenerator generator = generateCode(BYTECODE, VERIFY_GENERATED_BYTECODE);

            ClassHandle handle;

            using (ClassGenerator clazz = generator.generateClass(PACKAGE, "SimpleClass"), CodeBlock code = clazz.generateMethod(typeof(Integer), "box", param(typeof(int), "value")))
            {
                handle = clazz.Handle();
                code.Returns(code.Load("value"));
            }

            // when
            try
            {
                handle.LoadClass();
                fail("Should have thrown exception");
            }
            // then
            catch (CompilationFailureException expected)
            {
                assertThat(expected.ToString(), containsString("box(I)"));
            }
        }
Ejemplo n.º 25
0
        /// <param name="compilerVersion">Defaults to 'v4.0'</param>
        public static Assembly CompilePluginIntoAssembly(PluginClass plugin, string compilerVersion = null)
        {
            if (plugin == null)
            {
                throw new ArgumentNullException("plugin", "PluginClass is required");
            }
            if (string.IsNullOrWhiteSpace(plugin.Name))
            {
                throw new ArgumentException("Plugin name is required");
            }

            var sourceCode = ClassGenerator.GetClassAsString(plugin);
            var provider   = new CSharpCodeProvider(new Dictionary <string, string> {
                { "CompilerVersion", compilerVersion ?? "v4.0" }
            });
            var cp = new CompilerParameters();

            cp.ReferencedAssemblies.Add("Plugin.Interfaces.dll");
            cp.GenerateExecutable = false;
            cp.OutputAssembly     = plugin.Name + ".dll";
            cp.GenerateInMemory   = true;
            CompilerResults cr = provider.CompileAssemblyFromSource(cp, sourceCode);

            if (cr.Errors.Count > 0)
            {
                throw new PluginCompilationException(cr.Errors, "Plugin " + plugin.Name + "failed compilation");
            }
            return(cr.CompiledAssembly);
        }
Ejemplo n.º 26
0
        private static void TestTestGenerator()
        {
            string         path = @"C:\Users\emermillod\Documents\Visual Studio 2013\Projects\BusinessRuleManagementSystem\ConsoleApplication1\ARandomClass.cs";
            ClassGenerator gen  = new ClassGenerator(path);

            gen.GenerateClass();
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Constructor that creates a method with/without
        /// generating the method body based on the needMethodBody
        /// parameter.
        /// </summary>
        /// <param name="isStatic"> </param>
        /// <param name="numberOfParams"> </param>
        /// <param name="associatedClass"> </param>
        /// <param name="classList"> </param>
        /// <param name="name"> </param>
        /// <param name="locPerMethod"> </param>
        /// <param name="maxNestedIfs"> </param>
        /// <param name="maxAllowedMethodCalls"> </param>
        /// <param name="needMethodBody"> </param>
        private Method(bool isStatic, int numberOfParams, ClassGenerator associatedClass, List <ClassGenerator> classList, string name, int locPerMethod, int maxNestedIfs, int maxAllowedMethodCalls, bool needMethodBody)
        {
            Console.WriteLine("Constructing method..." + name);
            this.isStatic              = isStatic;
            this.numberOfParams        = numberOfParams;
            this.associatedClass       = associatedClass;
            this.classList             = classList;
            this.name                  = name;
            this.loc                   = 0;
            this.nestedIfCounter       = 0;
            this.locPerMethod          = locPerMethod;
            this.maxNestedIfs          = maxNestedIfs;
            this.maxAllowedMethodCalls = maxAllowedMethodCalls;
            this.methodCallCounter     = 0;

            generateParams();

            this.methodSignature = new MethodSignature(this.isStatic, this.returnType, this.name, this.parameterList);

            if (needMethodBody)
            {
                generateMethodBody();
                generateReturnStatement();
            }
        }
Ejemplo n.º 28
0
        public void ShouldAddTopLevelUsingsWhenNamespaceIsEmpty()
        {
            var classGenerator = new ClassGenerator();
            var classSource    = classGenerator.GenerateFile(archive.CoreFile.FileMetaData, mockConfig.Object);

            Assert.Contains("using System;", classSource);
            Assert.Contains("using DwC_A.Extensions", classSource);
        }
Ejemplo n.º 29
0
        private ClassGenerator getClassGenerator()
        {
            var generatorOptions = getGeneratorOptions();
            var entityBuilder    = new EntityBuilder(generatorOptions);
            var classGenerator   = new ClassGenerator(entityBuilder, generatorOptions);

            return(classGenerator);
        }
Ejemplo n.º 30
0
 public WorkflowToCSharpConverterFromXaml(XamlParser xamlParser,
                                          ClassCodeToCSharp classCodeToCSharp,
                                          ClassGenerator classGenerator)
 {
     this.xamlParser        = xamlParser;
     this.classCodeToCSharp = classCodeToCSharp;
     this.classGenerator    = classGenerator;
 }
Ejemplo n.º 31
0
        public static string Do3(MetaContext context)
        {
            var classGenerator = ClassGenerator.Class <D3>()
                                 .Property <B>(x => x.Some2)
                                 .Property <int>(x => x.Some);

            return(context.WrapMembers(classGenerator.Generate()));
        }
        public void SetUp()
        {
            ClassGenerator generator = new ClassGenerator();

            using (Stream schemaStream = File.OpenRead(Path.Combine("res", "ddexC.xsd")))
                generator.Parse(schemaStream);

            _classes = generator.Generate();
        }
Ejemplo n.º 33
0
        public void Generate(ClassGenerator generator, object context)
        {
            generator.WriteLine(
                "// useless comment added by user generator - '{0}', Context - '{1}'",
                GetType().FullName,
                context);

            generator.WriteLine();
        }
Ejemplo n.º 34
0
		public void ProducedFileIsSameAsExpected()
		{
			string exampleOutputContent = System.IO.File.ReadAllText(@"TestFiles\ExampleOutput.cs");
			Common.Automation.Sql.Database database = new Common.Automation.Sql.Database(TestDatabaseConnectionString);
			exampleOutputContent = exampleOutputContent.Replace("{TableCacheKey}", database.Tables[0].Hash);
			
			System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(TestDatabaseConnectionString);

			ClassGenerator cg = new ClassGenerator(conn.ConnectionString);
			string output = cg.GetPartialClassesFromDatabase();
			System.IO.File.WriteAllText(@"TestFiles\ActualOutput.cs", output);
			output = System.IO.File.ReadAllText(@"TestFiles\ActualOutput.cs");

			
			Assert.AreEqual(exampleOutputContent, output);
		}
Ejemplo n.º 35
0
        public void TestCharactersInClassName()
        {
            ItemSimpleType simple = new ItemSimpleType("fork", "int");
            FileInfo proxyFile = new FileInfo("TestColonsInVarName.cpp");
            using (var writer = proxyFile.CreateText())
            {
                writer.WriteLine();
                writer.Close();
            }

            ROOTClassShell mainClass = new ROOTClassShell("##Shapes") { NtupleProxyPath = proxyFile.FullName };
            mainClass.Add(simple);
            var ntup = new NtupleTreeInfo() { Classes = new ROOTClassShell[] { mainClass }, ClassImplimintationFiles = new string[0] };

            var userinfo = new TTreeUserInfo() { Groups = new ArrayGroup[] { new ArrayGroup() { Name = "jets", Variables = new VariableInfo[] { new VariableInfo() { NETName = "fork", TTreeName = "fork" } } } } };

            var cg = new ClassGenerator();
            var outputFile = new FileInfo("TestCharactersInClassName.cs");
            cg.GenerateClasss(ntup, outputFile, "junk", new Dictionary<string, TTreeUserInfo>() { { "TestSimpleGroupAndRename", userinfo } });

            DumpOutputFile(outputFile);

            Assert.AreEqual(3, CountInFile(outputFile, "##Shapes"), "Missing reference ot the shapes object");
        }
Ejemplo n.º 36
0
        public void TestSimpleGroupWithCustomClassName()
        {
            /// Create simple user info - but don't do anything with it!
            ItemSimpleType simple = new ItemSimpleType("var1", "int[]");
            FileInfo proxyFile = new FileInfo("TestSimpleGroupAndRename.cpp");
            using (var writer = proxyFile.CreateText())
            {
                writer.WriteLine();
                writer.Close();
            }
            ROOTClassShell mainClass = new ROOTClassShell("TestSimpleGroupAndRename") { NtupleProxyPath = proxyFile.FullName };
            mainClass.Add(simple);
            var ntup = new NtupleTreeInfo() { Classes = new ROOTClassShell[] { mainClass }, ClassImplimintationFiles = new string[0] };

            var userinfo = new TTreeUserInfo() { Groups = new ArrayGroup[] { new ArrayGroup() { Name = "jets", ClassName = "Jet", Variables = new VariableInfo[] { new VariableInfo() { NETName = "myvar", TTreeName = "var1" } } } } };

            var cg = new ClassGenerator();
            var outputFile = new FileInfo("TestSimpleGroupAndRename.cs");
            cg.GenerateClasss(ntup, outputFile, "junk", new Dictionary<string, TTreeUserInfo>() { { "TestSimpleGroupAndRename", userinfo } });

            DumpOutputFile(outputFile);

            /// Look through this to see if we can make sure there are no renames!
            Assert.IsTrue(FindInFile(outputFile, "RenameVariable(\"var1\")"), "Rename missing!");
            Assert.IsTrue(FindInFile(outputFile, "TTreeVariableGrouping"), "Missing TTreeVariableGrouping");
            Assert.IsTrue(FindInFile(outputFile, "jets"), "missing a reference to jets");
            Assert.IsTrue(FindInFile(outputFile, "int myvar"), "myvar missing");
            Assert.IsTrue(FindInFile(outputFile, "int[] var1"), "val1 missing");
            Assert.IsFalse(FindInFile(outputFile, "ungrouped"), "group found");
            Assert.IsFalse(FindInFile(outputFile, "TestSimpleGroupAndRenamejets"), "Found the non-class name default class name");
            Assert.IsTrue(FindInFile(outputFile, "Jet"), "Did not find the Jet custom class name");
        }
Ejemplo n.º 37
0
        public void GenerateClassFromClasses(
            ClassGenerator target,
            int outputChoice,
            int numExtraFiles,
            int numExtraFilesToCreate,
            int extraFileIndexNull,
            int proxyPathChoice,
            string nameSName,
            int NumObjectCollection)
        {
            if (numExtraFiles < 0
                || numExtraFilesToCreate < 0
                || extraFileIndexNull < 0
                || outputChoice < 0
                || proxyPathChoice < 0
                || NumObjectCollection < 0)
                return;

            ///
            /// Kill off the directory we might have left behind from a previous run, and create a new one.
            /// 

            DirectoryInfo testDir = new DirectoryInfo(".\\GenerateClassFromClasses");
            if (testDir.Exists)
            {
                testDir.Delete(true);
            }
            testDir.Create();

            ///
            /// Setup the input stuff so Pex can play
            /// 

            FileInfo outputCSFile;
            if (outputChoice == 1)
            {
                outputCSFile = new FileInfo(testDir.FullName + "\\output.cs");
            }
            else
            {
                outputCSFile = null;
            }

            ROOTClassShell[] objCollect = null;
            if (NumObjectCollection > 0)
            {
                List<ROOTClassShell> objs = new List<ROOTClassShell>();

                for (int i = 0; i < NumObjectCollection; i++)
                {
                    ROOTClassShell rcs = new ROOTClassShell();
                    rcs.Name = "dude_" + i.ToString();

                    for (int j = 0; j < i; j++)
                    {
                        IClassItem item = null;
                        switch (NumObjectCollection % 4)
                        {
                            case 0:
                                item = null;
                                break;

                            case 1:
                                var itm = new ItemSimpleType() { ItemType = "int" };
                                item = itm;
                                break;

                            case 2:
                                var itmv = new ItemVector() { ItemType = "int[]" };
                                item = itmv;
                                break;

                            case 3:
                                var itmr = new ItemROOTClass() { ItemType = "TLorentzVector" };
                                item = itmr;
                                break;
                        }
                        if (item != null)
                            item.Name = "item_" + j.ToString();
                        rcs.Items.Add(item);
                    }
                    objs.Add(rcs);
                }

                if (NumObjectCollection > 0)
                {
                    if (proxyPathChoice == 1)
                    {
                        var proxyFile = new FileInfo(testDir.FullName + "\\GenerateClassFromClasses_" + proxyPathChoice.ToString() + ".h");
                        using (var w = proxyFile.CreateText())
                        {
                            w.WriteLine("hi");
                            w.Close();
                        }
                        objs[0].NtupleProxyPath = proxyFile.FullName;
                    }

                    if (proxyPathChoice == 2)
                    {
                        var proxyFile = new FileInfo(testDir.FullName + "\\GenerateClassFromClasses_" + proxyPathChoice.ToString() + ".h");
                        objs[0].NtupleProxyPath = proxyFile.FullName;
                    }

                    if (proxyPathChoice == 3)
                    {
                        var proxyFile = new FileInfo(testDir.FullName + "\\GenerateClassFromClasses_" + proxyPathChoice.ToString() + ".h");
                        using (var w = proxyFile.CreateText())
                        {
                            w.WriteLine("hi");
                            w.Close();
                        }
                        foreach (var item in objs)
                        {
                            item.NtupleProxyPath = proxyFile.FullName;
                        }
                    }
                }
                objCollect = objs.ToArray();
            }

            ///
            /// Create the final object, and any extra files needed!
            /// 

            NtupleTreeInfo info = new NtupleTreeInfo() { Classes = objCollect };

            info.ClassImplimintationFiles = (from c in Enumerable.Range(0, numExtraFiles)
                                             let f = new FileInfo(testDir.FullName + "\\GenerateClassFromClasses_extra_" + c.ToString() + ".cpp")
                                             select f.FullName
                                                 ).ToArray();

            int maxFilesToCreate = numExtraFilesToCreate > numExtraFiles ? numExtraFiles : numExtraFilesToCreate;
            for (int i = 0; i < maxFilesToCreate; i++)
            {
                using (var w = File.CreateText(info.ClassImplimintationFiles[i]))
                {
                    w.WriteLine();
                    w.Close();
                }
            }

            if (extraFileIndexNull < numExtraFiles)
            {
                info.ClassImplimintationFiles[extraFileIndexNull] = null;
            }

            ///
            /// Ok, do the investigation
            /// 

            target.GenerateClasss(info, outputCSFile, nameSName);

            Assert.IsFalse(info.Classes.Any(c => c.NtupleProxyPath == null), "No null proxy paths allowed");
            Assert.IsFalse(info.Classes.Any(c => !File.Exists(c.NtupleProxyPath)), "proxy files must exist");

            Assert.IsFalse(info.ClassImplimintationFiles.Any(c => c == null), "no null implementation files allowed");
            Assert.IsFalse(info.ClassImplimintationFiles.Any(c => !File.Exists(c)), "all implimntation files must exist");

            /// Check that all the ntuple proxy guys and the temp file guys appear in the file

            foreach (var item in info.Classes.Where(c => c.IsTopLevelClass))
            {
                Assert.IsTrue(FindInFile(outputCSFile, item.NtupleProxyPath), "Could not find the proxy path '" + item.NtupleProxyPath + "'");
            }
            foreach (var item in info.ClassImplimintationFiles)
            {
                Assert.IsTrue(FindInFile(outputCSFile, item), "coul dnot find impl file '" + item + "'");
            }
        }
Ejemplo n.º 38
0
        public void TestNonIntIndex()
        {
            /// Create simple user info - but don't do anything with it!
            ItemSimpleType simpleIndex = new ItemSimpleType("index", "float[]");
            ItemSimpleType simpleVal = new ItemSimpleType("var1", "float[]");
            FileInfo proxyFile = new FileInfo("TestNonIntIndex.cpp");
            using (var writer = proxyFile.CreateText())
            {
                writer.WriteLine();
                writer.Close();
            }
            ROOTClassShell mainClass = new ROOTClassShell("TestNonIntIndex") { NtupleProxyPath = proxyFile.FullName };
            mainClass.Add(simpleIndex);
            mainClass.Add(simpleVal);
            var ntup = new NtupleTreeInfo() { Classes = new ROOTClassShell[] { mainClass }, ClassImplimintationFiles = new string[0] };

            var userinfo = new TTreeUserInfo()
            {
                Groups = new ArrayGroup[] {
                    new ArrayGroup()
                    {
                        Name = "jets", Variables = new VariableInfo[]
                        {
                            new VariableInfo() { NETName = "index", TTreeName = "index", IndexToGroup="muons" }
                        }
                    },
                    new ArrayGroup()
                    {
                        Name = "muons", Variables = new VariableInfo[]
                        {
                            new VariableInfo() { NETName = "var1", TTreeName = "var1"}
                        }
                    }
                }
            };

            var cg = new ClassGenerator();
            var outputFile = new FileInfo("TestNonIntIndex.cs");
            cg.GenerateClasss(ntup, outputFile, "junk", new Dictionary<string, TTreeUserInfo>() { { "TestNonIntIndex", userinfo } });
        }
Ejemplo n.º 39
0
 public void TestNullNamespace()
 {
     FileInfo f = new FileInfo("junk.xml");
     ClassGenerator target = new ClassGenerator();
     target.GenerateClasss(f, f, null);
 }
Ejemplo n.º 40
0
        public void TestConstCStyleArray()
        {
            // Simple set of types for an index array
            var vArray = new ItemCStyleArray("int[]", new ItemSimpleType("arr", "int"));
            vArray.Add(0, "10", true);
            var vIndex = new ItemSimpleType("n", "int");
            FileInfo proxyFile = new FileInfo("TestConstCStyleArray.cpp");
            using (var writer = proxyFile.CreateText())
            {
                writer.WriteLine();
                writer.Close();
            }

            ROOTClassShell mainClass = new ROOTClassShell("TestSimpleRename") { NtupleProxyPath = proxyFile.FullName };
            mainClass.Add(vIndex);
            mainClass.Add(vArray);
            var ntup = new NtupleTreeInfo() { Classes = new ROOTClassShell[] { mainClass }, ClassImplimintationFiles = new string[0] };

            var userinfo = new TTreeUserInfo()
            {
                Groups = new ArrayGroup[] { new ArrayGroup() {
                Name = "ungrouped",
                Variables = new VariableInfo[] {
                    new VariableInfo() { NETName = "n", TTreeName = "n" },
                    new VariableInfo() { NETName = "arr", TTreeName = "arr"}
                } } }
            };

            var cg = new ClassGenerator();
            var outputFile = new FileInfo("TestConstCStyleArray.cs");
            cg.GenerateClasss(ntup, outputFile, "junk", new Dictionary<string, TTreeUserInfo>() { { "TestSimpleRename", userinfo } });

            CopyToOutput(outputFile);

            /// Look through this to see if we can make sure there are no renames!
            Assert.IsTrue(FindInFile(outputFile, "int[] arr"), "Array Decl missing");
            Assert.IsTrue(FindInFile(outputFile, "int n"), "Index decl missing");
            Assert.IsTrue(FindInFile(outputFile, "[ArraySizeIndex(\"10\", IsConstantExpression = true, Index = 0)]"), "Missing array size index attribute");
        }
Ejemplo n.º 41
0
        public void TestDuplicateClassNames()
        {
            var vIndex = new ItemSimpleType("n", "int");
            FileInfo proxyFile = new FileInfo("TestCStyleArray.cpp");
            using (var writer = proxyFile.CreateText())
            {
                writer.WriteLine();
                writer.Close();
            }
            ROOTClassShell mainClass = new ROOTClassShell("TestSimpleRename") { NtupleProxyPath = proxyFile.FullName };
            mainClass.Add(vIndex);

            ROOTClassShell mainClass1 = new ROOTClassShell("TestSimpleRename") { NtupleProxyPath = proxyFile.FullName };
            mainClass1.Add(vIndex);
            var ntup = new NtupleTreeInfo() { Classes = new ROOTClassShell[] { mainClass, mainClass1 }, ClassImplimintationFiles = new string[0] };

            var userinfo = new TTreeUserInfo()
            {
                Groups = new ArrayGroup[] { new ArrayGroup() {
                Name = "ungrouped",
                Variables = new VariableInfo[] {
                    new VariableInfo() { NETName = "n", TTreeName = "n" },
                } } }
            };

            var cg = new ClassGenerator();
            var outputFile = new FileInfo("TestDuplicateClassNames.cs");
            cg.GenerateClasss(ntup, outputFile, "junk", new Dictionary<string, TTreeUserInfo>() { { "TestDuplicateClassNames", userinfo } });
        }
Ejemplo n.º 42
0
 public void TestNullOutputFile()
 {
     FileInfo f = new FileInfo("junk.xml");
     ClassGenerator target = new ClassGenerator();
     target.GenerateClasss(f, null, null);
 }
Ejemplo n.º 43
0
        public void TestParseXMLOfTTreeWithInterior()
        {
            var basexml = new FileInfo("EVNT-short.ntupom");
            Assert.IsTrue(basexml.Exists, "can't find input xml file");

            using (var h = new FileInfo("ntuple_CollectionTree.h").CreateText())
            {
                h.WriteLine("hi");
                h.Close();
            }

            var t = new ClassGenerator();
            var output = new FileInfo("TestXMLParsing.cs");
            t.GenerateClasss(basexml, output, "Bogus");
            Assert.IsTrue(output.Exists, "Output file existance");
            Assert.AreEqual(3, CountInFile(output, "TClonesArrayImpliedClass"), "# of TClonesArrayImpliedClass attributes");
            Assert.AreEqual(1, CountInFile(output, "class Queryable"), "# of Queryable classes");
            Assert.AreEqual(1, CountInFile(output, ": IExpressionHolder"), "# of Expression holder classeS");
            Assert.AreEqual(0, CountInFile(output, "ArraySizeIndex"), "# of times the ArraySizeIndex method appears"); // implied for tclones array guys...
            Assert.AreEqual(40, CountInFile(output, "[NotAPointer]"), "# of NotAPointer attributes");
        }
Ejemplo n.º 44
0
 private void GenerateMethod(ClassGenerator classGenerator, MethodDescriptor descriptor, bool forceAsync)
 {
     classGenerator.WriteMethod(
         descriptor.Method,
         forceAsync,
         g =>
         {
             MethodInfo method = descriptor.Method;
             string parameters = g.FormatMethodParameters(method, false);
             if (!string.IsNullOrEmpty(parameters))
             {
                 parameters = ", " + parameters;
             }
             if (HasReturnValue(method))
             {
                 if (IsAsync(method))
                 {
                     WriteLine(
                         "return this.SendAsync<{0}>({1}{2});",
                         FormatType(method.ReturnType.GenericTypeArguments.FirstOrDefault() ?? method.ReturnType),
                         GetStaticActionName(method),
                         parameters);
                 }
                 else if (forceAsync)
                 {
                     WriteLine(
                         "return this.SendAsync<{0}>({1}{2});",
                         FormatType(method.ReturnType),
                         GetStaticActionName(method),
                         parameters);
                 }
                 else
                 {
                     WriteLine(
                         "return this.Send<{0}>({1}{2});",
                         FormatType(method.ReturnType),
                         GetStaticActionName(method),
                         parameters);
                 }
             }
             else
             {
                 if (IsAsync(method))
                 {
                     WriteLine("return this.SendAsync({0}{1});", GetStaticActionName(method), parameters);
                 }
                 else if (forceAsync)
                 {
                     WriteLine("return this.SendAsync({0}{1});", GetStaticActionName(method), parameters);
                 }
                 else
                 {
                     WriteLine("this.Send({0}{1});", GetStaticActionName(method), parameters);
                 }
             }
         });
 }
Ejemplo n.º 45
0
        public void TestCStyleArrayBadIndexName()
        {
            // Simple set of types for an index array
            var vArray = new ItemCStyleArray("int[]", new ItemSimpleType("arr", "int"));
            vArray.Add(0, "i", false);
            var vIndex = new ItemSimpleType("n", "int");
            FileInfo proxyFile = new FileInfo("TestCStyleArray.cpp");
            using (var writer = proxyFile.CreateText())
            {
                writer.WriteLine();
                writer.Close();
            }
            ROOTClassShell mainClass = new ROOTClassShell("TestSimpleRename") { NtupleProxyPath = proxyFile.FullName };
            mainClass.Add(vIndex);
            mainClass.Add(vArray);
            var ntup = new NtupleTreeInfo() { Classes = new ROOTClassShell[] { mainClass }, ClassImplimintationFiles = new string[0] };

            var userinfo = new TTreeUserInfo()
            {
                Groups = new ArrayGroup[] { new ArrayGroup() {
                Name = "ungrouped",
                Variables = new VariableInfo[] {
                    new VariableInfo() { NETName = "n", TTreeName = "n" },
                    new VariableInfo() { NETName = "arr", TTreeName = "arr"}
                } } }
            };

            var cg = new ClassGenerator();
            var outputFile = new FileInfo("TestCStyleArray.cs");
            cg.GenerateClasss(ntup, outputFile, "junk", new Dictionary<string, TTreeUserInfo>() { { "TestSimpleRename", userinfo } });
        }
Ejemplo n.º 46
0
 private void GenerateStaticActions(ClassGenerator generator)
 {
     foreach (MethodInfo effectiveMethod in ContractDefinition.GetEffectiveMethods())
     {
         generator.WriteLine(
             "private static readonly {0} {1} = typeof({2}).GetMethod(nameof({2}.{3}));",
             FormatType<MethodInfo>(),
             GetStaticActionName(effectiveMethod),
             FormatType(effectiveMethod.DeclaringType),
             effectiveMethod.Name);
     }
 }
Ejemplo n.º 47
0
        public void TestColonsInVarName()
        {
            ItemSimpleType simple = new ItemSimpleType("dude::fork", "int[]");
            FileInfo proxyFile = new FileInfo("TestColonsInVarName.cpp");
            using (var writer = proxyFile.CreateText())
            {
                writer.WriteLine();
                writer.Close();
            }

            ROOTClassShell mainClass = new ROOTClassShell("TestSimpleGroupAndRename") { NtupleProxyPath = proxyFile.FullName };
            mainClass.Add(simple);
            var ntup = new NtupleTreeInfo() { Classes = new ROOTClassShell[] { mainClass }, ClassImplimintationFiles = new string[0] };

            var userinfo = new TTreeUserInfo() { Groups = new ArrayGroup[] { new ArrayGroup() { Name = "jets", Variables = new VariableInfo[] { new VariableInfo() { NETName = "dude::fork", TTreeName = "dude::fork" } } } } };

            var cg = new ClassGenerator();
            var outputFile = new FileInfo("TestSimpleGroupAndRename.cs");
            cg.GenerateClasss(ntup, outputFile, "junk", new Dictionary<string, TTreeUserInfo>() { { "TestSimpleGroupAndRename", userinfo } });

            DumpOutputFile(outputFile);

            /// Look through this to see if we can make sure there are no renames!
            Assert.IsFalse(FindInFile(outputFile, "dude::fork"), "Saw the double colon!!");
            Assert.IsTrue(FindInFile(outputFile, "dude__fork"), "Missing the variable!!");
        }
Ejemplo n.º 48
0
        public void TestRenamedIndex()
        {
            /// Create simple user info - but don't do anything with it!
            ItemSimpleType simpleIndex = new ItemSimpleType("index", "int[]");
            ItemSimpleType simpleVal = new ItemSimpleType("var1", "float[]");
            FileInfo proxyFile = new FileInfo("TestRenamedIndex.cpp");
            using (var writer = proxyFile.CreateText())
            {
                writer.WriteLine();
                writer.Close();
            }
            ROOTClassShell mainClass = new ROOTClassShell("TestRenamedIndex") { NtupleProxyPath = proxyFile.FullName };
            mainClass.Add(simpleIndex);
            mainClass.Add(simpleVal);
            var ntup = new NtupleTreeInfo() { Classes = new ROOTClassShell[] { mainClass }, ClassImplimintationFiles = new string[0] };

            var userinfo = new TTreeUserInfo()
            {
                Groups = new ArrayGroup[] {
                    new ArrayGroup()
                    {
                        Name = "jets", Variables = new VariableInfo[]
                        {
                            new VariableInfo() { NETName = "muons", TTreeName = "index", IndexToGroup="muons" }
                        }
                    },
                    new ArrayGroup()
                    {
                        Name = "muons", Variables = new VariableInfo[]
                        {
                            new VariableInfo() { NETName = "var1", TTreeName = "var1"}
                        }
                    }
                }
            };

            var cg = new ClassGenerator();
            var outputFile = new FileInfo("TestRenamedIndex.cs");
            cg.GenerateClasss(ntup, outputFile, "junk", new Dictionary<string, TTreeUserInfo>() { { "TestRenamedIndex", userinfo } });

            DumpOutputFile(outputFile);

            /// Look through this to see if we can make sure there are no renames!
            Assert.IsTrue(FindInFile(outputFile, "TTreeVariableGrouping"), "Missing TTreeVariableGrouping");
            Assert.IsTrue(FindInFile(outputFile, "jets"), "missing a reference to jets");
            Assert.IsTrue(FindInFile(outputFile, "muons"), "missing a reference to jets");
            Assert.IsTrue(FindInFile(outputFile, "IndexToOtherObjectArray(typeof("), "Missing IndexToOtherObject");
            Assert.IsTrue(FindInFile(outputFile, "TestRenamedIndexmuons muons"), "Muon reference is imporper");
            Assert.IsTrue(FindInFile(outputFile, "float var1"), "var1 missing");
            Assert.IsFalse(FindInFile(outputFile, "ungrouped"), "group found");
        }
Ejemplo n.º 49
0
        public void GroupWithArrayLengthSpecification()
        {
            ItemSimpleType simple1 = new ItemSimpleType("avar", "int[]");
            ItemSimpleType simple2 = new ItemSimpleType("bvar", "int[]");
            FileInfo proxyFile = new FileInfo("TestColonsInVarNameWRename.cpp");
            using (var writer = proxyFile.CreateText())
            {
                writer.WriteLine();
                writer.Close();
            }

            ROOTClassShell mainClass = new ROOTClassShell("GroupWithArrayLengthSpecification") { NtupleProxyPath = proxyFile.FullName };
            mainClass.Add(simple1);
            mainClass.Add(simple2);
            var ntup = new NtupleTreeInfo() { Classes = new ROOTClassShell[] { mainClass }, ClassImplimintationFiles = new string[0] };

            var userinfo = new TTreeUserInfo() { Groups = new ArrayGroup[] {
                new ArrayGroup() {
                    Name = "jets",
                    NETNameOfVariableToUseAsArrayLength ="b",
                    Variables = new VariableInfo[] {
                        new VariableInfo() { NETName = "a", TTreeName = "avar" },
                        new VariableInfo() { NETName = "b", TTreeName = "bvar" },
                    }
                } } };

            var cg = new ClassGenerator();
            var outputFile = new FileInfo("GroupWithArrayLengthSpecification.cs");
            cg.GenerateClasss(ntup, outputFile, "junk", new Dictionary<string, TTreeUserInfo>() { { "GroupWithArrayLengthSpecification", userinfo } });

            DumpOutputFile(outputFile);

            /// Look through this to see if we can make sure there are no renames!
            Assert.IsTrue(FindInFile(outputFile, "UseAsArrayLength"), "Missing the UseAsArrayLength attribute!!");
        }
Ejemplo n.º 50
0
 public void TestNullInputFile()
 {
     ClassGenerator target = new ClassGenerator();
     target.GenerateClasss((FileInfo)null, null, null);
 }
Ejemplo n.º 51
0
        public static void ReadCodeGenerator(List<FiledPropObject> list, string realName, string pre, string TemplateVOType)
        {
            string filename = EditorConfig.Instance.CodeGenarateReaderPath + pre + "/" + realName;
            ClassGenerator generator = new ClassGenerator("Game.Template", realName);
            generator.AddBaseType("ITemplateReader");
            //generator.AddImport("System.Collections.Generic");
            List<CodeStatement> CodeStatementList = new List<CodeStatement>();

            CodeParameterDeclarationExpression par = new CodeParameterDeclarationExpression(typeof(byte[]), "bytes");
            List<CodeParameterDeclarationExpression> pList = new List<CodeParameterDeclarationExpression>();
            pList.Add(par);

            CodeStatementList.Add(
                new CodeVariableDeclarationStatement(typeof(ByteArray), "data",
                    new CodeObjectCreateExpression(typeof(ByteArray),
                        new CodeVariableReferenceExpression("bytes"))));

            CodeStatementList.Add(
                new CodeVariableDeclarationStatement(typeof(List<object>), "list",
                    new CodeObjectCreateExpression(typeof(List<object>))));

            //length
            CodeStatementList.Add(
                new CodeVariableDeclarationStatement(typeof(int), "length",
                    new CodeVariableReferenceExpression("data.ReadInt()")));

            //for
            CodeIterationStatement forExp = new CodeIterationStatement();
            // 初始化  
            forExp.InitStatement = new CodeVariableDeclarationStatement(typeof(int), "i",
                new CodePrimitiveExpression(0));
            // 递增条件  
            forExp.IncrementStatement = new CodeAssignStatement(
                new CodeVariableReferenceExpression("i"),
                new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression("i"),
                    CodeBinaryOperatorType.Add,
                    new CodePrimitiveExpression(1)));
            // 测试表达式  
            forExp.TestExpression = new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("i"),
                CodeBinaryOperatorType.LessThan,
                new CodeVariableReferenceExpression("length"));
            forExp.Statements.Add(
                     new CodeVariableDeclarationStatement(TemplateVOType, "vo",
                         new CodeObjectCreateExpression(TemplateVOType)));

            for (int i = 0; i < list.Count; i++)
            {
                forExp.Statements.Add(
                    new CodeAssignStatement(
                        new CodeVariableReferenceExpression(
                            "vo." + list[i].name),
                            new CodeMethodInvokeExpression(
                                new CodeTypeReferenceExpression("data"),
                                GetByteArrayMethodName(list[i].type, pre))));
            }

            forExp.Statements.Add(new CodeVariableReferenceExpression("list.Add(vo)"));


            CodeStatementList.Add(forExp);

            //return
            CodeStatementList.Add(
                new CodeMethodReturnStatement(
                    new CodeVariableReferenceExpression("list")));

            generator.AddMethod("GenerateByteArray", pList, CodeStatementList, typeof(List<object>), MemberAttributes.Public | MemberAttributes.Final);
            generator.Generate(filename + ".cs");
        }
Ejemplo n.º 52
0
        public void TestNoGroups()
        {
            /// Create simple user info - but don't do anything with it!
            ItemSimpleType simple = new ItemSimpleType("var1", "int[]");
            Assert.IsFalse(simple.NotAPointer, "not a pointer");
            FileInfo proxyFile = new FileInfo("TestNoGroupsProxy.cpp");
            using (var writer = proxyFile.CreateText())
            {
                writer.WriteLine();
                writer.Close();
            }
            ROOTClassShell mainClass = new ROOTClassShell("TestSimpleRename") { NtupleProxyPath = proxyFile.FullName };
            mainClass.Add(simple);
            var ntup = new NtupleTreeInfo() { Classes = new ROOTClassShell[] { mainClass }, ClassImplimintationFiles = new string[0] };

            var userinfo = new TTreeUserInfo() { Groups = new ArrayGroup[] { new ArrayGroup() { Name = "ungrouped", Variables = new VariableInfo[] { new VariableInfo() { NETName = "var1", TTreeName = "var1" } } } } };

            var cg = new ClassGenerator();
            var outputFile = new FileInfo("TestNoGroups.cs");
            cg.GenerateClasss(ntup, outputFile, "junk", new Dictionary<string, TTreeUserInfo>() { { "TestSimpleRename", userinfo } });

            /// Look through this to see if we can make sure there are no renames!
            Assert.IsFalse(FindInFile(outputFile, "RenameVariable"), "We saw a rename!");
            Assert.IsFalse(FindInFile(outputFile, "ungrouped"), "group found");
        }
Ejemplo n.º 53
0
        /// <summary>
        /// Generates the appropriate class given some options.
        /// </summary>
        /// <param name="options">The options.</param>
        /// <param name="classOptions">The options for classes.</param>
        /// <returns>
        /// A <see cref="KeyValuePair"/> where the first element is the source 
        /// string and the second element is the set of attributes.
        /// </returns>
        /// 
        /// TODO: Abstract with a wrapper type wrapping around KeyValuePair.
        public static KeyValuePair<string, IReadOnlyDictionary<string, string>> Generate(SourceOptions options = SourceOptions.None, ClassOptions classOptions = ClassOptions.None)
        {
            ClassGenerator classes = new ClassGenerator()
            {
                Name = Name
            };

            // Class with many interfaces
            if (options.HasFlag(SourceOptions.ImplementsInterfaces) &&
                options.HasFlag(SourceOptions.BaseListMany))
            {
                classes.Interface1Name = Interface1Name;
                classes.Interface2Name = Interface2Name;
                classes.Interface3Name = Interface3Name;
                return new KeyValuePair<string, IReadOnlyDictionary<string, string>>(
                    classes.ClassWithManyInterfaces, classes.ClassWithManyInterfacesAttributes);
            }

            // Class with interface
            if (options.HasFlag(SourceOptions.ImplementsInterfaces))
            {
                classes.Interface1Name = Interface1Name;
                return new KeyValuePair<string, IReadOnlyDictionary<string, string>>(
                    classes.ClassWith1Interface, classes.ClassWith1InterfaceAttributes);
            }

            // Class with base class
            if (options.HasFlag(SourceOptions.HasInheritance))
            {
                classes.BaseClassName = BaseName;
                return new KeyValuePair<string, IReadOnlyDictionary<string, string>>(
                    classes.ClassWithBaseClass, classes.ClassWithBaseClassAttributes);
            }

            // Empty elements
            if (options.HasFlag(SourceOptions.EmptyElements))
            {
                return new KeyValuePair<string, IReadOnlyDictionary<string, string>>(
                    classes.VerySimpleClassWithEmptyMethods, classes.VerySimpleClassWithEmptyMethodsAttributes);
            }

            // Namespace
            if (options.HasFlag(SourceOptions.HasNamespace))
            {
                classes.NamespaceName = NamespaceName;
                return new KeyValuePair<string, IReadOnlyDictionary<string, string>>(
                    classes.VerySimpleClassInNamespace, classes.VerySimpleClassInNamespaceAttributes);
            }

            // Simple class
            if (classOptions.HasFlag(ClassOptions.HasContent))
            {
                return new KeyValuePair<string, IReadOnlyDictionary<string, string>>(
                classes.SimpleClass, classes.SimpleClassAttributes);
            }
            return new KeyValuePair<string, IReadOnlyDictionary<string, string>>(
                classes.VerySimpleClass, classes.VerySimpleClassAttributes);
        }
Ejemplo n.º 54
0
        public static void DictionaryGenerator(string realName, Type type, Type subType, Type dataType)
        {
            string filename = EditorConfig.Instance.CodeGenarateDataDicPath + realName;
            ClassGenerator generator = new ClassGenerator("Game.Template", realName + "Dictionary");
            generator.AddBaseType("ITemplateDictionary");
            generator.AddImport("UnityEngine");
            //generator.AddImport("System.Collections.Generic");

            List<CodeStatement> CodeStatementList = new List<CodeStatement>();

            generator.AddProperty("Item List", type, null);
            generator.AddProperty("Item Dic", dataType, null);

            CodeParameterDeclarationExpression par = new CodeParameterDeclarationExpression(typeof(List<object>), "list");
            List<CodeParameterDeclarationExpression> pList = new List<CodeParameterDeclarationExpression>();
            pList.Add(par);
            CodeStatementList.Add(new CodeAssignStatement(
                new CodeVariableReferenceExpression("_itemlist"),
                new CodeObjectCreateExpression(type)));

            CodeStatementList.Add(
                new CodeVariableDeclarationStatement(typeof(int), "length",
                    new CodeVariableReferenceExpression("list.Count")));

            //for
            CodeIterationStatement forExp = new CodeIterationStatement();
            // 初始化  
            forExp.InitStatement = new CodeVariableDeclarationStatement(typeof(int), "i",
                new CodePrimitiveExpression(0));
            // 递增条件  
            forExp.IncrementStatement = new CodeAssignStatement(
                new CodeVariableReferenceExpression("i"),
                new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression("i"),
                    CodeBinaryOperatorType.Add,
                    new CodePrimitiveExpression(1)));
            // 测试表达式  
            forExp.TestExpression = new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("i"),
                CodeBinaryOperatorType.LessThan,
                new CodeVariableReferenceExpression("length"));
            forExp.Statements.Add(
                     new CodeExpressionStatement(
                        new CodeMethodInvokeExpression(
                            new CodeTypeReferenceExpression("_itemlist"), "Add",
                            new CodeVariableReferenceExpression("list[i] as " + subType))));

            CodeStatementList.Add(forExp);

            CodeStatementList.Add(
                new CodeExpressionStatement(
                        new CodeMethodInvokeExpression(
                            new CodeThisReferenceExpression(), "InitDictionary")));

            generator.AddMethod("Init", pList, CodeStatementList, null, MemberAttributes.Public | MemberAttributes.Final);

            CodeStatementList.Clear();

            //for
            forExp = new CodeIterationStatement();
            // 初始化  
            forExp.InitStatement = new CodeVariableDeclarationStatement(typeof(int), "i",
                new CodePrimitiveExpression(0));
            // 递增条件  
            forExp.IncrementStatement = new CodeAssignStatement(
                new CodeVariableReferenceExpression("i"),
                new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression("i"),
                    CodeBinaryOperatorType.Add,
                    new CodePrimitiveExpression(1)));
            // 测试表达式  
            forExp.TestExpression = new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("i"),
                CodeBinaryOperatorType.LessThan,
                new CodeVariableReferenceExpression("length"));

            CodeTryCatchFinallyStatement myTrycafly = new CodeTryCatchFinallyStatement();
            // try  
            myTrycafly.TryStatements.Add(new CodeExpressionStatement(
                        new CodeMethodInvokeExpression(
                            new CodeTypeReferenceExpression("_itemdic"), "Add",
                            new CodeVariableReferenceExpression("_itemlist[i].id"),
                            new CodeVariableReferenceExpression("_itemlist[i]"))));
            // catch  
            myTrycafly.CatchClauses.Add(new CodeCatchClause(
                "ex", new CodeTypeReference(typeof(Exception)),
                new CodeExpressionStatement(
                    new CodeMethodInvokeExpression(
                        new CodeTypeReferenceExpression("Debug"),
                        "LogWarning",
                        new CodeVariableReferenceExpression("ex.Message")))));
            forExp.Statements.Add(myTrycafly);

            CodeStatementList.Add(
                new CodeVariableDeclarationStatement(typeof(int), "length",
                    new CodeVariableReferenceExpression("_itemlist.Count")));

            par = new CodeParameterDeclarationExpression(dataType, "_itemdic");
            pList = new List<CodeParameterDeclarationExpression>();
            pList.Add(par);
            CodeStatementList.Add(new CodeAssignStatement(
                new CodeVariableReferenceExpression("_itemdic"),
                new CodeObjectCreateExpression(dataType)));

            CodeStatementList.Add(forExp);

            generator.AddMethod("InitDictionary", null, CodeStatementList, null, MemberAttributes.Private);
            generator.Generate(filename + "Dictionary.cs");
            Debug.Log("Code generator completed : " + realName + "Dictionary.cs");
        }