Ejemplo n.º 1
0
        void PasteJson(Clipboard c, string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                InsertCSharp(string.Empty);
                return;
            }

            var gen = new JsonClassGenerator {
                Example       = text,
                MainClass     = "RootObject",
                UseProperties = true,
                CodeWriter    = new CSharpCodeWriter()
            };

            try {
                using (var sw = new StringWriter()) {
                    gen.OutputStream = sw;
                    gen.GenerateClasses();
                    sw.Flush();
                    var generatedString = sw.ToString();
                    InsertCSharp(generatedString);
                }
            } catch (Exception ex) {
                Console.WriteLine(ex.Message);
                MessageService.ShowWarning(string.Format("Invalid JSON: {0}", ex.Message));
            }

            gen = null;
        }
Ejemplo n.º 2
0
        private void GenerateCSharp()
        {
            this.copyOutput.Enabled = false;

            String jsonText = this.jsonInputTextbox.Text;

            if (String.IsNullOrWhiteSpace(jsonText))
            {
                this.csharpOutputTextbox.Text = String.Empty;
                return;
            }

            JsonClassGenerator generator = new JsonClassGenerator();

            this.ConfigureGenerator(generator);

            try
            {
                StringBuilder sb = generator.GenerateClasses(jsonText, errorMessage: out String errorMessage);
                if (!String.IsNullOrWhiteSpace(errorMessage))
                {
                    this.csharpOutputTextbox.Text = "Error:\r\n" + errorMessage;
                }
                else
                {
                    this.csharpOutputTextbox.Text = sb.ToString();
                    this.copyOutput.Enabled       = true;
                }
            }
            catch (Exception ex)
            {
                this.csharpOutputTextbox.Text = "Error:\r\n" + ex.ToString();
            }
        }
        public void Run()
        {
            Assert.Inconclusive(message: "This test is not yet implemented.");
            return;

            string           path = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_8_LargeArrayOfObjects_INPUT.txt"; string resultPath = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_8_LargeArrayOfObjects_OUTPUT.txt";
            string           input            = File.ReadAllText(path);
            string           errorMessage     = string.Empty;
            CSharpCodeWriter csharpCodeWriter = new CSharpCodeWriter();

            Stopwatch watch = new Stopwatch();

            watch.Start();

            JsonClassGenerator jsonClassGenerator = new JsonClassGenerator();

            jsonClassGenerator.CodeWriter = csharpCodeWriter;
            string returnVal = jsonClassGenerator.GenerateClasses(input, out errorMessage).ToString();

            watch.Stop();

            var seconds = watch.ElapsedMilliseconds / 1000;

            Assert.IsTrue(false);

            string resultsCompare = File.ReadAllText(resultPath);
            //Assert.AreEqual(resultsCompare.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\t", ""), returnVal.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\t", ""));
        }
Ejemplo n.º 4
0
        public string Build(string json, string rootClass)
        {
            var gen = new JsonClassGenerator();

            gen.Example            = json;//"{\"someprop\":\"HELLO\"}";
            gen.InternalVisibility = false;
            gen.CodeWriter         = new CSharpCodeWriter();
            //gen.ExplicitDeserialization =  && gen.CodeWriter is CSharpCodeWriter;
            gen.Namespace     = "TEST";
            gen.NoHelperClass = false;
            //gen.SecondaryNamespace = radDifferentNamespace.Checked && !string.IsNullOrEmpty(edtSecondaryNamespace.Text) ? edtSecondaryNamespace.Text : null;
            //gen.TargetFolder = edtTargetFolder.Text;
            gen.UseProperties              = true;      //radProperties.Checked;
            gen.MainClass                  = rootClass; //"DefaultClass";//edtMainClass.Text;
            gen.UsePascalCase              = true;
            gen.UseNestedClasses           = false;
            gen.ApplyObfuscationAttributes = false;
            gen.SingleFile                 = false;
            gen.TargetFolder               = @"C:\Projects\Other\ARestedDevelopment\ARested.Tests\SampleFiles\Gen";
            gen.ExamplesInDocumentation    = false;

            var stream = new MemoryStream();

            gen.OutputStream = new StreamWriter(stream, Encoding.UTF8);

            gen.GenerateClasses();
            gen.OutputStream.Flush();

            stream.Position = 0;
            TextReader reader = new StreamReader(stream);

            var text = reader.ReadToEnd();

            return(text);
        }
Ejemplo n.º 5
0
        private static string GenerateClassFromJsonArray(string arr)
        {
            using (var ms = new MemoryStream())
            {
                using (var tw = new StreamWriter(ms))
                {
                    var hash = Math.Abs(arr.GetHashCode());

                    var mrj = new ModelRuntime();
                    mrj.ClassName = "Data" + hash;

                    var gen = new JsonClassGenerator();
                    gen.Example                 = arr;
                    gen.InternalVisibility      = false;
                    gen.CodeWriter              = new CSharpCodeWriter();
                    gen.ExplicitDeserialization = false;
                    gen.Namespace               = null;

                    gen.NoHelperClass              = true;
                    gen.SecondaryNamespace         = null;
                    gen.TargetFolder               = null;
                    gen.UseProperties              = true;
                    gen.MainClass                  = mrj.ClassName;
                    gen.UsePascalCase              = false;
                    gen.UseNestedClasses           = true;
                    gen.ApplyObfuscationAttributes = false;
                    gen.SingleFile                 = true;
                    gen.ExamplesInDocumentation    = false;
                    gen.OutputStream               = tw;
                    gen.GenerateClasses();
                }
                return(Encoding.ASCII.GetString(ms.ToArray()));
            }
        }
Ejemplo n.º 6
0
        public Task GenerateClassFromDocument()
        {
            var id   = GetStringQueryString("id");
            var lang = (GetStringQueryString("lang", required: false) ?? "csharp")
                       .Trim().ToLowerInvariant();

            using (ContextPool.AllocateOperationContext(out DocumentsOperationContext context))
                using (context.OpenReadTransaction())
                {
                    var document = Database.DocumentsStorage.Get(context, id);
                    if (document == null)
                    {
                        HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
                        return(Task.CompletedTask);
                    }

                    switch (lang)
                    {
                    case "csharp":
                        break;

                    default:
                        throw new NotImplementedException($"Document code generator isn't implemented for {lang}");
                    }

                    using (var writer = new StreamWriter(ResponseBodyStream()))
                    {
                        var codeGenerator = new JsonClassGenerator(lang);
                        var code          = codeGenerator.Execute(document);
                        writer.Write(code);
                    }

                    return(Task.CompletedTask);
                }
        }
Ejemplo n.º 7
0
        // POST: api/Entity
        public IHttpActionResult Post([FromBody] Entity entity)
        {
            try
            {
                var classGenerator = new JsonClassGenerator();
                classGenerator.MainClass = entity.Name;
                classGenerator.Example   = entity.Json;

                var project = string.IsNullOrEmpty(entity.Project) ? "Global" : entity.Project;

                classGenerator.Namespace    = project + "." + Config.Models;
                classGenerator.TargetFolder = Path.Combine(Config.ProjectRepository, project, Config.Models);
                Directory.CreateDirectory(classGenerator.TargetFolder);
                classGenerator.UseProperties = true;
                classGenerator.UsePascalCase = true;
                if (entity.EnableDB)
                {
                    classGenerator.GenerateIdField = true;
                }

                var entities = classGenerator.GenerateClasses();

                if (entity.EnableDB)
                {
                    addDBContext(entity.Project, entities);
                }

                return(Ok("Entity created successfully"));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
Ejemplo n.º 8
0
        private static void GenerateBatch(BatchOptions o)
        {
            if (File.Exists(o.ConfigFile))
            {
                var configJson = File.OpenText(o.ConfigFile).ReadToEnd();
                var batch      = JsonConvert.DeserializeObject <JsonClassGenConfig>(configJson);

                foreach (var config in batch.Classes)
                {
                    var fi = new FileInfo(o.ConfigFile);
                    config.Filename = fi.Directory.FullName + Path.DirectorySeparatorChar + config.Filename;
                    if (File.Exists(config.Filename))
                    {
                        var json         = File.OpenText(config.Filename).ReadToEnd();
                        var info         = new FileInfo(config.Filename);
                        var targetFolder = info.Directory.FullName;

                        JsonClassGenerator gen = new JsonClassGenerator()
                        {
                            Namespace          = config.Namespace,
                            Example            = json,
                            InternalVisibility = batch.Options.Internalvisibility,
                            SingleFile         = batch.Options.Singlefile,
                            UsePascalCase      = batch.Options.Pascal,
                            UseProperties      = batch.Options.Useproperties,
                            TargetFolder       = targetFolder,
                            MainClass          = config.Mainclass,
                            UseNestedClasses   = batch.Options.Nested
                        };
                        Console.WriteLine("Generating: " + config.Namespace + "." + config.Mainclass);
                        gen.GenerateClasses();
                    }
                }
            }
        }
Ejemplo n.º 9
0
        public void Run2()
        {
            string path       = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_11_NoListSetter_INPUT1.txt";
            string resultPath = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_11_NoListSetter_OUTPUT1.txt";
            string input      = File.ReadAllText(path);

            CSharpCodeWriter   csharpCodeWriter   = new CSharpCodeWriter();
            JsonClassGenerator jsonClassGenerator = new JsonClassGenerator()
            {
                MutableClasses =
                {
                    ReadOnlyCollectionProperties = true
                },
                CollectionType   = OutputCollectionType.Array,
                AttributeLibrary = JsonLibrary.SystemTextJson,
                AttributeUsage   = JsonPropertyAttributeUsage.Always,
                UsePascalCase    = true
            };

            jsonClassGenerator.CodeWriter = csharpCodeWriter;
            string returnVal      = jsonClassGenerator.GenerateClasses(input, out string errorMessage).ToString();
            string resultsCompare = File.ReadAllText(resultPath);

            Assert.AreEqual(expected: resultsCompare.NormalizeOutput(), actual: returnVal.NormalizeOutput());
            Assert.AreEqual(string.Empty, errorMessage);
        }
        public async Task <IActionResult> Get(Json2CSharpPostRequestDto vm)
        {
            try
            {
                var gen = new JsonClassGenerator();
                gen.UsePascalCase = vm.UsePascalCase;
                gen.UseProperties = vm.UseProperties;
                gen.Example       = vm.Example;
                gen.MainClass     = "MyJsonObject";

                gen.GenerateClasses();
                var csharpCodeWriter = new CSharpCodeWriter();
                var resultWriter     = new StringWriter();
                csharpCodeWriter.WriteFileStart(gen, resultWriter);
                foreach (var type in gen.Types)
                {
                    csharpCodeWriter.WriteClass(gen, resultWriter, type);
                }
                csharpCodeWriter.WriteFileEnd(gen, resultWriter);

                return(Ok(new Json2CSharpPostResponseDto()
                {
                    Result = resultWriter.ToString()
                }));
            }
            catch (Exception e)
            {
                return(BadRequest());
            }
        }
        public void Run()
        {
            string path       = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_4_BracketError_INPUT.txt";
            string resultPath = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_4_BracketError_OUTPUT.txt";

            string             input              = File.ReadAllText(path);
            string             errorMessage       = string.Empty;
            CSharpCodeWriter   csharpCodeWriter   = new CSharpCodeWriter();
            JsonClassGenerator jsonClassGenerator = new JsonClassGenerator();

            jsonClassGenerator.CodeWriter = csharpCodeWriter;
            string returnVal      = jsonClassGenerator.GenerateClasses(input, out errorMessage).ToString();
            string resultsCompare = File.ReadAllText(resultPath);

            Assert.AreEqual(resultsCompare.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\t", ""), returnVal.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\t", ""));

            string             path1               = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_4_BracketError_INPUT_1.txt";
            string             resultPath1         = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_4_BracketError_OUTPUT_1.txt";
            string             input1              = File.ReadAllText(path1);
            string             errorMessage1       = string.Empty;
            CSharpCodeWriter   csharpCodeWriter1   = new CSharpCodeWriter();
            JsonClassGenerator jsonClassGenerator1 = new JsonClassGenerator();

            jsonClassGenerator1.CodeWriter = csharpCodeWriter1;
            string returnVal1      = jsonClassGenerator1.GenerateClasses(input1, out errorMessage1).ToString();
            string resultsCompare1 = File.ReadAllText(resultPath1);

            Assert.AreEqual(resultsCompare1.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\t", ""), returnVal1.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\t", ""));
        }
Ejemplo n.º 12
0
    private static JsonClassGenerator Prepare(string _jsonData, string _csharpPath, string _csName)
    {
        if (_jsonData == string.Empty)
        {
            Debug.Log("Please insert some sample JSON.");
            return(null);
        }

        JsonClassGenerator gen = new JsonClassGenerator();

        gen.Example                    = _jsonData;
        gen.InternalVisibility         = false;
        gen.CodeWriter                 = new CSharpCodeWriter();
        gen.ExplicitDeserialization    = false;
        gen.Namespace                  = "HuanJueGameData";
        gen.NoHelperClass              = true;
        gen.SecondaryNamespace         = null;
        gen.TargetFolder               = _csharpPath;
        gen.UseProperties              = true;
        gen.MainClass                  = "Cfg" + _csName;
        gen.UsePascalCase              = false;
        gen.UseNestedClasses           = false;
        gen.ApplyObfuscationAttributes = false;
        gen.SingleFile                 = true;
        gen.ExamplesInDocumentation    = false;
        return(gen);
    }
Ejemplo n.º 13
0
    private JsonClassGenerator Prepare(string json)
    {
        var gen = new JsonClassGenerator();

        gen.Example            = json;
        gen.InternalVisibility = !Jconfigure.isPublic;

        gen.CodeWriter = new CSharpCodeWriter();
        gen.ExplicitDeserialization = false;



        gen.Namespace = Jconfigure.nameSpace;



        gen.NoHelperClass = true;
        //	gen.SecondaryNamespace =  Jconfigure.nameSpace;

        gen.TargetFolder               = Jconfigure.outputFolder;
        gen.UseProperties              = !Jconfigure.isFields;
        gen.MainClass                  = Jconfigure.mainClassName;
        gen.UsePascalCase              = false;
        gen.UseNestedClasses           = false;
        gen.ApplyObfuscationAttributes = false;
        gen.SingleFile                 = Jconfigure.isGenerateSingleFile;
        gen.ExamplesInDocumentation    = false;
        return(gen);
    }
Ejemplo n.º 14
0
        private JsonClassGenerator Prepare()
        {
            if (edtJson.Text == string.Empty)
            {
                MessageBox.Show(this, "Please insert some sample JSON.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                edtJson.Focus();
                return(null);
            }


            if (edtMainClass.Text == string.Empty)
            {
                MessageBox.Show(this, "Please specify a main class name.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(null);
            }

            var gen = new JsonClassGenerator();

            gen.Example                    = edtJson.Text;
            gen.InternalVisibility         = radInternal.Checked;
            gen.CodeWriter                 = (ICodeWriter)cmbLanguage.SelectedItem;
            gen.ExplicitDeserialization    = chkExplicitDeserialization.Checked && gen.CodeWriter is CSharpCodeWriter;
            gen.Namespace                  = string.IsNullOrEmpty(edtNamespace.Text) ? null : edtNamespace.Text;
            gen.NoHelperClass              = chkNoHelper.Checked;
            gen.SecondaryNamespace         = radDifferentNamespace.Checked && !string.IsNullOrEmpty(edtSecondaryNamespace.Text) ? edtSecondaryNamespace.Text : null;
            gen.TargetFolder               = edtTargetFolder.Text;
            gen.UseProperties              = radProperties.Checked;
            gen.MainClass                  = edtMainClass.Text;
            gen.UsePascalCase              = chkPascalCase.Checked;
            gen.UseNestedClasses           = radNestedClasses.Checked;
            gen.ApplyObfuscationAttributes = chkApplyObfuscationAttributes.Checked;
            gen.SingleFile                 = chkSingleFile.Checked;
            gen.ExamplesInDocumentation    = chkDocumentationExamples.Checked;
            return(gen);
        }
Ejemplo n.º 15
0
        private string Prepare(string code, string ns, string mainClass)
        {
            var gen = new JsonClassGenerator();

            gen.Example = code;
            TextWriter txtStream = new StringWriter();

            gen.OutputStream = txtStream;
            //gen.InternalVisibility = this.radInternal.Checked;
            gen.CodeWriter = new TypeScriptCodeWriter();

            gen.Namespace = ns;
            //gen.NoHelperClass = this.chkNoHelper.Checked;
            //gen.SecondaryNamespace = this.radDifferentNamespace.Checked && !string.IsNullOrEmpty(this.edtSecondaryNamespace.Text) ? this.edtSecondaryNamespace.Text : null;
            //gen.TargetFolder = this.edtTargetFolder.Text;
            //gen.UseProperties = true;
            gen.MainClass = mainClass;
            //gen.UsePascalCase = false;
            gen.UseNestedClasses = true; //this.radNestedClasses.Checked;
            //gen.ApplyObfuscationAttributes = this.chkApplyObfuscationAttributes.Checked;
            gen.SingleFile = true;       //this.chkSingleFile.Checked;
            //gen.ExamplesInDocumentation = true;
            gen.GenerateClasses();
            return(txtStream.ToString());
        }
Ejemplo n.º 16
0
        public static void Main(string[] args)
        {
            string pathToJson        = args[0];
            string pathToClass       = args[1];
            string namespaceName     = args[2];
            bool   useNullableValues = false;

            if (args.Length > 3)
            {
                useNullableValues = bool.Parse(args[3]);
            }

            string json       = File.ReadAllText(pathToJson);
            string folderPath = Path.GetDirectoryName(pathToClass);
            string className  = Path.GetFileNameWithoutExtension(pathToClass);

            JsonClassGenerator generator = new JsonClassGenerator();

            generator.Example                 = json;
            generator.TargetFolder            = folderPath;
            generator.MainClass               = className;
            generator.Namespace               = namespaceName;
            generator.AlwaysUseNullableValues = useNullableValues;
            generator.SingleFile              = true;
            // Set UseNestedClasses to false because it doesn't work...
            generator.UseNestedClasses = false;
            generator.UseProperties    = true;
            generator.UsePascalCase    = true;
            generator.GenerateClasses();
        }
Ejemplo n.º 17
0
        public JsonResult OnPost()
        {
            APIRequest apiRequest = new APIRequest();

            if (Request.Form.ContainsKey("UsePascalCase"))
            {
                var resultWriter     = new StringWriter();
                var csharpCodeWriter = new CSharpCodeWriter();
                try
                {
                    Json2CSharpPostRequestDto vm = new Json2CSharpPostRequestDto();
                    vm.UsePascalCase      = bool.Parse(Request.Form["UsePascalCase"]);
                    vm.UseProperties      = bool.Parse(Request.Form["UseProperties"]);
                    vm.EscapedDoubleQuote = bool.Parse(Request.Form["EscapedDoubleQuote"]);

                    if (vm.EscapedDoubleQuote)
                    {
                        //Unescape double quote
                        vm.Example = Request.Form["Example"].ToString().Replace("\\\"", "\"");
                    }
                    else
                    {
                        vm.Example = Request.Form["Example"];
                    }

                    var gen = new JsonClassGenerator();
                    gen.UsePascalCase = vm.UsePascalCase;
                    gen.UseProperties = vm.UseProperties;
                    gen.Example       = vm.Example;
                    gen.MainClass     = "MyJsonObject";

                    gen.GenerateClasses();


                    csharpCodeWriter.WriteFileStart(gen, resultWriter);
                    foreach (var type in gen.Types)
                    {
                        csharpCodeWriter.WriteClass(gen, resultWriter, type);
                    }
                    csharpCodeWriter.WriteFileEnd(gen, resultWriter);

                    apiRequest.status = 0;
                    apiRequest.data   = resultWriter.ToString();
                }
                catch (Exception ex)
                {
                    apiRequest.status   = -1;
                    apiRequest.debugmsg = ex.Message;
                }
            }
            else
            {
                //invalid request
                apiRequest.status  = -1;
                apiRequest.message = "Invalid Request";
            }

            return(new JsonResult(apiRequest));
        }
Ejemplo n.º 18
0
        static void Main(string[] args)
        {
            string json = "{ \"name\":\"runoob\", \"alexa\":10000, \"site\":null }";

            string classCode = JsonClassGenerator.GenerateString(json, CodeLanguage.CSharp);

            Console.WriteLine(classCode);
            Console.ReadLine();
        }
Ejemplo n.º 19
0
    public static bool Json2CSharp(string _jsonPath, string _csharpPath)
    {
        Encoding encoding = Encoding.UTF8;

        DirectoryInfo folder = new DirectoryInfo(_jsonPath);

        FileSystemInfo[] files = folder.GetFileSystemInfos();
        int length             = files.Length;

        for (int index = 0; index < length; index++)
        {
            if (files[index].Name.EndsWith(".json"))
            {
                string csName = files[index].Name;
                csName = csName.Substring(0, csName.LastIndexOf("."));

                string csContent = "";
                using (StreamReader textReader = new StreamReader(files[index].FullName, Encoding.UTF8))
                {
                    string str = textReader.ReadToEnd();//读取文件
                    csContent = str;
                    textReader.Close();
                }

                JsonClassGenerator gen = Prepare(csContent, _csharpPath, csName);
                if (gen == null)
                {
                    return(false);
                }

                try
                {
                    gen.GenerateClasses();
                }
                catch (Exception ex)
                {
                    Debug.Log("Unable to generate the code: " + ex.Message);
                    return(false);
                }


                //				//写入文件
                //				using (FileStream fileStream = new FileStream(_csharpPath + "/" + csName + ".cs", FileMode.Create, FileAccess.Write))
                //				{
                //					using (TextWriter textWriter = new StreamWriter(fileStream, encoding))
                //					{
                //						textWriter.Write(csContent);
                //					}
                //				}
            }
        }
        return(true);
    }
Ejemplo n.º 20
0
        public void GenerateClasses(string nameSpace)
        {
            try
            {
                var className = Name.SanitiseClassName();

                var finalNamespace = nameSpace + "." + className + "Input";
                var outputStream   = new MemoryStream();
                var outputWriter   = new StreamWriter(outputStream);

                var jsg = new JsonClassGenerator
                {
                    Example                = Json,
                    Namespace              = finalNamespace,
                    MainClass              = className,
                    OutputStream           = outputWriter,
                    NoHelperClass          = true,
                    UseProperties          = true,
                    GeneratePartialClasses = true
                };

                jsg.GenerateClasses();

                outputWriter.Flush();
                outputStream.Seek(0, SeekOrigin.Begin);

                var classDef = new StreamReader(outputStream)
                               .ReadToEnd()
                               .Replace("IList<", "List<");

                classDef =
                    classDef.Substring(classDef.IndexOf(String.Format("namespace {0}", nameSpace),
                                                        StringComparison.Ordinal));

                NamespacesToAdd.Add(finalNamespace);

                _generatedClass = new JsonTextGeneratedClass(this)
                {
                    Namespace       = finalNamespace,
                    ClassName       = className,
                    ClassDefinition = classDef,
                    Success         = true
                };
            }
            catch (Exception e)
            {
                _generatedClass = new JsonTextGeneratedClass(this)
                {
                    Success = false,
                    Error   = e
                };
            }
        }
Ejemplo n.º 21
0
        public void TestDoohickey()
        {
            var    transformed = Transformer.GetMethodList(_data);
            string str         = "/users/register/{search}";

            var parameterList = str.Split('/')
                                .Where(x => x.Contains("{") && x.Contains("}"))
                                .Select(x => x.Replace("{", "").Replace("}", ""))
                                .ToList();

            var ctor    = string.Join(", ", parameterList.Select(x => string.Format("string {0}", x)));
            var assign  = parameterList.Select(x => string.Format("{0} = {1};", Helpers.NeatTitleCase(x), x));
            var methods =
                parameterList.Select(
                    x =>
                    string.Format("[JsonProperty(\"{2}\")]\r\npublic string {0} {{ {1} }}", Helpers.NeatTitleCase(x),
                                  "get; set;", x));

            //str = string.Join("", str.Split('/').Select(x => x.Length > 0 ? x.Substring(0, 1).ToUpper() + x.Substring(1) : "")) + "Request";
            var res =
                str.Split('/')
                .Where(x => x.Contains("{") && x.Contains("}"))
                .Select(x => x.Replace("{", "").Replace("}", ""))
                .ToList();
            var item = Enum.GetName(typeof(HttpStatusCode), 200);

            foreach (var i in transformed)
            {
                foreach (var s in i.Responses)
                {
                    var generator = new JsonClassGenerator();
                    using (var ms = new MemoryStream())
                    {
                        using (var sw = new StreamWriter(ms))
                        {
                            generator.OutputStream  = sw;
                            generator.Example       = s.Json;
                            generator.UsePascalCase = true;
                            generator.UseProperties = true;
                            generator.MainClass     = "MyRequest";
                            generator.GenerateClasses();
                            sw.Flush();
                            ms.Position = 0;
                            using (var sr = new StreamReader(ms))
                            {
                                var result = sr.ReadToEnd();
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 22
0
        public void GenerateClassFromJson()
        {
            var json   = "{\"next\":\"https://api.robinhood.com/options/orders/?cursor=cD0yMDE5LTA0LTIyKzE3JTNBMzElM0E1Ni44MjQzNzYlMkIwMCUzQTAw\",\"previous\":null,\"results\":[{\"cancel_url\":null,\"canceled_quantity\":\"0.00000\",\"created_at\":\"2020-02-28T17:55:05.955191Z\",\"direction\":\"credit\",\"id\":\"e2d8dc8d-6637-469c-9b27-61499069d300\",\"legs\":[{\"executions\":[{\"id\":\"5bba6932-93c7-4e77-91ee-c3da36106f73\",\"price\":\"$6.85000000\",\"quantity\":\"2.00000\",\"settlement_date\":\"2020-03-02\",\"timestamp\":\"2020-02-28T21:00:00.059000Z\"},{\"id\":\"c730e53c-eaf8-4b30-b258-344ff7d3bf21\",\"price\":\"$6.85000000\",\"quantity\":\"2.00000\",\"settlement_date\":\"2020-03-02\",\"timestamp\":\"2020-02-28T21:02:17.765000Z\"},{\"id\":\"2da9a6b4-61a8-4726-a42d-e43c68333b0b\",\"price\":\"6.85000000\",\"quantity\":\"6.00000\",\"settlement_date\":\"2020-03-02\",\"timestamp\":\"2020-02-28T21:02:17.773000Z\"},{\"id\":\"e202d522-0eb9-4932-8323-c030368a20eb\",\"price\":\"6.85000000\",\"quantity\":\"2.00000\",\"settlement_date\":\"2020-03-02\",\"timestamp\":\"2020-02-28T21:02:17.609000Z\"}],\"id\":\"c91e3aed-ace2-488b-9cb6-19acc8e64b44\",\"option\":\"https://api.robinhood.com/options/instruments/2de556d4-fde0-43a3-83bf-9ff8aaa41d46/\",\"position_effect\":\"close\",\"ratio_quantity\":1,\"side\":\"sell\"}],\"pending_quantity\":\"0.00000\",\"premium\":\"685.00000000\",\"processed_premium\":\"8220.00000000000000000\",\"price\":\"6.85000000\",\"processed_quantity\":\"12.00000\",\"quantity\":\"12.00000\",\"ref_id\":\"560047e3-a3ee-47a6-858e-17c5cab67bc7\",\"state\":\"filled\",\"time_in_force\":\"gfd\",\"trigger\":\"immediate\",\"type\":\"limit\",\"updated_at\":\"2020-02-28T21:02:18.447276Z\",\"chain_id\":\"c277b118-58d9-4060-8dc5-a3b5898955cb\",\"chain_symbol\":\"SPY\",\"response_category\":\"success\",\"opening_strategy\":null,\"closing_strategy\":\"long_call\",\"stop_price\":null}]}";
            var result = new JsonClassGenerator
            {
                Settings = new JsonClassGeneratorSettings {
                    RootName = "MarketdataOptions"
                }
            }.FromString(json);

            Console.WriteLine(result);
            Console.WriteLine(Jsonizer.Format(json));
        }
        public void Run()
        {
            string             path               = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_5_BASIC_SCENARIO_INPUT.txt";
            string             resultPath         = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_5_BASIC_SCENARIO_OUTPUT.txt";
            string             input              = File.ReadAllText(path);
            string             errorMessage       = string.Empty;
            CSharpCodeWriter   csharpCodeWriter   = new CSharpCodeWriter();
            JsonClassGenerator jsonClassGenerator = new JsonClassGenerator();
            string             returnVal          = jsonClassGenerator.GenerateClasses(input, out errorMessage).ToString();
            string             resultsCompare     = File.ReadAllText(resultPath);

            Assert.AreEqual(resultsCompare.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\t", ""), returnVal.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\t", ""));
        }
Ejemplo n.º 24
0
        static int Main(string[] args)
        {
            var parameters = new OptionSet
            {
                { "?|help", "display help information", help => _showHelp = !String.IsNullOrWhiteSpace(help) },
                { "n|namespace=", "the namespace for the generated classes", n => _namespace = n },
                { "c|class=", "the main class name", cn => _mainClassName = cn },
                { "t|target=", "the target output folder", output => _targetFolder = output },
                { "p|pascal", "use PascalCase", pc => _pascalCase = !string.IsNullOrWhiteSpace(pc) },
                { "sf|single", "generate a single file", sf => _singleFile = !string.IsNullOrWhiteSpace(sf) },
                { "i|input=", "input json file to process", json => _inputFilename = json }
            };

            try
            {
                parameters.Parse(args);
            }
            catch (Exception)
            {
                ShowHelp(parameters);
                return(1);
            }

            if (_showHelp)
            {
                ShowHelp(parameters);
                return(0);
            }

            var jsonFile = File.ReadAllText(_inputFilename);

            var gen = new JsonClassGenerator
            {
                Namespace     = _namespace,
                TargetFolder  = _targetFolder,
                MainClass     = _mainClassName,
                UsePascalCase = _pascalCase,
                SingleFile    = _singleFile,
                Example       = jsonFile
            };

            using (var sw = new StringWriter())
            {
                gen.OutputStream = sw;
                gen.GenerateClasses();
                sw.Flush();
            }

            return(0);
        }
        public void Run()
        {
            string             path = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_2_CHECK_RESERVED_KEYWORDS_INPUT.txt"; string resultPath = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_2_CHECK_RESERVED_KEYWORDS_OUTPUT.txt";
            string             input              = File.ReadAllText(path);
            string             errorMessage       = string.Empty;
            CSharpCodeWriter   csharpCodeWriter   = new CSharpCodeWriter();
            JsonClassGenerator jsonClassGenerator = new JsonClassGenerator();

            jsonClassGenerator.CodeWriter = csharpCodeWriter;
            string returnVal      = jsonClassGenerator.GenerateClasses(input, out errorMessage).ToString();
            string resultsCompare = File.ReadAllText(resultPath);

            Assert.AreEqual(resultsCompare.NormalizeOutput(), returnVal.NormalizeOutput());
        }
Ejemplo n.º 26
0
        public void Run()
        {
            string             path = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_1_6_SETTINGS_JSONPROPERTYNAME_NETCORE_INPUT.txt"; string resultPath = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_1_6_SETTINGS_JSONPROPERTYNAME_NETCORE_OUTPUT.txt";
            string             input              = File.ReadAllText(path);
            string             errorMessage       = string.Empty;
            CSharpCodeWriter   csharpCodeWriter   = new CSharpCodeWriter();
            JsonClassGenerator jsonClassGenerator = new JsonClassGenerator();

            jsonClassGenerator.CodeWriter          = csharpCodeWriter;
            jsonClassGenerator.UseJsonPropertyName = true;
            string returnVal      = jsonClassGenerator.GenerateClasses(input, out errorMessage).ToString();
            string resultsCompare = File.ReadAllText(resultPath);

            Assert.AreEqual(resultsCompare.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\t", ""), returnVal.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\t", ""));
        }
        public void AddJsonAttribute()
        {
            string             path               = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_3_SETTINGS_INPUT.txt";
            string             resultPath         = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_3_SETTINGS_OUTPUT.txt";
            string             input              = File.ReadAllText(path);
            string             errorMessage       = string.Empty;
            JavaCodeWriter     javaCodeWriter     = new JavaCodeWriter();
            JsonClassGenerator jsonClassGenerator = new JsonClassGenerator();

            jsonClassGenerator.CodeWriter = javaCodeWriter;
            string returnVal      = jsonClassGenerator.GenerateClasses(input, out errorMessage).ToString();
            string resultsCompare = File.ReadAllText(resultPath);

            Assert.AreEqual(resultsCompare.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\t", ""), returnVal.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\t", ""));
        }
Ejemplo n.º 28
0
        public async Task GenerateClassFromJsonUrl()
        {
            using var client = new HttpClient();
            var json = await client.GetStringAsync("https://api.fda.gov/download.json");

            var result = new JsonClassGenerator
            {
                Settings = new JsonClassGeneratorSettings {
                    RootName = "FdaDownloadModel"
                }
            }.FromString(json);

            Console.WriteLine(result);
            Console.WriteLine(Jsonizer.Format(json));
        }
        public void Run_2()
        {
            string path1       = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_4_BracketError_INPUT_1.txt";
            string resultPath1 = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_4_BracketError_OUTPUT_1.txt";
            string input1      = File.ReadAllText(path1);

            CSharpCodeWriter   csharpCodeWriter1   = new CSharpCodeWriter();
            JsonClassGenerator jsonClassGenerator1 = new JsonClassGenerator();

            jsonClassGenerator1.CodeWriter = csharpCodeWriter1;

            string returnVal1      = jsonClassGenerator1.GenerateClasses(input1, out string errorMessage1).ToString();
            string resultsCompare1 = File.ReadAllText(resultPath1);

            Assert.AreEqual(resultsCompare1.NormalizeOutput(), returnVal1.NormalizeOutput());
        }
        public void Run()
        {
            string path       = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_1_3_SETTINGS_FIELDS_INPUT.txt";
            string resultPath = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_1_3_SETTINGS_FIELDS_OUTPUT.txt";
            string input      = File.ReadAllText(path);

            CSharpCodeWriter   csharpCodeWriter   = new CSharpCodeWriter();
            JsonClassGenerator jsonClassGenerator = new JsonClassGenerator();

            jsonClassGenerator.CodeWriter             = csharpCodeWriter;
            jsonClassGenerator.MutableClasses.Members = OutputMembers.AsPublicFields;

            string returnVal      = jsonClassGenerator.GenerateClasses(input, out string errorMessage).ToString();
            string resultsCompare = File.ReadAllText(resultPath);

            Assert.AreEqual(resultsCompare.NormalizeOutput(), returnVal.NormalizeOutput());
        }
Ejemplo n.º 31
0
        private JsonClassGenerator Prepare()
        {
            if (edtJson.Text == string.Empty)
            {
                MessageBox.Show(this, "Please insert some sample JSON.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                edtJson.Focus();
                return null;
            }


            if (edtMainClass.Text == string.Empty)
            {
                MessageBox.Show(this, "Please specify a main class name.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return null;
            }

            var gen = new JsonClassGenerator();
            gen.Example = edtJson.Text;
            gen.InternalVisibility = radInternal.Checked;
            gen.CodeWriter = (ICodeWriter)cmbLanguage.SelectedItem;
            gen.ExplicitDeserialization = chkExplicitDeserialization.Checked && gen.CodeWriter is CSharpCodeWriter;
            gen.Namespace = string.IsNullOrEmpty(edtNamespace.Text) ? null : edtNamespace.Text;
            gen.NoHelperClass = chkNoHelper.Checked;
            gen.SecondaryNamespace = radDifferentNamespace.Checked && !string.IsNullOrEmpty(edtSecondaryNamespace.Text) ? edtSecondaryNamespace.Text : null;
            gen.TargetFolder = edtTargetFolder.Text;
            gen.UseProperties = radProperties.Checked;
            gen.MainClass = edtMainClass.Text;
            gen.UsePascalCase = chkPascalCase.Checked;
            gen.UseNestedClasses = radNestedClasses.Checked;
            gen.ApplyObfuscationAttributes = chkApplyObfuscationAttributes.Checked;
            gen.SingleFile = chkSingleFile.Checked;
            gen.ExamplesInDocumentation = chkDocumentationExamples.Checked;
            return gen;
        }