private static JToken GenerateToken(JSchema schema, JObject oldObj, JObject existing = null)
        {
            if (existing == null)
            {
                existing = JsonGenerator.Generate(schema) as JObject;
            }

            if (schema.OneOf.Count > 0)
            {
                foreach (var oneOf in schema.OneOf)
                {
                    foreach (var key in oneOf.Required)
                    {
                        if (oldObj.ContainsKey(key))
                        {
                            var val = oldObj[key].ToString();
                            var s   = oneOf.Properties[key].Const?.ToString();

                            if (val == s)
                            {
                                var newToken = JsonGenerator.Generate(oneOf) as JObject;
                                existing.Merge(newToken, new JsonMergeSettings()
                                {
                                    MergeArrayHandling = MergeArrayHandling.Union
                                });

                                return(GenerateToken(oneOf, oldObj, existing));
                            }
                        }
                    }
                }
            }

            return(existing);
        }
예제 #2
0
        public static TransformationContext GetContext([NotNull] string path, [NotNull, ItemNotNull] IEnumerable <string> files)
        {
            TransformationContext context = null;
            var references = new[] { Path.Combine(Directory.GetCurrentDirectory(), "TestDll.dll") };
            //Generate(
            //string workingDirectory, string[] sourceFiles, string[] references,
            // string deploymentScriptHeader, string deploymentToolPath, bool isMethodTypingEnabled, Lazy< TextWriter > output, string transformatorOutput, TransfomationFunc transformatorOpt, bool isTestMode, BooleanMarshalMode booleanMarshalMode, string jsonSchemaType);
            var compilerMessages = JsonGenerator.Generate(
                path,
                files.ToArray(),
                references: references,
                deploymentScriptHeader: "",
                deploymentToolPath: "",
                isMethodTypingEnabled: true,
                output: null,
                transformatorOutput: null,
                transformatorOpt: transformationContext => context = transformationContext,
                isTestMode: false,
                booleanMarshalMode: BooleanMarshalMode.Boolean,
                jsonSchemaType: "prod",
                diffFile: null,
                repositoryRoot: null,
                excludeTriggerPathScenarios: false,
                isSampleGeneration: true);

            if (context == null)
            {
                var compileOutput = string.Join("\r\n", compilerMessages.Messages.Select(msg => msg.ToString()));
                throw new InvalidOperationException($"Transformation context was not generated. Perhaps syntax error. Compiler output:\r\n{compileOutput}\r\n");
            }

            return(context);
        }
        public static JToken AddMissingProperties(Node selectedNode)
        {
            if (selectedNode.Error != null && selectedNode.Error.StartsWith("Required properties are missing from object"))
            {
                var missingProps = selectedNode.Error.Replace("Required properties are missing from object:", "");
                var tokens       = missingProps.Trim().TrimEnd('.').Split(',');

                var oldProp = selectedNode.Tag as JProperty;

                var parentProperty = selectedNode.Parent.Tag as JProperty;
                parentProperty = parentProperty.DeepClone() as JProperty;

                foreach (var v in (parentProperty.Value as JObject))
                {
                    if (v.Key == oldProp.Name)
                    {
                        var targetProp = v.Value as JObject;
                        foreach (var t in tokens)
                        {
                            var name = t.Trim();
                            var kvp  = selectedNode.Schema.Properties.FirstOrDefault(x => x.Key == name);
                            if (kvp.Value != null)
                            {
                                var jObject = JsonGenerator.Generate(kvp.Value) as JObject;
                                targetProp.Add(name, jObject);
                            }
                        }
                        break;
                    }
                }

                return(parentProperty);
            }
            return(null);
        }
예제 #4
0
        private static void Main(string[] args)
        {
            // read arguments
            var argumentReader = new ArgumentReader();

            argumentReader.Parse(args);

            // setup the app config
            var configReader = new ConfigReader();

            configReader.Initialise(argumentReader.exportConfig);

            // extract data from sheets
            var sheet2Json = new GoogleSheet2Json(configReader.appConfig);

            sheet2Json.ReadDataFromSheet(argumentReader.exportConfig);

            // setup compilation process
            var builder   = new Builder();
            var parser    = new Parser(builder);
            var lexer     = new Lexer(parser);
            var generator = new JsonGenerator();

            lexer.Lex(sheet2Json.dataKeys[0], sheet2Json.dataValues, argumentReader.exportConfig);
            generator.Generate(builder.BuildData, argumentReader.exportConfig);

            StreamWriter file = new StreamWriter(configReader.appConfig.outputDirectory + argumentReader.exportConfig.outputFileName);

            using (file)
            {
                file.WriteLine(generator.GeneratedContent);
            }

            Logger.LogLine($"Write file with name: {argumentReader.exportConfig.outputFileName} in the directory: {configReader.appConfig.outputDirectory}");
        }
예제 #5
0
        public void GenerateJson_VALID()
        {
            JsonGenerator jsonGenerator = new JsonGenerator();
            string        result        = jsonGenerator.Generate(10);

            Assert.True(result != String.Empty);
            Assert.True(JsonValidator.IsJsonValid(result));
        }
예제 #6
0
        public void GenerateJson_INVALID_NUMBER()
        {
            JsonGenerator jsonGenerator = new JsonGenerator();
            string        result        = jsonGenerator.Generate(-1);

            Assert.True(result == String.Empty);
            Assert.False(JsonValidator.IsJsonValid(result));
        }
        private static JToken GenerateToken(JSchema schema, JProperty oldProperty, JObject existing = null)
        {
            if (existing == null)
            {
                existing = JsonGenerator.Generate(schema) as JObject;
            }

            if (schema.Properties.Count > 0)
            {
                foreach (var prop in schema.Properties)
                {
                    if (prop.Key == oldProperty.Name)
                    {
                        return(GenerateToken(prop.Value, oldProperty, existing));
                    }
                }
            }

            if (schema.OneOf.Count > 0)
            {
                var myObj = oldProperty.Value as JObject;
                foreach (var oneOf in schema.OneOf)
                {
                    foreach (var key in oneOf.Required)
                    {
                        if (myObj.ContainsKey(key))
                        {
                            var val = myObj[key].ToString();
                            var s   = oneOf.Properties[key].Const?.ToString();

                            if (val == s)
                            {
                                var newToken = JsonGenerator.Generate(oneOf) as JObject;
                                var temp     = existing[oldProperty.Name] as JObject;
                                temp.Merge(newToken, new JsonMergeSettings()
                                {
                                    MergeArrayHandling = MergeArrayHandling.Union
                                });

                                return(GenerateToken(oneOf, oldProperty, existing));
                            }
                        }
                    }
                }
            }
            return(existing);
        }
        public Profile(string profileName, string plugInName)
        {
            ProfileName = profileName;
            PluginName  = plugInName;

            Schema = SchemaManager.GetSchemaForProfile(plugInName, profileName);

            if (Schema == null)
            {
                _logger.Log(Level.Error, $"Unable to find schema for {profileName} [{plugInName}]");
                throw new NoSchemaFoundException($"Unable to find schema for {profileName} [{plugInName}]", profileName, plugInName);
            }

            Token = JsonGenerator.Generate(Schema);

            _schemaLookup = SchemaManager.GetSchemaDictionary(plugInName, profileName);

            Validate();
        }
 private void MitigateErrors()
 {
     foreach (var error in ErrorMessages)
     {
         if (error.Message.StartsWith("Required properties are missing from object"))
         {
             var tokens = error.Message.Trim().TrimEnd('.').Split(':');
             if (tokens.Length > 1)
             {
                 var tag = tokens[1].Trim();
                 if (Schema.Properties.ContainsKey(tag))
                 {
                     var schema = Schema.Properties[tag];
                     var token  = JsonGenerator.Generate(schema);
                     (Token as JObject).Add(new JProperty(tag, token));
                 }
             }
         }
     }
 }
예제 #10
0
        private static void ShowGenerateJsonDialog()
        {
            int numberOfMessages = 0;

            Console.Write("Enter a number of messages to generate (500 messages = 7.5 megabytes): ");
            try
            {
                numberOfMessages = Convert.ToInt32(Console.ReadLine());
            }
            catch (Exception ex)
            {
                Console.WriteLine("Invalid number of messages.");
                logger.Error("Invalid number of messages: " + ex);
                ShowExitDialog();
            }

            JsonGenerator jsonGenerator = new JsonGenerator();
            string        json          = jsonGenerator.Generate(numberOfMessages);

            Files.Write(file, json);
        }
        public static Profile Create(string profileName, string pluginName, List <ICsvRow> mappedData)
        {
            var profile = Activator.CreateInstance(typeof(Profile), new object[] { profileName, pluginName }) as Profile;

            profile.AddNode();

            foreach (var row in mappedData)
            {
                var node = profile.GetAllNavigatorNodes().FirstOrDefault(x => x.Path.ToLower() == row.FormattedPath.ToLower());
                if (node != null)
                {
                    var schema   = node.Schema;
                    var required = Node.GetRequiredProperties(node);

                    foreach (var name in required)
                    {
                        foreach (var oneOf in schema.OneOf)
                        {
                            var prop = oneOf.Properties.FirstOrDefault(x => x.Key == name && x.Value.Const?.ToString() == "mapped");
                            if (prop.Key == name)
                            {
                                // Found
                                var token = JsonGenerator.Generate(oneOf, row) as JObject;
                                (node.Tag as JProperty).Value = token;

                                node.Nodes.Clear();
                                profile.AddNode(token, node);

                                break;
                            }
                        }
                    }
                }
            }

            return(profile);
        }
        public static JToken SuggestCorrection(Node selectedNode)
        {
            var    selectedParentNode = selectedNode.Parent;
            JToken newToken           = null;

            try
            {
                JSchema schema = selectedParentNode.Parent != null ? selectedParentNode.Parent.Schema : selectedParentNode.Schema;

                if (schema != null)
                {
                    if (schema.Type == JSchemaType.Object)
                    {
                        var oldProp = selectedParentNode.Tag as JProperty;

                        // Deep clone before merge
                        oldProp = oldProp.DeepClone() as JProperty;

                        JObject jObject = null;
                        if (oldProp.Value is JObject)
                        {
                            jObject = GenerateToken(schema, oldProp) as JObject;
                        }
                        else
                        {
                            jObject = JsonGenerator.Generate(schema) as JObject;
                        }
                        JToken token;

                        if (jObject.TryGetValue(selectedParentNode.Name, out token))
                        {
                            // !!!! This token.Parent is same level as node.Tag object
                            var newProp = token.Parent as JProperty;

                            Merge(oldProp, newProp);

                            newToken = newProp;
                        }
                    }
                    else if (schema.Type == JSchemaType.Array)
                    {
                        var firstElement = schema.Items.FirstOrDefault();

                        var oldObj = selectedParentNode.Tag as JObject;
                        oldObj = oldObj.DeepClone() as JObject;

                        foreach (var oneOf in firstElement.OneOf)
                        {
                            foreach (var key in oneOf.Required)
                            {
                                if (oldObj.ContainsKey(key))
                                {
                                    var val = oldObj[key].ToString();
                                    var s   = oneOf.Properties[key].Const?.ToString();

                                    if (val == s)
                                    {
                                        // found
                                        var newObj = GenerateToken(oneOf, oldObj) as JObject;
                                        Merge(oldObj, newObj);

                                        newToken = newObj;

                                        break;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        _logger.Log(Level.Debug, "Suggested correction: Schema Type = " + schema.Type);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Log(Level.Error, ex.Message, ex);
                throw;
            }
            return(newToken);
        }
예제 #13
0
        // additional method is required by Costura's assembly loading hack under Mono
        private static int MainImpl(string[] args)
        {
            var timer   = Stopwatch.StartNew();
            var options = new CommandLineOptions();

            try
            {
                var toolName = Assembly.GetExecutingAssembly().GetName();

                options.Parse(args);
                var isTestMode = options.IsTestMode;

                if (!isTestMode)
                {
                    Print($"{toolName.Name} v{toolName.Version}", ConsoleColor.Gray);
                }


                if (options.NeedHelp)
                {
                    options.PrintHelp(Console.Out);
                    return(0);
                }


                JsonGenerator.OnMessage += (message, importance) =>
                {
                    if (!isTestMode && importance >= options.LogLevel)
                    {
                        Print(message, ConsoleColor.DarkGray);
                    }
                };

                foreach (var ignoredOption in options.IgnoredOptions)
                {
                    PrintError($"File or option was ignored: {ignoredOption}");
                }

                var(tdls, refs) = (options.InputFiles.ToArray(), options.References.ToArray());
                var output = new Lazy <TextWriter>(() => new StreamWriter(options.OutputFile, false, Encoding.UTF8));
                CompilerMessageBag messages;

                if (options.Transformers.Count > 0)
                {
                    Print($"Using custom transformers", ConsoleColor.Magenta);
                    messages = new CompilerMessageBag();
                    foreach (var t in options.Transformers)
                    {
                        var transformatorFunc     = LoadTransformator(t.assembly, t.type, t.method);
                        var transformationContext = JsonGenerator.Generate(options.WorkingDirectory, tdls, refs, options.DeploymentScriptHeader, options.DeploymentToolPath,
                                                                           isMethodTypingEnabled: true, output: null, transformatorOutput: options.OutputFile, transformatorOpt: transformatorFunc, isTestMode: isTestMode,
                                                                           booleanMarshalMode: options.BooleanMarshalMode, jsonSchemaType: options.JsonSchemaType, diffFile: options.DiffFile,
                                                                           repositoryRoot: options.RepositoryPath, excludeTriggerPathScenarios: options.ExcludeTriggerPathScenarios,
                                                                           isSampleGeneration: options.SampleOutputFile != null);
                        messages.AddRange(transformationContext.Messages);

                        if (messages.HasErrors)
                        {
                            break;
                        }
                    }
                }
                else
                {
                    var transformationContext = JsonGenerator.Generate(options.WorkingDirectory, tdls, refs, options.DeploymentScriptHeader, options.DeploymentToolPath,
                                                                       isMethodTypingEnabled: true, output: output, transformatorOutput: null, transformatorOpt: null, isTestMode: isTestMode,
                                                                       booleanMarshalMode: options.BooleanMarshalMode, jsonSchemaType: options.JsonSchemaType, diffFile: options.DiffFile,
                                                                       repositoryRoot: options.RepositoryPath, excludeTriggerPathScenarios: options.ExcludeTriggerPathScenarios,
                                                                       isSampleGeneration: options.SampleOutputFile != null);

                    if (isTestMode)
                    {
                        Debug.Assert(transformationContext.Comments != null);

                        if (!TestCompilerMessages(transformationContext, options))
                        {
                            return(-4);
                        }
                        if (output.IsValueCreated && options.SampleOutputFile != null)
                        {
                            var result = TestCompareWitSample(options, output);
                            if (result < 0)
                            {
                                return(result);
                            }
                        }

                        Print($"test passed.  Elapsed time: {timer.Elapsed}", ConsoleColor.Green);
                        return(0);
                    }

                    messages = transformationContext.Messages;
                }

                if (output.IsValueCreated)
                {
                    output.Value.Dispose();
                }

                ReportCompilerMessages(messages);

                if (output.IsValueCreated)
                {
                    Print($"JSON file was created successfully: '{options.OutputFile}'.", ConsoleColor.Green);
                }

                Print("Took: " + timer.Elapsed, ConsoleColor.DarkGray);

                return(messages.HasErrors ? -3 : 0);
            }
            catch (OptionException e)
            {
                PrintError(e.Message);
                return(-2);
            }
            catch (ConfigurationException e)
            {
                PrintError($"Configuration error: {e.Message}");
                return(-3);
            }
            catch (Exception e)
            {
                PrintError($"Unhandled exception: {e}");
                return(-3);
            }
            finally
            {
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }
            }
        }