示例#1
0
        public void InvalidDictionaryKeyHandling()
        {
            //Generate a basic javascript model from a C# class

            var modelType = typeof(DictionaryKeyTesting);


            var codeRanThrough = false;

            try
            {
                JsGenerator.Generate(new[] { modelType }, new JsGeneratorOptions()
                {
                    ClassNameConstantsToRemove = null,
                    CamelCase                    = true,
                    IncludeMergeFunction         = false,
                    OutputNamespace              = "models",
                    RespectDataMemberAttribute   = false,
                    RespectDefaultValueAttribute = false
                });

                codeRanThrough = true;
            }
            catch (Exception)
            {
                Assert.Pass();
            }

            if (codeRanThrough)
            {
                Assert.Fail("Expected exception generating type with incompatible dictionary key type.");
            }
        }
示例#2
0
        public void CollectionHandling()
        {
            //Generate a basic javascript model from a C# class

            var modelType = typeof(CollectionTesting);

            var outputJs = JsGenerator.Generate(new[] { modelType }, new JsGeneratorOptions()
            {
                ClassNameConstantsToRemove = new List <string>()
                {
                    "Dto"
                },
                CamelCase                    = true,
                IncludeMergeFunction         = true,
                OutputNamespace              = "models",
                RespectDataMemberAttribute   = true,
                RespectDefaultValueAttribute = true
            });

            Assert.IsTrue(!string.IsNullOrEmpty(outputJs));

            var js = new Jint.Parser.JavaScriptParser();



            try
            {
                js.Parse(outputJs);
            }
            catch (Exception ex)
            {
                Assert.Fail("Expected no exception parsing javascript, but got: " + ex.Message);
            }
        }
示例#3
0
        public void BasicGenerationWithOptions()
        {
            //Generate a basic javascript model from a C# class

            var modelType = typeof(AddressInformation);

            var outputJs = JsGenerator.Generate(new[] { modelType }, new JsGeneratorOptions()
            {
                ClassNameConstantsToRemove = new List <string>()
                {
                    "Dto"
                },
                CamelCase             = true,
                IncludeMergeFunction  = false,
                OutputNamespace       = "models",
                IncludeEqualsFunction = true
            });

            Assert.IsTrue(!string.IsNullOrEmpty(outputJs));

            var js = new Jint.Parser.JavaScriptParser();

            try
            {
                js.Parse(outputJs);
            }
            catch (Exception ex)
            {
                Assert.Fail("Expected no exception parsing javascript, but got: " + ex.Message);
            }
        }
示例#4
0
        private void btnGenerate_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                ShowFileMissingErrorMessage();
                return;
            }

            try
            {
                // String which contains whole file contents
                string fileContent = FileContentUtil.GetFileContent(filePath);

                // Get option values for generator options
                JsGeneratorOptions options = GetOptions();

                // Create compiler and execute content of file
                Assembly asm = BuildAssemblyUtil.CompileCode(fileContent);

                // Get all types from assembly using reflection
                List <Type> rawTypes = BuildAssemblyUtil.GetExportedTypes(asm);

                // Filter types, and take only parent ones (the ones that are not referenced in parent, and standalone one)
                // If referenced children will be generated automatically, so no need to duplicate stuff.
                List <Type> types = BuildAssemblyUtil.FilterExportedTypes(rawTypes);

                // Finally generate
                StringBuilder sbFinal = new StringBuilder();
                foreach (Type type in types)
                {
                    switch (options.ConversionType)
                    {
                    case EGenerateOptions.Javascript:
                        sbFinal.AppendLine(JsGenerator.Generate(new[] { type }, options));
                        break;

                    case EGenerateOptions.Ecma6:
                        sbFinal.AppendLine(Ecma6Generator.Generate(new[] { type }, options));
                        break;

                    case EGenerateOptions.KnockoutEcma6:
                        sbFinal.AppendLine(Ecma6KnockoutGenerator.Generate(new[] { type }, options));
                        break;

                    default:
                        throw new Exception(
                                  "Somehow Conversion type is not set or is out of bounds. I have no idea what happened.");
                    }
                }

                codeTextEditor.Text = sbFinal.ToString();
            }
            catch (Exception exception)
            {
                // Since we presumably should know what we are doing here, we are just showing message from exception
                // Would be good idea to log this somewhere tho.
                ShowErrorMessage(exception.Message);
            }
        }
示例#5
0
        //REVIEW: put code in different class
        private static string GenerateGameCode(string json)
        {
            var model     = DeserializeJson(json);
            var generator = new JsGenerator(Application.PresetModules);
            var code      = generator.GenerateGameCode(model);

            return(code);
        }
示例#6
0
        public void ShouldCompileProperly()
        {
            var generator = new JsGenerator(new ITermJsGenerator[] { new SimpleTermDefinitionJsGenerator(), new ComplexTermDefinitionJsGenerator() });
            var generated = generator.Generate(TestTerms.Terms, this.Culture);

            this.jsExecutor = new JsExecutor("var testTerms = new class {\n" + generated + "\n}();");

            this.Assertions();
        }
        public static string GetJavaScriptPoco(this Type type, JsGeneratorOptions options, bool addModelArray = false)
        {
            var poco = JsGenerator.Generate(new[] { type }, options);

            if (addModelArray)
            {
                return(AddModels(poco));
            }
            return(poco);
        }
        public static string GetTypeScriptPocos(this IEnumerable <Type> types, JsGeneratorOptions options, bool addModelArray = false)
        {
            var poco = JsGenerator.Generate(types, options);

            if (addModelArray)
            {
                return(AddModels(poco));
            }
            return(poco);
        }
示例#9
0
        public void EqualsDictionaryHandling()
        {
            //Generate a basic javascript model from a C# class

            var modelType = typeof(CollectionTesting);

            var outputJs = JsGenerator.Generate(new[] { modelType }, new JsGeneratorOptions()
            {
                ClassNameConstantsToRemove = new List <string>()
                {
                    "Dto"
                },
                CamelCase                    = true,
                IncludeMergeFunction         = true,
                OutputNamespace              = "models",
                RespectDataMemberAttribute   = true,
                RespectDefaultValueAttribute = true,
                IncludeEqualsFunction        = true
            });

            Assert.IsTrue(!string.IsNullOrEmpty(outputJs));


            var js = new Jint.Parser.JavaScriptParser();



            try
            {
                js.Parse(outputJs);
            }
            catch (Exception ex)
            {
                Assert.Fail("Expected no exception parsing javascript, but got: " + ex.Message);
            }

            var strToExecute = "this.models = {};\r\n" + outputJs + ";\r\n" + $"var p1 = new models.CollectionTesting({{ dictionaryCollection: {{ 'Prop1' : 'Test' }} }});\r\n" +
                               $"var p2 = new models.CollectionTesting({{ dictionaryCollection: {{ 'Prop1' : 'Test' }} }});\r\n" +
                               $"var result = p1.$equals(p2);";

            var jsEngine = new Jint.Engine().Execute(strToExecute);
            var res      = (bool)jsEngine.GetValue("result").ToObject();

            Assert.IsTrue(res);

            var strToExecuteNotEqual = "this.models = {};\r\n" + outputJs + ";\r\n" + $"var p1 = new models.CollectionTesting({{ dictionaryCollection: {{ 'Prop1' : 'Test' }} }});\r\n" +
                                       $"var p2 = new models.CollectionTesting({{ dictionaryCollection: {{ 'Prop1' : 'Test2' }} }});\r\n" +
                                       $"var result = p1.$equals(p2);";

            var jsEngineNotEqual = new Jint.Engine().Execute(strToExecuteNotEqual);
            var resNotEqual      = (bool)jsEngineNotEqual.GetValue("result").ToObject();

            Assert.IsFalse(resNotEqual);
        }
        public static string GetJavaScriptPoco(this Type type, bool addModelArray = false)
        {
            var poco = JsGenerator.Generate(new[] { type }, new JsGeneratorOptions
            {
                CamelCase             = true,
                IncludeMergeFunction  = false,
                IncludeEqualsFunction = false
            });

            if (addModelArray)
            {
                return(AddModels(poco));
            }
            return(poco);
        }
        public static string GetJavaScriptPocos(this IEnumerable <Type> types, bool addModelArray = false)
        {
            var poco = JsGenerator.Generate(types, new JsGeneratorOptions
            {
                CamelCase             = true,
                IncludeMergeFunction  = false,
                IncludeEqualsFunction = false
            });

            if (addModelArray)
            {
                return(AddModels(poco));
            }
            return(poco);
        }
示例#12
0
        public void CustomFunctionHandling()
        {
            //Generate a basic javascript model from a C# class

            var modelType = typeof(CollectionTesting);

            var outputJs = JsGenerator.Generate(new[] { modelType }, new JsGeneratorOptions()
            {
                ClassNameConstantsToRemove = new List <string>()
                {
                    "Dto"
                },
                CamelCase                    = true,
                IncludeMergeFunction         = true,
                OutputNamespace              = "models",
                RespectDataMemberAttribute   = true,
                RespectDefaultValueAttribute = true,
                CustomFunctionProcessors     =
                    new List <Action <StringBuilder, IEnumerable <PropertyBag>, JsGeneratorOptions> >()
                {
                    (builder, bags, arg3) =>
                    {
                        builder.AppendLine($"\tthis.helloWorld = function () {{");
                        builder.AppendLine("\t\tconsole.log('hello');");
                        builder.AppendLine("\t}");
                    }
                }
            });



            Assert.IsTrue(!string.IsNullOrEmpty(outputJs));

            Assert.IsTrue(outputJs.Contains("this.helloWorld"));

            var js = new Jint.Parser.JavaScriptParser();



            try
            {
                js.Parse(outputJs);
            }
            catch (Exception ex)
            {
                Assert.Fail("Expected no exception parsing javascript, but got: " + ex.Message);
            }
        }
示例#13
0
        public void FatalStateHandling()
        {
            //Generate a basic javascript model from a C# class

            var modelType   = typeof(AttributeInformationTest);
            var tempOptions = JsGenerator.Options;

            JsGenerator.Options = null;

            Assert.Catch <ArgumentNullException>((() =>
            {
                var outputJs = JsGenerator.Generate(new[] { modelType });
            }), "Expected engine to throw ArguementNullException when Options are null");

            JsGenerator.Options = tempOptions;
        }
示例#14
0
        static void Main(string[] args)
        {
            //var a = new {a = new DbSetting(), pi = new ProjectMeta()};
            //JntTemplateApp.Render("x", a);

            JsGenerator.Run(args);

//            var tmp = @"$a.Name
//    $a.Age
//";
//            var t = (Template) JinianNet.JNTemplate.Engine.CreateTemplate(tmp);
//            t.Set("a", new { Name = "tester", Age = 15 });
//            var rst = t.Render();


            Console.WriteLine(@"press any key to close.");
            Console.ReadKey();
        }
示例#15
0
        public string LoadPublishedGame(string gameName)
        {
            string path = Path.Combine(Application.RootPath, PathFinder.GetPublishedGamePath(gameName));
            if (!File.Exists(path))
            {
                throw new FileNotFoundException();
            }
            using (StreamReader reader = new StreamReader(path))
            {
                GameModel model = GameModel.Load(GameModel.SupportedSaveFormats.Xml, reader);
                var generator = new JsGenerator(Application.PresetModules);
                var code = generator.GenerateGameCode(model);

                string scriptPath = PathFinder.GetGameFilePath();
                File.WriteAllText(Path.Combine(Application.RootPath, scriptPath), code);
                return scriptPath;
            }
        }
示例#16
0
        public string LoadPublishedGame(string gameName)
        {
            string path = Path.Combine(Application.RootPath, PathFinder.GetPublishedGamePath(gameName));

            if (!File.Exists(path))
            {
                throw new FileNotFoundException();
            }
            using (StreamReader reader = new StreamReader(path))
            {
                GameModel model     = GameModel.Load(GameModel.SupportedSaveFormats.Xml, reader);
                var       generator = new JsGenerator(Application.PresetModules);
                var       code      = generator.GenerateGameCode(model);

                string scriptPath = PathFinder.GetGameFilePath();
                File.WriteAllText(Path.Combine(Application.RootPath, scriptPath), code);
                return(scriptPath);
            }
        }
示例#17
0
        public void RecursiveTypeGenerationLegacy()
        {
            //Generate a basic javascript model from a C# class

            var modelType = typeof(RecursiveTest);

            var outputJs = JsGenerator.GenerateJsModelFromTypeWithDescendants(modelType, true, "castle");

            Assert.IsTrue(!string.IsNullOrEmpty(outputJs));

            var js = new Jint.Parser.JavaScriptParser();

            try
            {
                js.Parse(outputJs);
            }
            catch (Exception ex)
            {
                Assert.Fail("Expected no exception parsing javascript, but got: " + ex.Message);
            }
        }
示例#18
0
        public void BasicGeneration()
        {
            //Generate a basic javascript model from a C# class

            var modelType = typeof(AddressInformation);

            var outputJs = JsGenerator.Generate(new[] { modelType });

            Assert.IsTrue(!string.IsNullOrEmpty(outputJs));

            var js = new Jint.Parser.JavaScriptParser();

            try
            {
                js.Parse(outputJs);
            }
            catch (Exception ex)
            {
                Assert.Fail("Expected no exception parsing javascript, but got: " + ex.Message);
            }
        }
示例#19
0
        public void BasicGenerationLegacy()
        {
            //Generate a basic javascript model from a C# class

            var modelType = typeof(AddressInformation);

#pragma warning disable 618
            var outputJs = JsGenerator.GenerateJsModelFromTypeWithDescendants(modelType, true, "castle");
#pragma warning restore 618

            Assert.IsTrue(!string.IsNullOrEmpty(outputJs));

            var js = new Jint.Parser.JavaScriptParser();

            try
            {
                js.Parse(outputJs);
            }
            catch (Exception ex)
            {
                Assert.Fail("Expected no exception parsing javascript, but got: " + ex.Message);
            }
        }
示例#20
0
        private void CodeForm_Load(object sender, EventArgs e)
        {
            // Restore position from registry.
            RegistryKey twbstStudioRegKey = Registry.CurrentUser.OpenSubKey("Software\\Codecentrix\\OpenTwebst\\Studio");

            // If Twebst Studio registry key does not exist then create it.
            if (twbstStudioRegKey == null)
            {
                twbstStudioRegKey = Registry.CurrentUser.CreateSubKey("Software\\Codecentrix\\OpenTwebst\\Studio");
            }

            if (twbstStudioRegKey != null)
            {
                int top    = (int)twbstStudioRegKey.GetValue("codex", -1);
                int left   = (int)twbstStudioRegKey.GetValue("codey", -1);
                int height = (int)twbstStudioRegKey.GetValue("codeh", -1);
                int width  = (int)twbstStudioRegKey.GetValue("codew", -1);

                if ((top != -1) && (left != -1) && (height != -1) && (width != -1) &&
                     IsValidFormPosAndSize(top, left, height, width))
                {
                    this.Top = top;
                    this.Left = left;
                    this.Height = height;
                    this.Width = width;
                }
                else
                {
                    this.GoDefaultPosAndSize();
                }

                twbstStudioRegKey.Close();
            }
            else
            {
                this.GoDefaultPosAndSize();
            }

            // Create target language objects.
            BaseLanguageGenerator vbsLang    = new VbsGenerator();
            BaseLanguageGenerator jsLang     = new JsGenerator();
            BaseLanguageGenerator pythonLang = new PyGenerator();
            BaseLanguageGenerator watirEnv   = new WatirGenerator();
            BaseLanguageGenerator csLang     = new CSharpGenerator();
            BaseLanguageGenerator vbNetLang  = new VbNetGenerator();
            BaseLanguageGenerator vbaLang    = new VbaGenerator();

            // Populate language combo-box.
            this.codeToolStripLanguageCombo.Items.Add(vbsLang);
            this.codeToolStripLanguageCombo.Items.Add(jsLang);
            this.codeToolStripLanguageCombo.Items.Add(vbaLang);
            this.codeToolStripLanguageCombo.Items.Add(csLang);
            this.codeToolStripLanguageCombo.Items.Add(vbNetLang);
            this.codeToolStripLanguageCombo.Items.Add(pythonLang);
            this.codeToolStripLanguageCombo.Items.Add(watirEnv);

            // Initialize code generator.
            this.codeGen = new CodeGenerator(vbsLang);
            this.codeGen.NewStatement += OnNewStatement;
            this.codeGen.CodeChanged  += OnLanguageChanged;

            // Select a language in the combo-box.
            int defaultLanguage = GetRecorderSavedLanguage();
            if ((defaultLanguage < 0) || (defaultLanguage >= this.codeToolStripLanguageCombo.Items.Count))
            {
                defaultLanguage = 0;
            }

            this.codeToolStripLanguageCombo.SelectedIndex = defaultLanguage;

            this.codeToolStrip.ClickThrough = true;
            this.toolStripStatusProductLabel.Text = CoreWrapper.Instance.productName + " " + CoreWrapper.Instance.productVersion;
        }
示例#21
0
 //REVIEW: put code in different class
 private static string GenerateGameCode(string json)
 {
     var model = DeserializeJson(json);
     var generator = new JsGenerator(Application.PresetModules);
     var code = generator.GenerateGameCode(model);
     return code;
 }
示例#22
0
        public void CamelCaseHandling()
        {
            //Generate a basic javascript model from a C# class

            var modelType = typeof(CamelCaseTest);

            var outputJs = JsGenerator.Generate(new[] { modelType }, new JsGeneratorOptions()
            {
                ClassNameConstantsToRemove = new List <string>()
                {
                    "Dto"
                },
                CamelCase                    = true,
                IncludeMergeFunction         = false,
                OutputNamespace              = "models",
                RespectDataMemberAttribute   = true,
                RespectDefaultValueAttribute = true
            });

            Assert.IsTrue(!string.IsNullOrEmpty(outputJs));

            var js = new Jint.Parser.JavaScriptParser();

            Program res = null;

            try
            {
                res = js.Parse(outputJs);
            }
            catch (Exception ex)
            {
                Assert.Fail("Expected no exception parsing javascript, but got: " + ex.Message);
            }


            var classExpression = res.Body.First().As <ExpressionStatement>();

            var functionDefinition =
                classExpression.Expression.As <AssignmentExpression>().Right.As <FunctionExpression>()
                .Body.As <BlockStatement>()
                .Body;

            var firstMemberDefinition =
                functionDefinition.Skip(1)
                .Take(1)
                .First()
                .As <ExpressionStatement>()
                .Expression.As <AssignmentExpression>();

            var memberName = firstMemberDefinition.Left.As <MemberExpression>().Property.As <Identifier>().Name;

            Assert.IsTrue(memberName == "wktPolygon");

            var secondMemberDefinition =
                functionDefinition.Skip(2)
                .Take(1)
                .First()
                .As <ExpressionStatement>()
                .Expression.As <AssignmentExpression>();

            var secondMemberName = secondMemberDefinition.Left.As <MemberExpression>().Property.As <Identifier>().Name;

            Assert.IsTrue(secondMemberName == "alreadyUnderscored");

            var thirdMemberDefinition =
                functionDefinition.Skip(3)
                .Take(1)
                .First()
                .As <ExpressionStatement>()
                .Expression.As <AssignmentExpression>();

            var thirdMemberName = thirdMemberDefinition.Left.As <MemberExpression>().Property.As <Identifier>().Name;

            Assert.IsTrue(thirdMemberName == "regularCased");
        }