Exemple #1
0
        public void Publish(CogsModel model)
        {
            //if (CogsLocation == null)
            //{
            //    throw new InvalidOperationException("Cogs location must be specified");
            //}
            if (TargetDirectory == null)
            {
                throw new InvalidOperationException("Target directory must be specified");
            }

            if (Overwrite && Directory.Exists(TargetDirectory))
            {
                Directory.Delete(TargetDirectory, true);
            }

            Directory.CreateDirectory(TargetDirectory);

            ReusableStorage = model.ReusableDataTypes;
            ItemTypeStorage = model.ItemTypes;
            set             = new HashSet <string>();
            map             = new Dictionary <string, List <string> >();

            //Start here
            var           projName = model.Settings.Slug;
            StringBuilder res      = new StringBuilder();

            res.AppendLine(@"<?xml version=""1.0""?>");
            res.AppendLine(@"<rdf:RDF xmlns=""" + TargetNamespacePrefix + projName + @"""");
            res.AppendLine(@"   xml:base=""" + TargetNamespacePrefix + projName + @"""");
            res.AppendLine(@"   xmlns:rdf=""http://www.w3.org/1999/02/22-rdf-syntax-ns#""");
            res.AppendLine(@"   xmlns:owl=""http://www.w3.org/2002/07/owl#""");
            res.AppendLine(@"   xmlns:xml=""http://www.w3.org/XML/1998/namespace""");
            res.AppendLine(@"   xmlns:xsd=""http://www.w3.org/2001/XMLSchema#""");
            res.AppendLine(@"   xmlns:rdfs=""http://www.w3.org/2000/01/rdf-schema#"">");
            res.AppendLine(@"   <owl:Ontology rdf:about=""" + TargetNamespacePrefix + projName + @"""/>");
            res.AppendLine("\n");

            //Generate each ItemType class and add to result
            GenComment(res, "Annotation properties & Datatypes");
            PredefineSimple(res, projName);

            GenComment(res, "Classes");
            GenOwlClass(res, model.ItemTypes, null, projName);
            GenOwlClass(res, null, model.ReusableDataTypes, projName);

            GenComment(res, "SimpleType");
            GenSimpleClass(res, projName);

            GenComment(res, "DataProperty Type & Objectproperty");
            GenProperty(res, model.ItemTypes, null, projName);
            GenProperty(res, null, model.ReusableDataTypes, projName);

            res.AppendLine(@"</rdf:RDF>");
            File.WriteAllText(Path.Combine(TargetDirectory, projName + ".owl"), res.ToString());
        }
Exemple #2
0
        public void MakeGraphSingle(CogsModel model, string header)
        {
            int previousOutput = 0;

            foreach (var item in model.ItemTypes.Concat(model.ReusableDataTypes))
            {
                if (previousOutput > item.Name.Length)
                {
                    Console.Write("\rCreating Graph for " + item.Name + string.Join("", Enumerable.Repeat(" ", previousOutput - item.Name.Length)));
                }
                else
                {
                    Console.Write("\rCreating Graph for " + item.Name);
                }
                previousOutput = item.Name.Length;
                StringBuilder arrows    = new StringBuilder();
                bool          isCluster = false;
                if (ShowReusables && item.Properties.Where(x => ReusableList.Contains(x.DataType)).ToList().Count > 0)
                {
                    isCluster = true;
                }
                foreach (var clss in model.ItemTypes.Concat(model.ReusableDataTypes))
                {
                    if (Inheritance && clss.ExtendsTypeName.Equals(item.Name))
                    {
                        if (isCluster)
                        {
                            arrows.Append($"{clss.Name} -> {item.Name}Properties [arrowhead=\"empty\" lhead = cluster{item.Name}] ");
                        }
                        else
                        {
                            arrows.Append($"{clss.Name} -> {item.Name} [ arrowhead=\"empty\"] ");
                        }
                    }
                    foreach (var property in clss.Properties)
                    {
                        if (property.DataTypeName.Equals(item.Name))
                        {
                            if (isCluster && clss.Name.Equals(item.Name))
                            {
                                arrows.Append($"{clss.Name}Properties -> {item.Name}Properties [ arrowhead=\"none\" label = {property.Name}] ");
                            }
                            else if (isCluster)
                            {
                                arrows.Append($"{clss.Name} -> {item.Name}Properties [ arrowhead=\"none\" label= {property.Name} lhead = cluster{item.Name}] ");
                            }
                            else
                            {
                                arrows.Append($"{clss.Name} -> {item.Name}[ arrowhead=\"none\" label={property.Name}] ");
                            }
                        }
                    }
                }
                GenerateOutput(item.Name, header + " " + MakeItem(item) + arrows + " }");
            }
        }
        public void Build(CogsModel cogsModel, string outputDirectory)
        {
            this.cogsModel       = cogsModel;
            this.outputDirectory = outputDirectory;

            CreateSphinxSkeleton();
            CopyArticles();
            BuildTopIndex();
            BuildItemTypePages();
            BuildReusableTypePages();
            BuildTopicPages();
        }
Exemple #4
0
        public List <ReusableType> Iteratereusable(CogsModel model)
        {
            List <ReusableType> res = new List <ReusableType>();

            foreach (var reuseabletype in model.ReusableDataTypes)
            {
                ReusableType define = new ReusableType();
                define.Name = reuseabletype.Name;
                foreach (var prop in reuseabletype.Properties)
                {
                    var temp = new JsonSchemaProp();
                    temp.MultiplicityElement = new Cardinality();
                    temp.Name = prop.Name;
                    if (IsReusableType(prop.DataType.Name))
                    {
                        temp.Reference = "#/definitions/" + prop.DataType.Name;
                    }
                    else if (IsSimpleType(prop.DataType.Name))
                    {
                        temp.Reference = "#/simpleType/" + prop.DataType.Name;
                    }
                    else if (IsItemType(prop.DataType.Name))
                    {
                        temp.Reference = "#/definitions/Reference";
                    }
                    else
                    {
                        if (TypeBelongToInt(prop.DataType.Name))
                        {
                            temp.Type          = "integer";
                            temp.original_type = prop.DataType.Name;
                        }
                        else if (TypeBelongToNum(prop.DataType.Name))
                        {
                            temp.Type          = "number";
                            temp.original_type = prop.DataType.Name;
                        }
                        else
                        {
                            temp.Type = prop.DataType.Name.ToLower();
                        }
                    }
                    temp.MultiplicityElement.MinCardinality = prop.MinCardinality;
                    temp.MultiplicityElement.MaxCardinality = prop.MaxCardinality;
                    temp.Description = prop.Description;
                    define.Properties.Add(temp);
                }
                res.Add(define);
            }
            return(res);
        }
Exemple #5
0
        public void JsonSchema_Multiple_Properties_Same_Numeric_Type_Multiplicity_1()
        {
            var model = new CogsModel();

            var type = new Model.ItemType();

            type.Name        = "Reusable1";
            type.Description = "Description One";

            var property1 = new Model.Property();

            property1.Name        = "Property1";
            property1.Description = "Description One";
            property1.DataType    = new Model.DataType {
                Name = "int"
            };
            property1.MinCardinality = "0";
            property1.MaxCardinality = "1";
            type.Properties.Add(property1);

            var property2 = new Model.Property();

            property2.Name        = "Property2";
            property2.Description = "Description Two";
            property2.DataType    = new Model.DataType {
                Name = "int"
            };
            property2.MinCardinality = "0";
            property2.MaxCardinality = "1";
            type.Properties.Add(property2);


            model.ItemTypes.Add(type);

            var jsonPublisher = new JsonPublisher();

            jsonPublisher.TargetDirectory = Environment.CurrentDirectory;
            jsonPublisher.Publish(model);

            Assert.True(true);
        }
        public void MakeGraphAll(CogsModel model, string header)
        {
            var output = new StringBuilder(header);

            foreach (var item in model.ItemTypes)
            {
                if (Inheritance && !String.IsNullOrWhiteSpace(item.ExtendsTypeName))
                {
                    output.Append(item.Name + " -> " + item.ExtendsTypeName + " [arrowhead=\"empty\"]");
                }
                foreach (var property in item.Properties)
                {
                    if (ClassList.Contains(property.DataType))
                    {
                        output.Append(item.Name + " -> " + property.DataTypeName + " ");
                    }
                }
            }
            output.Append("}");
            GenerateOutput("output", output.ToString());
        }
Exemple #7
0
        public void Publish(CogsModel model)
        {
            if (TargetDirectory == null)
            {
                throw new InvalidOperationException("Target directory must be specified");
            }
            if (Overwrite && Directory.Exists(TargetDirectory))
            {
                Directory.Delete(TargetDirectory, true);
            }
            // TODO: if Overwrite is false and Directory.Exists(TargetDirectory)) throw an error and exit
            Directory.CreateDirectory(TargetDirectory);

            // create graphs for each item
            var builder = new DotSchemaPublisher
            {
                TargetDirectory = Path.Combine(Path.Combine(TargetDirectory, "source"), "images"),
                Overwrite       = Overwrite,
                Format          = "svg",
                Output          = "single",
                Inheritance     = false,
                ShowReusables   = true,
                DotLocation     = DotLocation
            };

            builder.Publish(model);
            // create documentation
            var doc = new BuildSphinxDocumentation();

            doc.Build(model, TargetDirectory);
            //copy over image css file
            var path = Path.Combine(Path.Combine(Path.Combine(Path.Combine(TargetDirectory, "build"), "html"), "_static"), "css");

            Directory.CreateDirectory(path);
            using (var stream = new FileStream(Path.Combine(path, "image.css"), FileMode.Create))
            {
                Assembly.GetExecutingAssembly().GetManifestResourceStream("Cogs.Publishers.image.css").CopyTo(stream);
            }
        }
Exemple #8
0
        // creates a file called IIdentifiable.cs which holds the IIdentifiable interface from which all item types descend
        private void CreatePartialIIdentifiable(CogsModel model, string projName)
        {
            StringBuilder builder = new StringBuilder("using System;");

            builder.AppendLine();
            builder.AppendLine("using System.Xml.Linq;");
            builder.AppendLine("using Newtonsoft.Json.Linq;");
            builder.AppendLine("using System.Collections.Generic;");
            builder.AppendLine();
            builder.AppendLine($"namespace {projName}");
            builder.AppendLine("{");
            builder.AppendLine("    /// <summary>");
            builder.AppendLine("    /// IIdentifiable class which all object Inherit from. Used to Serialize to Json");
            builder.AppendLine("    /// <summary>");
            builder.AppendLine("    public partial interface IIdentifiable");
            builder.AppendLine("    {");
            foreach (var prop in model.Identification)
            {
                builder.AppendLine($"        {prop.DataTypeName} {prop.Name} {{ get; set; }}");
            }
            builder.AppendLine("    }");
            builder.AppendLine("}");
            File.WriteAllText(Path.Combine(TargetDirectory, "IIdentifiable.Properties.cs"), builder.ToString());
        }
Exemple #9
0
        public void Publish(CogsModel model)
        {
            if (TargetDirectory == null)
            {
                throw new InvalidOperationException("Target directory must be specified");
            }
            if (Overwrite && Directory.Exists(TargetDirectory))
            {
                Directory.Delete(TargetDirectory, true);
            }
            // TODO: if Overwrite is false and Directory.Exists(TargetDirectory)) throw an error and exit
            Directory.CreateDirectory(TargetDirectory);

            InitializeDictionary();

            //get the project name
            var projName = model.Settings.Slug;

            CreatePartialIIdentifiable(model, projName);
            CreatePartialItemContainer(model, projName);
            //create project file
            XDocument project = new XDocument(new XElement("Project", new XAttribute("Sdk", "Microsoft.NET.Sdk"),
                                                           new XElement("PropertyGroup", new XElement("TargetFramework", "netstandard2.0"),
                                                                        new XElement("AssemblyName", projName), new XElement("RootNamespace", projName)),
                                                           new XElement("ItemGroup", new XElement("PackageReference", new XAttribute("Include", "System.ComponentModel.Annotations"),
                                                                                                  new XAttribute("Version", "4.4.0")),
                                                                        new XElement("PackageReference", new XAttribute("Include", "Microsoft.CSharp"),
                                                                                     new XAttribute("Version", "4.4.0")),
                                                                        new XElement("PackageReference", new XAttribute("Include", "Newtonsoft.Json"), new XAttribute("Version", "10.0.3")))));
            XmlWriterSettings xws = new XmlWriterSettings {
                OmitXmlDeclaration = true
            };

            using (XmlWriter xw = XmlWriter.Create(Path.Combine(TargetDirectory, projName + ".csproj"), xws))
            {
                project.Save(xw);
            }


            // copy types file
            this.GetType().GetTypeInfo().Assembly.GetManifestResourceStream("Cogs.Publishers.Csharp.Types.txt").CopyTo(
                new FileStream(Path.Combine(TargetDirectory, "Types.cs"), FileMode.Create));

            // copy types file
            using (Stream stream = this.GetType().GetTypeInfo().Assembly.GetManifestResourceStream("Cogs.Publishers.Csharp.DependantTypes.txt"))
                using (StreamReader reader = new StreamReader(stream))
                {
                    string fileContents = reader.ReadToEnd();

                    fileContents = fileContents.Replace("__CogsGeneratedNamespace", projName);

                    File.WriteAllText(Path.Combine(TargetDirectory, "DependantTypes.cs"), fileContents, Encoding.UTF8);
                }



            foreach (var item in model.ItemTypes.Concat(model.ReusableDataTypes))
            {
                // add class description using '$' for newline and '#' for tabs
                var newClass = new StringBuilder("using System;");
                newClass.AppendLine();
                newClass.AppendLine("using System.Linq;");
                newClass.AppendLine("using Newtonsoft.Json;");
                newClass.AppendLine("using System.Xml.Linq;");
                newClass.AppendLine("using Cogs.SimpleTypes;");
                newClass.AppendLine("using System.Reflection;");
                newClass.AppendLine("using System.Collections;");
                newClass.AppendLine("using Newtonsoft.Json.Linq;");
                newClass.AppendLine("using Cogs.DataAnnotations;");
                newClass.AppendLine("using Cogs.Converters;");
                newClass.AppendLine("using System.Collections.Generic;");
                newClass.AppendLine("using System.ComponentModel.DataAnnotations;");
                newClass.AppendLine();
                newClass.AppendLine($"namespace {projName}");
                newClass.AppendLine("{");
                newClass.AppendLine("    /// <summary>");
                newClass.AppendLine($"    /// {item.Description}");
                newClass.AppendLine("    /// <summary>");
                newClass.Append("    public ");


                var    helpers = new StringBuilder();
                var    toXml   = new StringBuilder();
                string n       = "";
                if (model.ReusableDataTypes.Contains(item))
                {
                    n = "string name";
                }
                if (!string.IsNullOrWhiteSpace(item.ExtendsTypeName))
                {
                    toXml.AppendLine($"        public override XElement ToXml({n})");
                }
                else
                {
                    toXml.AppendLine($"        public virtual XElement ToXml({n})");
                }
                toXml.AppendLine("        {");
                toXml.AppendLine($"            XNamespace ns = \"{TargetNamespace}\";");
                if (n.Equals(""))
                {
                    toXml.AppendLine($"            XElement xEl = new XElement(ns + \"{item.Name}\");");
                }
                else
                {
                    toXml.AppendLine($"            XElement xEl = new XElement(ns + name);");
                }


                // add abstract to class title if relevant
                if (item.IsAbstract)
                {
                    newClass.Append("abstract ");
                }
                newClass.Append("partial class " + item.Name);

                // allow inheritance when relevant
                string nameArgument = model.ReusableDataTypes.Contains(item) ? "\"" + item.ExtendsTypeName + "\"" : string.Empty;
                if (!string.IsNullOrWhiteSpace(item.ExtendsTypeName))
                {
                    newClass.AppendLine($" : {item.ExtendsTypeName}");
                    newClass.AppendLine("    {");
                    toXml.AppendLine($"            foreach (var el in base.ToXml({nameArgument}).Descendants())");
                    toXml.AppendLine("            {");
                    toXml.AppendLine("                xEl.Add(el);");
                    toXml.AppendLine("            }");
                }
                else if (!model.ReusableDataTypes.Contains(item))
                {
                    newClass.AppendLine(" : IIdentifiable");
                    newClass.AppendLine("    {");
                    newClass.AppendLine("        [JsonIgnore]");
                    string format = string.Join(":", model.Identification.Select(x => "{" + x.Name + "}"));
                    newClass.AppendLine($"        public string ReferenceId {{ get {{ return $\"{format}\"; }} }}");
                }
                else
                {
                    newClass.AppendLine($"{Environment.NewLine}    {{");
                }

                foreach (var prop in item.Properties)
                {
                    // create documentation for property
                    newClass.AppendLine("        /// <summary>");
                    newClass.AppendLine($"        /// {prop.Description}");
                    newClass.AppendLine("        /// <summary>");


                    // Add type converters for specific serialization
                    if (prop.DataTypeName.Equals("date", StringComparison.CurrentCultureIgnoreCase))
                    {
                        newClass.AppendLine("        [JsonConverter(typeof(DateConverter))]");
                    }
                    else if (prop.DataTypeName.Equals("time", StringComparison.CurrentCultureIgnoreCase))
                    {
                        newClass.AppendLine("        [JsonConverter(typeof(TimeConverter))]");
                    }
                    else if (prop.DataTypeName.Equals("datetime", StringComparison.CurrentCultureIgnoreCase))
                    {
                        newClass.AppendLine("        [JsonConverter(typeof(DateTimeConverter))]");
                    }
                    else if (prop.DataTypeName.Equals("gday", StringComparison.CurrentCultureIgnoreCase))
                    {
                        newClass.AppendLine("        [JsonConverter(typeof(GDayConverter))]");
                    }
                    else if (prop.DataTypeName.Equals("gmonth", StringComparison.CurrentCultureIgnoreCase))
                    {
                        newClass.AppendLine("        [JsonConverter(typeof(GMonthConverter))]");
                    }
                    else if (prop.DataTypeName.Equals("gmonthday", StringComparison.CurrentCultureIgnoreCase))
                    {
                        newClass.AppendLine("        [JsonConverter(typeof(GMonthDayConverter))]");
                    }
                    else if (prop.DataTypeName.Equals("gyear", StringComparison.CurrentCultureIgnoreCase))
                    {
                        newClass.AppendLine("        [JsonConverter(typeof(GYearConverter))]");
                    }
                    else if (prop.DataTypeName.Equals("gyearmonth", StringComparison.CurrentCultureIgnoreCase))
                    {
                        newClass.AppendLine("        [JsonConverter(typeof(GYearMonthConverter))]");
                    }
                    else if (prop.DataTypeName.Equals("duration", StringComparison.CurrentCultureIgnoreCase))
                    {
                        newClass.AppendLine("        [JsonConverter(typeof(DurationConverter))]");
                    }



                    // set c# datatype representation while saving original so can tell what type it is
                    string origDataTypeName = null;
                    if (Translator.ContainsKey(prop.DataTypeName))
                    {
                        origDataTypeName  = prop.DataTypeName;
                        prop.DataTypeName = Translator[prop.DataTypeName];
                    }

                    // create constraints
                    if (prop.DataTypeName.Equals("string") || prop.DataTypeName.Equals("Uri"))
                    {
                        if (prop.MinLength != null && prop.MaxLength != null)
                        {
                            newClass.AppendLine($"        [StringLength({prop.MaxLength}, MinimumLength = {prop.MinLength})]");
                        }
                        else if (prop.MaxLength != null)
                        {
                            newClass.AppendLine($"        [StringLength({prop.MaxLength})]");
                        }
                        else if (prop.MinLength != null)
                        {
                            newClass.AppendLine($"        [StringLength({int.MaxValue}, MinimumLength = {prop.MinLength})]");
                        }
                        if (prop.DataTypeName.Equals("string"))
                        {
                            // work with Enum and pattern
                            if (prop.Enumeration.Count > 0)
                            {
                                newClass.AppendLine("        [StringValidation(new string[] {");
                                bool useComma = false;
                                foreach (var option in prop.Enumeration)
                                {
                                    if (useComma)
                                    {
                                        newClass.Append(", ");
                                    }
                                    newClass.AppendLine($"            \"{option}\"");
                                    useComma = true;
                                }
                                if (!string.IsNullOrWhiteSpace(prop.Pattern))
                                {
                                    newClass.AppendLine($"        }}, {prop.Pattern})]");
                                }
                                else
                                {
                                    newClass.AppendLine("        })]");
                                }
                            }
                            else if (!string.IsNullOrWhiteSpace(prop.Pattern))
                            {
                                newClass.AppendLine($"        [StringValidation(null, \"{prop.Pattern}\")]");
                            }
                        }
                    }
                    else if (!prop.DataTypeName.Equals("bool") && !prop.DataTypeName.Equals("CogsDate"))
                    {
                        if (prop.MinInclusive != null || prop.MaxInclusive != null)
                        {
                            newClass.AppendLine($"        [Range({prop.MinInclusive}, {prop.MaxInclusive})]");
                        }
                        if (prop.MinExclusive != null || prop.MaxExclusive != null)
                        {
                            newClass.AppendLine($"        [ExclusiveRange({prop.MinInclusive}, {prop.MaxInclusive})]");
                        }
                    }


                    if (model.ItemTypes.Contains(prop.DataType) && !item.IsAbstract)
                    {
                        newClass.AppendLine("        [JsonConverter(typeof(IIdentifiableConverter))]");
                    }
                    // if there can be at most one, create an instance variable
                    if (!prop.MaxCardinality.Equals("n") && int.Parse(prop.MaxCardinality) == 1)
                    {
                        if (Isboolintdoubleulong(prop.DataTypeName) || model.Identification.Contains(prop))
                        {
                            toXml.AppendLine($"            xEl.Add(new XElement(ns + \"{prop.Name}\", {prop.Name}));");
                        }
                        else if (origDataTypeName != null)
                        {
                            if (!prop.DataTypeName.Equals("string"))
                            {
                                //newClass.AppendLine("        [JsonConverter(typeof(SimpleTypeConverter))]");
                            }
                            if (prop.DataTypeName.Equals("CogsDate"))
                            {
                                toXml.AppendLine($"            if ({prop.Name} != null && {prop.Name}.UsedType != CogsDateType.None)");
                            }
                            else if (prop.DataTypeName.Equals("DateTimeOffset") || prop.DataTypeName.Equals("TimeSpan"))
                            {
                                toXml.AppendLine($"            if ({prop.Name} != default({prop.DataTypeName}))");
                            }
                            else
                            {
                                toXml.AppendLine($"            if ({prop.Name} != null)");
                            }
                            toXml.AppendLine("            {");
                            toXml.AppendLine($"                {SimpleToXml(origDataTypeName, prop.Name, prop.Name, "xEl")}");
                            toXml.AppendLine("            }");
                        }
                        else if (model.ReusableDataTypes.Contains(prop.DataType))
                        {
                            toXml.AppendLine($"            if ({prop.Name} != null) {{ xEl.Add({prop.Name}.ToXml(\"{prop.Name}\")); }}");
                        }
                        else if (!model.ItemTypes.Contains(prop.DataType))
                        {
                            toXml.AppendLine($"            if ({prop.Name} != null)");
                            toXml.AppendLine("            {");
                            toXml.AppendLine($"                xEl.Add(new XElement(ns + \"{prop.Name}\", {prop.Name}));");
                            toXml.AppendLine("            }");
                        }
                        else
                        {
                            toXml.AppendLine($"            if ({prop.Name} != null)");
                            toXml.AppendLine("            {");
                            toXml.AppendLine($"                xEl.Add(new XElement(ns + \"{prop.Name}\", ");
                            foreach (var part in model.Identification)
                            {
                                toXml.AppendLine($"                    new XElement(ns + \"{part.Name}\", {prop.Name}.{part.Name}), ");
                            }
                            toXml.AppendLine($"                    new XElement(ns + \"TypeOfObject\", {prop.Name}.GetType().Name)));");
                            toXml.AppendLine("            }");
                        }
                        newClass.AppendLine($"        public {prop.DataTypeName} {prop.Name} {{ get; set; }}");
                    }
                    // otherwise, create a list object to allow multiple
                    else
                    {
                        if (Isboolintdoubleulong(prop.DataTypeName) || model.Identification.Contains(prop))
                        {
                            toXml.AppendLine($"            xEl.Add(");
                            toXml.AppendLine($"                from item in {prop.Name}");
                            toXml.AppendLine($"                select new XElement(ns + \"{prop.Name}\", item));");
                        }
                        else if (origDataTypeName != null)
                        {
                            toXml.AppendLine($"            if ({prop.Name} != null && {prop.Name}.Count > 0)");
                            toXml.AppendLine("            {");
                            toXml.AppendLine($"                foreach (var item in {prop.Name})");
                            toXml.AppendLine("                {");
                            toXml.AppendLine($"                    {SimpleToXml(origDataTypeName, "item", prop.Name, "xEl")}");
                            toXml.AppendLine("                }");
                            toXml.AppendLine("            }");
                        }
                        else if (model.ReusableDataTypes.Contains(prop.DataType))
                        {
                            toXml.AppendLine($"            if ({prop.Name} != null && {prop.Name}.Count > 0)");
                            toXml.AppendLine("            {");
                            toXml.AppendLine($"                foreach (var item in {prop.Name})");
                            toXml.AppendLine("                {");
                            toXml.AppendLine($"                    xEl.Add(item.ToXml(\"{prop.Name}\"));");
                            toXml.AppendLine("                }");
                            toXml.AppendLine("            }");
                        }
                        else if (!model.ItemTypes.Contains(prop.DataType))
                        {
                            toXml.AppendLine($"            if ({prop.Name} != null && {prop.Name}.Count > 0)");
                            toXml.AppendLine("            {");
                            toXml.AppendLine($"                xEl.Add(");
                            toXml.AppendLine($"                    from item in {prop.Name}");
                            toXml.AppendLine($"                    select new XElement(ns + \"{prop.Name}\", item.ToString()));");
                            toXml.AppendLine("            }");
                        }
                        else
                        {
                            toXml.AppendLine($"            if ({prop.Name} != null && {prop.Name}.Count > 0)");
                            toXml.AppendLine("            {");
                            toXml.AppendLine($"                foreach (var item in {prop.Name})");
                            toXml.AppendLine("                {");
                            toXml.AppendLine($"                    xEl.Add(new XElement(ns + \"{prop.Name}\", ");
                            foreach (var part in model.Identification)
                            {
                                toXml.AppendLine($"                        new XElement(ns + \"{part.Name}\", item.{part.Name}), ");
                            }
                            toXml.AppendLine($"                        new XElement(ns + \"TypeOfObject\", item.GetType().Name)));");
                            toXml.AppendLine("                }");
                            toXml.AppendLine("            }");
                        }

                        newClass.AppendLine($"        public List<{prop.DataTypeName}> {prop.Name} {{ get; set; }} = new List<{prop.DataTypeName}>();");
                        newClass.AppendLine($"        public bool ShouldSerialize{prop.Name}() {{ return {prop.Name}.Count > 0; }}");
                    }
                }

                newClass.AppendLine();
                newClass.AppendLine("        /// <summary>");
                newClass.AppendLine("        /// Used to Serialize this object to XML");
                newClass.AppendLine("        /// <summary>");
                newClass.Append(toXml.ToString());
                newClass.AppendLine("            return xEl;");
                newClass.AppendLine("        }");
                newClass.AppendLine("    }");
                newClass.AppendLine("}");
                newClass.AppendLine();
                // write class to out folder
                File.WriteAllText(Path.Combine(TargetDirectory, item.Name + ".cs"), newClass.ToString());
            }
        }
Exemple #10
0
        public void Publish(CogsModel model2)
        {
            if (CogsLocation == null)
            {
                throw new InvalidOperationException("Cogs location must be specified");
            }
            if (TargetDirectory == null)
            {
                throw new InvalidOperationException("Target directory must be specified");
            }

            if (Overwrite && Directory.Exists(TargetDirectory))
            {
                Directory.Delete(TargetDirectory, true);
                Thread.Sleep(50);
            }

            Directory.CreateDirectory(TargetDirectory);


            CogsModel  = model2;
            CogsSchema = new XmlSchema();

            CogsSchema.TargetNamespace = TargetNamespace;
            CogsSchema.Namespaces.Add(TargetNamespacePrefix, TargetNamespace);
            CogsSchema.ElementFormDefault   = XmlSchemaForm.Qualified;
            CogsSchema.AttributeFormDefault = XmlSchemaForm.Unqualified;

            // create built in types
            XmlSchemaComplexType referenceType = CreateReferenceType();


            // Create the container

            /*
             * XmlSchemaComplexType containerType = new XmlSchemaComplexType();
             * containerType.Name = "FragmentInstance";
             * containerType.AddSchemaDocumentation("A Fragment Instance is used to transfer items plus any associated notes and other material. TopLevelReference provides a record of the main item of the FragmentInstance.");
             * cogsSchema.Items.Add(containerType);
             *
             * XmlSchemaSequence containerSequence = new XmlSchemaSequence();
             * containerType.Particle = containerSequence;
             */

            XmlSchemaChoice      itemChoices   = null;
            XmlSchemaComplexType containerType = CreateItemContainerType(out itemChoices);

            CogsSchema.Items.Add(containerType);

            XmlSchemaElement container = new XmlSchemaElement();

            container.Name = "ItemContainer";
            container.AddSchemaDocumentation("A Item Container is used to transfer items plus any associated notes and other material. TopLevelReference provides a record of the main item of the Item Container.");
            container.SchemaTypeName = new XmlQualifiedName("ItemContainerType", TargetNamespace);
            CogsSchema.Items.Add(container);

            foreach (var item in CogsModel.ItemTypes)
            {
                CreateDataType(item);

                // create a usage for the container
                XmlSchemaElement element = new XmlSchemaElement();
                element.Name           = item.Name;
                element.SchemaTypeName = new XmlQualifiedName(item.Name, TargetNamespace);
                CogsSchema.Items.Add(element);

                // include item in container via element reference
                XmlSchemaElement elementRef = new XmlSchemaElement();
                elementRef.RefName = new XmlQualifiedName(item.Name, TargetNamespace);
                itemChoices.Items.Add(elementRef);
            }

            CreateCogsDataType();

            foreach (var dataType in CogsModel.ReusableDataTypes)
            {
                CreateDataType(dataType);
            }

            XmlSchemaSet schemaSet = new XmlSchemaSet();

            schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
            schemaSet.Add(CogsSchema);
            schemaSet.Compile();

            foreach (XmlSchema schema in schemaSet.Schemas())
            {
                CogsSchema = schema;
            }

            // Write the complete schema
            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Encoding    = Encoding.UTF8;
            settings.Indent      = true;
            settings.IndentChars = "    ";
            using (XmlWriter writer = XmlWriter.Create(Path.Combine(TargetDirectory, "schema.xsd"), settings))
            {
                CogsSchema.Write(writer);
            }
        }
Exemple #11
0
        public object Publish(CogsModel model)
        {
            if (TargetDirectory == null)
            {
                throw new InvalidOperationException("Target directory must be specified");
            }
            if (Overwrite && Directory.Exists(TargetDirectory))
            {
                Directory.Delete(TargetDirectory, true);
            }
            // TODO: if Overwrite is false and Directory.Exists(TargetDirectory)) throw an error and exit
            Directory.CreateDirectory(TargetDirectory);

            if (DotLocation == null)
            {
                if (File.Exists("dot.exe"))
                {
                    DotLocation = Path.GetFullPath("dot.exe");
                }
                else if (File.Exists("dot"))
                {
                    DotLocation = Path.GetFullPath("dot");
                }
                else
                {
                    if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                    {
                        foreach (var exe in Environment.GetEnvironmentVariable("PATH").Split(Path.PathSeparator))
                        {
                            var fullPath = Path.Combine(exe, "dot.exe");
                            if (File.Exists(fullPath))
                            {
                                DotLocation = fullPath;
                            }
                        }
                    }
                    else if (Environment.OSVersion.Platform == PlatformID.Unix)
                    {
                        DotLocation = "dot";
                    }
                }
                if (DotLocation == null)
                {
                    Errors.Add(new CogsError(ErrorLevel.Error, "Could not find dot file: please specify path"));
                    return(-1);
                }
            }
            // create list of all class names so you know if a class is being referenced
            ClassList = model.ItemTypes;
            // create list of all reusable types so you know if a reusable type is being referenced and can get information about it
            ReusableList = model.ReusableDataTypes;
            var header = "digraph G { compound = true rankdir=LR fontsize = 8 node [fontsize = 8 shape = \"oval\" " +
                         "style = \"filled\" fillcolor = \"#f7b733\"] edge [ fontsize = 8 ] ";

            if (Output.Equals("all"))
            {
                MakeGraphAll(model, header);
            }
            else if (Output.Equals("topic"))
            {
                MakeGraphTopic(model, header);
            }
            else
            {
                MakeGraphSingle(model, header);
            }
            return(0);
        }
Exemple #12
0
        public void Publish(CogsModel model)
        {
            if (TargetDirectory == null)
            {
                throw new InvalidOperationException("Target directory must be specified");
            }
            if (Overwrite && Directory.Exists(TargetDirectory))
            {
                Directory.Delete(TargetDirectory, true);
            }
            // TODO: if Overwrite is false and Directory.Exists(TargetDirectory)) throw an error and exit

            Directory.CreateDirectory(TargetDirectory);

            //TODO: get project name and set it here
            string projectName = model.Settings.Slug;

            // set namespaces based on output format
            XNamespace xmins = "http://www.omg.org/spec/XMI/20110701";
            XNamespace umlns = "http://www.omg.org/spec/UML/20110701";

            if (!Normative)
            {
                xmins = "http://www.omg.org/spec/XMI/20131001";
                umlns = "http://www.omg.org/spec/UML/20131001";
            }

            XElement xmodel = new XElement("packagedElement", new XAttribute(xmins + "type", "uml:Package"),
                                           new XAttribute(xmins + "id", projectName), new XAttribute("name", projectName));
            XElement        diagramElements = new XElement("elements");
            List <XElement> nodes           = null;
            var             xOff            = 0.0;
            var             yOff            = 0.0;
            XNamespace      ns = "http://www.w3.org/2000/svg";

            if (!Normative)
            {
                // run svg publisher to create svg file to use for positioning
                DotSchemaPublisher publisher = new DotSchemaPublisher
                {
                    TargetDirectory = TargetDirectory,
                    Overwrite       = Overwrite,
                    Format          = "svg",
                    Output          = "all",
                    Inheritance     = true,
                    DotLocation     = DotLocation,
                    ShowReusables   = true
                };
                publisher.Publish(model);

                // read created svg file
                nodes = XDocument.Load(Path.Combine(TargetDirectory, "output.svg")).Root.Descendants(ns + "g")
                        .Where(x => x.Attribute("class").Value == "node").ToList();
                File.Delete(Path.Combine(TargetDirectory, "output.svg"));

                //get leftmost  and topmost value to shift graph accordingly
                foreach (var item in nodes.Descendants(ns + "title").ToList())
                {
                    var node = XElement.Parse(item.NextNode.ToString());
                    if (Convert.ToDouble(node.Attribute("cx").Value) < xOff)
                    {
                        xOff = Convert.ToDouble(node.Attribute("cx").Value);
                    }
                    if (Convert.ToDouble(node.Attribute("cy").Value) < yOff)
                    {
                        yOff = Convert.ToDouble(node.Attribute("cy").Value);
                    }
                }
                xOff = Math.Abs(xOff);
                yOff = Math.Abs(yOff);
            }
            int count  = model.ItemTypes.Count;
            var offset = 2.5;

            // loop through classes and reusable data types
            foreach (var item in model.ItemTypes)
            {
                // Create class
                var newItem = new XElement(new XElement("packagedElement", new XAttribute(xmins + "type", "uml:Class"),
                                                        new XAttribute(xmins + "id", CreateId(item.Name)),
                                                        new XAttribute("name", item.Name)));
                // add class to diagram
                if (!Normative)
                {
                    var node   = XElement.Parse(nodes.Descendants(ns + "text").Where(x => x.FirstNode.ToString().Contains(item.Name)).ToList()[0].PreviousNode.ToString());
                    var left   = (Double.Parse(node.Attribute("cx").Value) - Double.Parse(node.Attribute("rx").Value) + xOff) * offset;
                    var right  = (Double.Parse(node.Attribute("cx").Value) + Double.Parse(node.Attribute("rx").Value) + xOff) * offset;
                    var top    = (Double.Parse(node.Attribute("cy").Value) - Double.Parse(node.Attribute("ry").Value) + yOff) * offset;
                    var bottom = (Double.Parse(node.Attribute("cy").Value) + Double.Parse(node.Attribute("ry").Value) + yOff) * offset;
                    diagramElements.Add(new XElement("element", new XAttribute("geometry", "Left=" + left + ";Top=" + top + ";Right=" + right + ";Bottom=" + bottom + ";"),
                                                     new XAttribute("subject", item.Name), new XAttribute("seqno", count.ToString()), new XAttribute("style",
                                                                                                                                                     "DUID=" + "item.Name" + ";NSL=0;BCol=-1;BFol=-1;LCol=-1;LWth=-1;fontsz=0;bold=0;black=0;italic=0;ul=0;charset=0;pitch=0;));")));
                }
                string extends = item.ExtendsTypeName;
                // loop through properties of class and add to class
                foreach (var property in item.Properties)
                {
                    var newProperty = new XElement("ownedAttribute", new XAttribute(xmins + "type", "uml:Property"),
                                                   new XAttribute(xmins + "id", CreateId(item.Name + "." + property.Name)),
                                                   new XAttribute("name", property.Name));
                    if (string.Equals(property.DataTypeName, "cogsDate", StringComparison.OrdinalIgnoreCase))
                    {
                        property.DataTypeName = "string";
                    }
                    newProperty.Add(new XElement("type", new XAttribute(xmins + "idref", property.DataTypeName)));
                    if (property.MinCardinality != null)
                    {
                        newProperty.Add(new XElement("lowerValue", new XAttribute(xmins + "type", "uml:LiteralInteger"),
                                                     new XAttribute(xmins + "id", CreateId(item.Name + "." + property.Name + ".MinCardinality")),
                                                     new XAttribute("value", property.MinCardinality)));
                    }
                    if (property.MaxCardinality != null)
                    {
                        var attribute = new XAttribute("value", property.MaxCardinality);
                        // if max is "n" change to "*"
                        if (property.MaxCardinality.Equals("n"))
                        {
                            attribute = new XAttribute("value", "*");
                        }
                        newProperty.Add(new XElement("upperValue", new XAttribute(xmins + "type", "uml:LiteralUnlimitedNatural"),
                                                     new XAttribute(xmins + "id", CreateId(item.Name + "." + property.Name + ".MaxCardinality")),
                                                     attribute));
                    }
                    newItem.Add(newProperty);
                    // see if property is a type of class
                    if (model.ItemTypes.Contains(property.DataType) && !IdList.Contains("Association.from" + property.Name + ".to." + property.DataTypeName))
                    {
                        // create link association
                        var classLink = new XElement("packagedElement", new XAttribute(xmins + "type", "uml:Association"),
                                                     new XAttribute(xmins + "id", CreateId("Association.from" + property.Name + ".to." + property.DataTypeName)));
                        classLink.Add(new XElement("memberEnd", new XAttribute(xmins + "idref", item.Name + "." + property.Name + ".association")));
                        classLink.Add(new XElement("memberEnd",
                                                   new XAttribute(xmins + "idref", "Association.from" + property.Name + ".to." + property.DataTypeName + ".ownedEnd")));
                        var ownedEnd = new XElement("ownedEnd", new XAttribute(xmins + "type", "uml:Property"),
                                                    new XAttribute(xmins + "id", CreateId("Association.from" + property.Name + ".to." + property.DataTypeName + ".ownedEnd")),
                                                    new XAttribute("association", "Association.from" + property.Name + ".to." + property.DataTypeName),
                                                    new XAttribute("isOrdered", "true"));
                        ownedEnd.Add(new XElement("type", new XAttribute(xmins + "idref", item.Name)));
                        var min = "0";
                        var max = "*";
                        // check to see if item being referenced is a ReusableDataType
                        if (model.ReusableDataTypes.Contains(property.DataType))
                        {
                            min = "1";
                            max = "1";
                        }
                        ownedEnd.Add(new XElement("lowerValue", new XAttribute(xmins + "type", "uml:LiteralInteger"),
                                                  new XAttribute(xmins + "id", CreateId("Association.from" + property.Name + ".to." + property.DataTypeName + ".ownedEnd.MinCardinality")),
                                                  new XAttribute("value", min)));
                        ownedEnd.Add(new XElement("upperValue", new XAttribute(xmins + "type", "uml:LiteralUnlimitedNatural"),
                                                  new XAttribute(xmins + "id", CreateId("Association.from" + property.Name + ".to." + property.DataTypeName + ".ownedEnd.MaxCardinality")),
                                                  new XAttribute("value", max)));
                        classLink.Add(ownedEnd);
                        xmodel.Add(classLink);
                        // reference link from current class as attribute
                        var link = new XElement("ownedAttribute", new XAttribute(xmins + "type", "uml:Property"),
                                                new XAttribute(xmins + "id", CreateId(item.Name + "." + property.Name + ".association")),
                                                new XAttribute("name", property.Name),
                                                new XAttribute("association", "Association.from" + property.Name + ".to." + property.DataTypeName),
                                                new XAttribute("isOrdered", "true"));
                        link.Add(new XElement("type", new XAttribute(xmins + "idref", property.DataTypeName)));
                        link.Add(new XElement("lowerValue", new XAttribute(xmins + "type", "uml:LiteralInteger"),
                                              new XAttribute(xmins + "id", CreateId(item.Name + "." + property.Name + ".association.MinCardinality")),
                                              new XAttribute("value", min)));
                        link.Add(new XElement("upperValue", new XAttribute(xmins + "type", "uml:LiteralUnlimitedNatural"),
                                              new XAttribute(xmins + "id", CreateId(item.Name + "." + property.Name + ".association.MaxCardinality")),
                                              new XAttribute("value", max)));
                        newItem.Add(link);
                    }
                }
                // adds pointers for inheritance where applicable
                if (!string.IsNullOrWhiteSpace(extends))
                {
                    newItem.Add(new XElement("generalization",
                                             new XAttribute(xmins + "type", "uml:Generalization"),
                                             new XAttribute(xmins + "id", CreateId(item.Name + ".Generalization")),
                                             new XAttribute("general", extends)));
                }
                // add class to model
                xmodel.Add(newItem);
                count -= 1;
            }
            //create document header based on format specified
            XDocument xDoc;

            if (Normative)
            {
                xDoc = new XDocument(
                    new XDeclaration("1.0", "utf-8", null),
                    new XElement(xmins + "XMI", new XAttribute(XNamespace.Xmlns + "uml", "http://www.omg.org/spec/UML/20110701"),
                                 new XAttribute(XNamespace.Xmlns + "xmi", "http://www.omg.org/spec/XMI/20110701"),
                                 new XElement(xmins + "Documentation", new XElement("exporter", "Enterprise Architect"), new XElement("exporterVersion", "6.5")),
                                 new XElement(umlns + "Model", new XAttribute(xmins + "type", "uml:Model"), new XAttribute("name", "EA_Model"), xmodel)));
            }
            else
            {
                // get current date and time for when setting created and last modified settings
                var currentTime = DateTime.UtcNow.Year + "-" + DateTime.UtcNow.Month + "-" + DateTime.UtcNow.Day + " " + DateTime.UtcNow.Hour + ":" +
                                  DateTime.UtcNow.Minute + ":" + DateTime.UtcNow.Second;
                // create header + structure of xml 2.5.1 (chunky and unpleasing, but works)
                xDoc = new XDocument(
                    new XDeclaration("1.0", "utf-8", null),
                    new XElement(xmins + "XMI", new XAttribute(XNamespace.Xmlns + "uml", "http://www.omg.org/spec/UML/20131001"),
                                 new XAttribute(XNamespace.Xmlns + "xmi", "http://www.omg.org/spec/XMI/20131001"),
                                 new XElement(xmins + "Documentation", new XAttribute("exporter", "Enterprise Architect"), new XAttribute("exporterVersion", "6.5")),
                                 new XElement(umlns + "Model", new XAttribute(xmins + "type", "uml:Model"), new XAttribute("name", "EA_Model"), xmodel),
                                 new XElement(xmins + "Extension", new XAttribute("extender", "Enterprise Architect"), new XAttribute("extenderID", "6.5"),
                                              new XElement("diagrams", new XElement("diagram", new XAttribute(xmins + "id", CreateId("ModelDiagram")),
                                                                                    new XElement("model", new XAttribute("package", projectName), new XAttribute("localID", "28"), new XAttribute("owner", projectName)),
                                                                                    new XElement("properties", new XAttribute("name", projectName), new XAttribute("type", "Logical")),
                                                                                    new XElement("project", new XAttribute("author", "computer"), new XAttribute("version", "1.0"), new XAttribute("created", currentTime),
                                                                                                 new XAttribute("modified", currentTime)),
                                                                                    new XElement("style1", new XAttribute("value", "ShowPrivate=1;ShowProtected=1;ShowPublic=1;HideRelationships=0;Locked=0;Border=1;HighlightForeign=1;" +
                                                                                                                          "PackageContents=1;SequenceNotes=0;ScalePrintImage=0;PPgs.cx=1;PPgs.cy=1;DocSize.cx=815;DocSize.cy=1067;ShowDetails=0;Orientation=P;" +
                                                                                                                          "Zoom=100;ShowTags=0;OpParams=1;VisibleAttributeDetail=0;ShowOpRetType=1;ShowIcons=1;CollabNums=0;HideProps=0;ShowReqs=0;ShowCons=0;PaperSize=1;" +
                                                                                                                          "HideParents=0;UseAlias=0;HideAtts=0;HideOps=0;HideStereo=0;HideElemStereo=0;ShowTests=0;ShowMaint=0;ConnectorNotation=UML 2.1;ExplicitNavigability=0;" +
                                                                                                                          "ShowShape=1;AdvancedElementProps=1;AdvancedFeatureProps=1;AdvancedConnectorProps=1;m_bElementClassifier=1;ShowNotes=0;SuppressBrackets=0;SuppConnectorLabels=0;" +
                                                                                                                          "PrintPageHeadFoot=0;ShowAsList=0;")),
                                                                                    new XElement("style2", new XAttribute("value", "ExcludeRTF=0;DocAll=0;HideQuals=0;AttPkg=1;ShowTests=0;ShowMaint=0;" +
                                                                                                                          "SuppressFOC=1;MatrixActive=0;SwimlanesActive=1;KanbanActive=0;MatrixLineWidth=1;MatrixLineClr=0;MatrixLocked=0;TConnectorNotation=UML 2.1;TExplicitNavigability=0;" +
                                                                                                                          "AdvancedElementProps=1;AdvancedFeatureProps=1;AdvancedConnectorProps=1;m_bElementClassifier=1;ProfileData=;MDGDgm=;STBLDgm=;ShowNotes=0;VisibleAttributeDetail=0;" +
                                                                                                                          "ShowOpRetType=1;SuppressBrackets=0;SuppConnectorLabels=0;PrintPageHeadFoot=0;ShowAsList=0;SuppressedCompartments=;Theme=:119;SaveTag=D7ED2A20;")),
                                                                                    new XElement("swimlanes", new XAttribute("value", "locked=false;orientation=0;width=0;inbar=false;names=false;color=-1;bold=false;fcol=0;tcol=-1;ofCol=-1;ufCol=-1;" +
                                                                                                                             "hl=0;ufh=0;cls=0;SwimlaneFont=lfh:-10,lfw:0,lfi:0,lfu:0,lfs:0,lfface:Calibri,lfe:0,lfo:0,lfchar:1,lfop:0,lfcp:0,lfq:0,lfpf=0,lfWidth=0;")),
                                                                                    new XElement("matrixitems", new XAttribute("value", "locked=false;matrixactive=false;swimlanesactive=true;kanbanactive=false;width=1;clrLine=0;")),
                                                                                    new XElement("extendedProperties"), diagramElements)))));
            }


            //write collection to file
            using (StreamWriter outputFile = new StreamWriter(Path.Combine(TargetDirectory, "uml" + ".xmi.xml")))
            {
                XmlTextWriter writer = new XmlTextWriter(outputFile);
                writer.Formatting = Formatting.Indented;
                xDoc.WriteTo(writer);
                writer.Flush();
            }
        }
Exemple #13
0
        public void Publish(CogsModel model)
        {
            //if (CogsLocation == null)
            //{
            //    throw new InvalidOperationException("Cogs location must be specified");
            //}
            if (TargetDirectory == null)
            {
                throw new InvalidOperationException("Target directory must be specified");
            }

            if (Overwrite && Directory.Exists(TargetDirectory))
            {
                Directory.Delete(TargetDirectory, true);
            }

            Directory.CreateDirectory(TargetDirectory);
            settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            settings.Formatting            = Formatting.Indented;
            settings.Converters.Add(new JsonSchemaConverter());
            settings.ContractResolver     = new CamelCasePropertyNamesContractResolver();
            settings.DefaultValueHandling = DefaultValueHandling.Ignore;

            ReusableStorage = model.ReusableDataTypes;
            ItemTypeStorage = model.ItemTypes;
            //create a list to store jsonschema for each itemtype
            var root = new SchemaList();
            List <JsonSchema> items = new List <JsonSchema>();

            JsonSchema   reference_node = new JsonSchema();
            ReusableType reference_def  = new ReusableType();

            reference_def.Name = "~~reference~~";

            reference_node.Title = "~~reference~~";
            items.Add(reference_node);
            List <ReusableType> define = Iteratereusable(model);

            define.Add(reference_def);

            Iterate(model, items);

            root.Schema      = "http://json-schema.org/draft-04/schema#";
            root.Id          = "#root";
            root.Properties  = items;
            root.SimpleType  = "root";
            root.definitions = define;

            if (!AdditionalProp)
            {
                foreach (var prop in root.Properties)
                {
                    prop.AddProp = false;
                }
                foreach (var prop in root.definitions)
                {
                    prop.AddProp = false;
                }
            }
            else
            {
                foreach (var prop in root.Properties)
                {
                    prop.AddProp = true;
                }
                foreach (var prop in root.definitions)
                {
                    prop.AddProp = true;
                }
            }
            //Console.WriteLine(JsonConvert.SerializeObject(root, settings));
            string res = JsonConvert.SerializeObject(root, settings);

            File.WriteAllText(Path.Combine(TargetDirectory, "jsonSchema" + ".json"), res);
        }