private static IEnumerable <Class> GenerateClasses(IList <Table> tables)
        {
            var fileNames = new List <string>();

            return((
                       from table in tables
                       let uniqueName = GenerateUniqueTableName(fileNames, table.Name.LegalCsharpName)
                                        let classTemplate = ClassTemplateGenerator.Generate(table, uniqueName)
                                                            let content = ClassRenderer.Render(classTemplate)
                                                                          select new Class($"{uniqueName}.cs", $"Entities\\{table.SchemaName}", content, table)
                       ).ToList());
        }
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine("--------Class generator--------");
            Console.WriteLine("Example connection string: Persist Security Info=False;User ID=MY_SQL_USER;Password=MY_SQL_PASSWORD;Server=localhost,1433; Initial Catalog=MY_CATALOG_NAME");
            Console.Write("Enter connection string: ");
            var cs = Console.ReadLine();

            Console.Write("Enter namespace: ");
            var namespaceName = Console.ReadLine();

            Console.Write("Enter output path: ");
            var outputPath = Console.ReadLine();

            if (!Directory.Exists(outputPath))
            {
                Directory.CreateDirectory(outputPath);
            }

            var explorer = new SqlServerSchemaExplorer(cs);
            var tables   = await explorer.GetTablesAsync(CancellationToken.None);

            var renderer = new ClassRenderer();

            foreach (var table in tables)
            {
                Console.WriteLine("Class:");
                var content = renderer.Render(new ClassTemplate
                {
                    Namespace  = namespaceName,
                    Properties = table.Columns,
                    TypeName   = table.Name.LegalCsharpName
                });
                Console.WriteLine(content);
                var fileName = Path.Join(outputPath, $"{table.Name.LegalCsharpName}.cs");
                Console.WriteLine($"Saving it to disk, see {fileName}");
                File.WriteAllLines(fileName, content.Split(Environment.NewLine));
            }

            Console.WriteLine("Done.");

            _applicationLifetime.StopApplication();
        }
Esempio n. 3
0
        private string GenerateFactoryMethod(TypeReference tr, string ownerNs)
        {
            StringWriter sw = new StringWriter();

            Dictionary <string, string[]> cfm = ClassRenderer.CreateFactoryMethod(tr, "retVal", true);


            if (tr.Class != null && tr.Class.IsAbstract)
            {
                foreach (var chld in tr.Class.SpecializedBy)
                {
                    sw.WriteLine(GenerateFactoryMethod(chld, ownerNs));
                }
            }
            else
            {
                string factoryName = String.Format("Create{0}", tr.Class.Name), tfact = factoryName;
                if (generatedFactoryMethods.Contains(factoryName))
                {
                    factoryName = String.Format("Create{0}", Util.Util.MakeFriendly(tr.Name));
                }
                generatedFactoryMethods.Add(factoryName);

                // Iterate and create shortcuts
                List <String> wroteParms = new List <string>(); // Keep track of the parameters used
                foreach (KeyValuePair <String, String[]> kv in cfm)
                {
                    if (kv.Value[0].Length == 0 || wroteParms.Contains(kv.Value[0]))
                    {
                        continue;
                    }

                    wroteParms.Add(kv.Value[0]);

                    // Correct generic children
                    // TODO: Turn these into regexes
                    //if (tr.Class.TypeParameters != null)
                    //    for (int i = 0; i < tr.Class.TypeParameters.Count; i++)
                    //    {
                    //        List<TypeReference> filler = tr.GenericSupplier == null ? new List<TypeReference>() : tr.GenericSupplier.FindAll(o => (o as TypeParameter).ParameterName == tr.Class.TypeParameters[i].ParameterName);

                    //        for(int f = 0; f< 2; f++)
                    //            if (filler.Count == 1)
                    //                foreach(string replacement in replaceMe)
                    //                    kv.Value[f] = kv.Value[f].Replace(String.Format(replacement, tr.Class.TypeParameters[i].ParameterName), String.Format(replacement, filler[0].Name));
                    //            else
                    //                foreach (string replacement in replaceMe)
                    //                    kv.Value[f] = kv.Value[f].Replace(String.Format(replacement, tr.Class.TypeParameters[i].ParameterName), String.Format(replacement, "System.Object"));
                    //    }

                    // Generate method(s)
                    Class cls = tr.Class;
                    sw.WriteLine("\t\t/// <summary> Create a new instance of {0} to populate {1} </summary>", tr.Name, tr is TypeParameter ? (tr as TypeParameter).ParameterName : "");
                    sw.Write(kv.Value[2]);
                    sw.WriteLine("\t\tpublic static {0} {1} ({2}) {{ \r\n\t\t\t{0} retVal = new {0}();\r\n{3}", ClassRenderer.CreateDatatypeRef(tr, new Property()), factoryName,
                                 kv.Value[0].Substring(0, kv.Value[0].Length - 1), kv.Value[1]);
                    sw.WriteLine("\t\t\treturn retVal;\r\n\t\t}");

                    if (!wroteParms.Contains(""))
                    {
                        wroteParms.Add("");
                        sw.WriteLine("\t\t/// <summary> Create a new instance of {0} to populate {1} </summary>", tr.Name, tr.Class.Name);
                        sw.WriteLine("\t\tpublic static {0} {1} () {{ \r\n\t\t\treturn new {0}();\r\n\t\t}}", ClassRenderer.CreateDatatypeRef(tr, new Property()), factoryName);
                    }
                }


                foreach (TypeReference tpr in tr.GenericSupplier ?? new List <TypeReference>())
                {
                    sw.WriteLine(GenerateFactoryMethod(tpr, ownerNs));
                }
            }

            return(sw.ToString());
        }
Esempio n. 4
0
        public void Render(string OwnerNS, string apiNs, Feature f, System.IO.TextWriter tw)
        {
            this.generatedFactoryMethods = new List <string>();
            // Get a strongly typed reference to the
            Interaction interaction = f.Clone() as Interaction;

            interaction.MemberOf = f.MemberOf;

            StringWriter sw = new StringWriter();

            #region Usings

            // Validate Usings
            string[] usings = new string[] { "Attributes", "Interfaces", "DataTypes", "DataTypes.Primitives" };
            // API usings
            foreach (string s in usings)
            {
                sw.WriteLine("using {1}.{0};", s, apiNs);
            }

            // Owner Usings
            foreach (String s in GatherUsings(interaction.MessageType))
            {
                sw.WriteLine("using {0}.{1};", OwnerNS, s);
            }

            if (f.MemberOf.Find(o => o is Enumeration) != null)
            {
                sw.WriteLine("using {0}.Vocabulary;", OwnerNS);
            }
            #endregion

            // HACK: If there is no description on the interaction then we'll
            // HACK: add the business name as a description
            // TODO: Remove this and come up with a better solution
            if (interaction.Documentation == null ||
                interaction.Documentation.Description == null)
            {
                interaction.Documentation = new Documentation()
                {
                    Description = new List <string>()
                    {
                        interaction.BusinessName
                    }
                }
            }
            ;

            // Determine if the interaction is an IInteraction
            bool     isIInteraction = true;
            string[] members        =
            {
                "creationtime",
                "versioncode",
                "interactionid",
                "processingmodecode"
            };
            foreach (var m in members)
            {
                isIInteraction &= interaction.MessageType.Class.Content.Exists(o => o.Name.ToLower() == m);
            }


            sw.WriteLine("namespace {0}.Interactions {{\r\n", OwnerNS);
            var vLength = sw.ToString().Length;
            sw.Write(DocumentationRenderer.Render(interaction.Documentation, 1));
            if (sw.ToString().Length == vLength)
            {
                sw.WriteLine("\t/// <summary>{0}</summary>", interaction.BusinessName != null ? interaction.BusinessName.Replace("\n", "").Replace("\r", "") : interaction.Name);
            }
            sw.WriteLine("\t[Structure(Name = \"{0}\", StructureType = StructureAttribute.StructureAttributeType.Interaction)]", interaction.Name);
            sw.WriteLine("\t[Interaction(TriggerEvent = \"{0}\")]", interaction.TriggerEvent);
            sw.WriteLine("\t#if !WINDOWS_PHONE");
            sw.WriteLine("\t[Serializable]");
            sw.WriteLine("\t#endif");
            sw.WriteLine("\t[System.CodeDom.Compiler.GeneratedCode(\"gpmr\",\"{0}\")]", Assembly.GetEntryAssembly().GetName().Version.ToString());
            foreach (Interaction response in interaction.Responses)
            {
                sw.WriteLine("\t[InteractionResponse(Name = \"{0}\", TriggerEvent = \"{1}\")]", response.Name, response.TriggerEvent);
            }
            sw.WriteLine("\t[System.ComponentModel.Description(\"{0}\")]", interaction.BusinessName != null ? interaction.BusinessName.Replace("\n", "").Replace("\r", "") : interaction.Name);
            sw.WriteLine("\tpublic class {0} : {1}{2} {{", interaction.Name, CreateInteractionDatatype(interaction.MessageType), isIInteraction ? ", MARC.Everest.Interfaces.IInteraction" : "");

            #region Constants

            // Get the trigger event
            sw.WriteLine("\t\t/// <summary> Gets the default trigger event to be used for this interaction </summary>");
            sw.WriteLine("\t\tpublic static CV<String> GetTriggerEvent() {{ return new CV<String>(\"{0}\", \"{1}\"); }}", interaction.TriggerEvent, triggerEventOid);

            // Get the interaction id
            sw.WriteLine("\t\t/// <summary> Gets the interaction ID of this interaction </summary>");
            sw.WriteLine("\t\tpublic static II GetInteractionId() {{ return new II(new OID(\"{1}\"), \"{0}\"); }}", interaction.Name, interactionIdOid);

            // Get the profile id
            if (!String.IsNullOrEmpty(profileId))
            {
                sw.WriteLine("\t\t/// <summary> Gets the profile id of this interaction </summary>");
                sw.WriteLine("\t\tpublic static LIST<II> GetProfileId() {{ return new LIST<II>() {{ new II (new OID(\"{0}\"), \"{1}\") }}; }}", profileIdOid, profileId);
            }


            #endregion

            #region Constructors

            sw.WriteLine("\t\t/// <summary> Creates a new, empty instance of {0} </summary>", interaction.Name);
            sw.WriteLine("\t\tpublic {0}() : base() {{ }}\r\n", interaction.Name);

            //string ctor_parameters = "";
            //string ctor_body = "";
            //foreach (ClassContent cc in interaction.MessageType.Class.Content)
            //{
            //    if (cc.Conformance == ClassContent.ConformanceKind.Mandatory) // Mandatory ctor
            //    {
            //        if (cc is Property && ((cc as Property).FixedValue == null || (cc as Property).PropertyType == Property.PropertyTypes.TraversableAssociation))
            //        {
            //            Property p = cc as Property;
            //            TypeReference tr = Datatypes.MapDatatype(p.Type);

            //            // Documentation
            //            if (p.Documentation != null && p.Documentation.Definition != null && p.Documentation.Definition.Count > 0)
            //                sw.WriteLine("\t\t/// <param name=\"{0}\">{1}</param>", p.Name, p.Documentation.Definition[0]);

            //            // Now the signature
            //            ctor_parameters += string.Format("{0} {1},", ClassRenderer.CreateDatatypeRef(tr, p), p.Name);
            //            ctor_body += string.Format("\t\t\tthis.{0} = {1};\r\n", Util.Util.PascalCase(p.Name), p.Name);

            //        }
            //        else
            //        {
            //        }
            //    }
            //}

            //// Write CTOR
            //if (ctor_parameters.Length > 0)
            //{
            //    sw.WriteLine("\t\t/// <summary>\r\n\t\t/// CTOR for all mandatory elements\r\n\t\t/// </summary>");
            //    sw.WriteLine("\t\tpublic {0}({1}) : base() {{ \r\n\t\t{2}\t\t}}", interaction.Name, ctor_parameters.Substring(0, ctor_parameters.Length - 1), ctor_body);
            //}

            Dictionary <String, String[]> ctors = ClassRenderer.CreateFactoryMethod(interaction.MessageType, "this", true);

            // Write CTOR
            List <String> wroteParms = new List <string>(); // Keep track of the parameters used
            foreach (KeyValuePair <String, String[]> kv in ctors)
            {
                if (kv.Value[0].Length > 0 && !wroteParms.Contains(kv.Value[0]))
                {
                    wroteParms.Add(kv.Value[0]);
                    sw.WriteLine("\t\t/// <summary>\r\n\t\t/// CTOR for all {0} elements\r\n\t\t/// </summary>", kv.Key);
                    sw.WriteLine(kv.Value[2]);
                    sw.WriteLine("\t\tpublic {0}({1}) : base() {{ \r\n\t\t{2}\t\t}}", interaction.Name, kv.Value[0].Substring(0, kv.Value[0].Length - 1), kv.Value[1]);
                }
            }
            #endregion

            #region Creator for payload, control act, etc...

            // Owner namespace
            if (interaction.MessageType.GenericSupplier != null)
            {
                foreach (TypeReference tr in interaction.MessageType.GenericSupplier)
                {
                    sw.WriteLine(GenerateFactoryMethod(tr, OwnerNS));
                }
            }



            if (isIInteraction)
            {
                // Version code
                sw.WriteLine("\t\t/// <summary>Implementation of version code</summary>");
                sw.WriteLine("\t\tMARC.Everest.DataTypes.Interfaces.ICodedSimple MARC.Everest.Interfaces.IInteraction.VersionCode { get { return this.VersionCode; } }");

                // Version code
                sw.WriteLine("\t\t/// <summary>Implementation of processing mode code</summary>");
                sw.WriteLine("\t\tMARC.Everest.DataTypes.Interfaces.ICodedSimple MARC.Everest.Interfaces.IInteraction.ProcessingModeCode { get { return this.ProcessingModeCode; } }");

                sw.WriteLine("\t\t/// <summary>Implementation of generic IInteraction.ControlActEvent Property</summary>");
                // Create the control act event
                if (interaction.MessageType.GenericSupplier != null && interaction.MessageType.GenericSupplier.Count > 0)
                {
                    Property cactProperty = interaction.MessageType.Class.Content.Find(o => o is Property && (o as Property).Type.Name == interaction.MessageType.Class.TypeParameters[0].ParameterName) as Property;
                    if (cactProperty == null)
                    {
                        ;
                    }

                    string cactName = cactProperty.Type.Name == interaction.MessageType.Class.TypeParameters[0].ParameterName ? Util.Util.MakeFriendly(cactProperty.Name) : Util.Util.PascalCase(cactProperty.Name);
                    sw.WriteLine("\t\tSystem.Object MARC.Everest.Interfaces.IInteraction.ControlAct {");
                    sw.WriteLine("\t\t\tget {{ return this.{0}; }}", cactName);
                    sw.WriteLine("\t\t\tset {{ this.{1} = value as {0}; }}", CreateInteractionDatatype(interaction.MessageType.GenericSupplier[0]), cactName);
                    sw.WriteLine("\t\t}");
                }
                else
                {
                    sw.WriteLine("\t\tSystem.Object MARC.Everest.Interfaces.IInteraction.ControlAct {");
                    sw.WriteLine("\t\t\tget { return null; }");
                    sw.WriteLine("\t\t\tset { ; }");
                    sw.WriteLine("\t\t}");
                }
            }
            #endregion

            sw.WriteLine("\t}");
            sw.WriteLine("}");
            tw.WriteLine(sw);
        }
Esempio n. 5
0
        public void Render(string ownerPackage, string apiNs, Feature f, System.IO.TextWriter tw)
        {
            ClassRenderer.s_imports.Clear();

            // Validate arguments
            if (String.IsNullOrEmpty(ownerPackage))
            {
                throw new ArgumentNullException("ownerPackage");
            }
            if (String.IsNullOrEmpty(apiNs))
            {
                throw new ArgumentNullException("apiNs");
            }
            if (f == null || !(f is Interaction))
            {
                throw new ArgumentException("Parameter must be of type Enumeration", "f");
            }

            this.generatedFactoryMethods = new List <string>();
            // Get a strongly typed reference to the
            Interaction interaction = f.Clone() as Interaction;

            interaction.MemberOf = f.MemberOf;

            StringWriter sw = new StringWriter();

            #endregion

            // HACK: If there is no description on the interaction then we'll
            // HACK: add the business name as a description
            // TODO: Remove this and come up with a better solution
            if (interaction.Documentation == null ||
                interaction.Documentation.Description == null)
            {
                interaction.Documentation = new Documentation()
                {
                    Description = new List <string>()
                    {
                        interaction.BusinessName
                    }
                }
            }
            ;

            // Determine if this class is an interaction
            bool     isIInteraction = true;
            string[] members        =
            {
                "creationtime",
                "versioncode",
                "interactionid",
                "processingmodecode"
            };
            foreach (var m in members)
            {
                isIInteraction &= interaction.MessageType.Class.Content.Exists(o => o.Name.ToLower() == m);
            }


            sw.Write(DocumentationRenderer.Render(interaction.Documentation, 0));
            sw.WriteLine("@Structure(name = \"{0}\", structureType = StructureType.INTERACTION)", interaction.Name);
            sw.WriteLine("@Interaction(name=\"{1}\", triggerEvent = \"{0}\")", interaction.TriggerEvent, interaction.Name);
            sw.WriteLine("@InteractionResponses( value = {");
            List <String> resp = new List <string>();
            foreach (Interaction response in interaction.Responses)
            {
                if (resp.Contains(response.Name))
                {
                    continue;
                }
                sw.WriteLine("\t@Interaction(name = \"{0}\", triggerEvent = \"{1}\"){2}", response.Name, response.TriggerEvent, response == interaction.Responses.Last() ? "" : ",");
                resp.Add(response.Name);
            }
            sw.WriteLine("})");
            sw.WriteLine("public class {0} extends {1} {2} {{", interaction.Name, CreateInteractionDatatype(interaction.MessageType, ownerPackage),
                         isIInteraction ? "implements IInteraction" : "");

            #region Constants

            // Get the trigger event
            sw.WriteLine("\t/** Gets the default trigger event to be used for this interaction */");
            sw.WriteLine("\tpublic static CV<String> defaultTriggerEvent() {{ return new CV<String>(\"{0}\", \"{1}\"); }}", interaction.TriggerEvent, triggerEventOid, apiNs);

            // Get the interaction id
            sw.WriteLine("\t/** Gets the interaction ID of this interaction */");
            sw.WriteLine("\tpublic static II defaultInteractionId() {{ return new II(\"{1}\", \"{0}\"); }}", interaction.Name, interactionIdOid, apiNs);

            // Get the profile id
            if (!String.IsNullOrEmpty(profileId))
            {
                sw.WriteLine("\t/** Gets the profile id of this interaction */");
                sw.WriteLine("\tpublic static LIST<II> defaultProfileId() {{ LIST<II> retVal = new LIST<II>(); retVal.add(new II (\"{0}\", \"{1}\")); return retVal; }}", profileIdOid, profileId, apiNs);
            }


            #endregion

            #region Constructors

            sw.WriteLine("\t/** Creates a new, empty instance of {0} */", interaction.Name);
            sw.WriteLine("\tpublic {0}() {{ super(); }}\r\n", interaction.Name);

            //string ctor_parameters = "";
            //string ctor_body = "";
            //foreach (ClassContent cc in interaction.MessageType.Class.Content)
            //{
            //    if (cc.Conformance == ClassContent.ConformanceKind.Mandatory) // Mandatory ctor
            //    {
            //        if (cc is Property && ((cc as Property).FixedValue == null || (cc as Property).PropertyType == Property.PropertyTypes.TraversableAssociation))
            //        {
            //            Property p = cc as Property;
            //            TypeReference tr = Datatypes.MapDatatype(p.Type);

            //            // Documentation
            //            if (p.Documentation != null && p.Documentation.Definition != null && p.Documentation.Definition.Count > 0)
            //                sw.WriteLine("\t\t/// <param name=\"{0}\">{1}</param>", p.Name, p.Documentation.Definition[0]);

            //            // Now the signature
            //            ctor_parameters += string.Format("{0} {1},", ClassRenderer.CreateDatatypeRef(tr, p), p.Name);
            //            ctor_body += string.Format("\t\t\tthis.{0} = {1};\r\n", Util.Util.PascalCase(p.Name), p.Name);

            //        }
            //        else
            //        {
            //        }
            //    }
            //}

            //// Write CTOR
            //if (ctor_parameters.Length > 0)
            //{
            //    sw.WriteLine("\t\t/// <summary>\r\n\t\t/// CTOR for all mandatory elements\r\n\t\t/// </summary>");
            //    sw.WriteLine("\t\tpublic {0}({1}) : base() {{ \r\n\t\t{2}\t\t}}", interaction.Name, ctor_parameters.Substring(0, ctor_parameters.Length - 1), ctor_body);
            //}

            Dictionary <String, String[]> ctors = ClassRenderer.CreateFactoryMethod(interaction.MessageType, "this", true, ownerPackage);

            // Write CTOR
            List <String> wroteParms = new List <string>(); // Keep track of the parameters used
            foreach (KeyValuePair <String, String[]> kv in ctors)
            {
                if (kv.Value[0].Length > 0 && !wroteParms.Contains(kv.Value[0]))
                {
                    wroteParms.Add(kv.Value[0]);
                    sw.WriteLine("\t/**\r\n\t * CTOR for all {0} elements\r\n\t", kv.Key);
                    sw.WriteLine(kv.Value[2]);
                    sw.WriteLine("\t*/\r\n\tpublic {0}({1}) {{ \r\n\t\tsuper();\r\n{2}\t}}", interaction.Name, kv.Value[0].Substring(0, kv.Value[0].Length - 1), kv.Value[1]);
                }
            }
            #endregion

            #region Creator for payload, control act, etc...

            // Owner namespace
            if (interaction.MessageType.GenericSupplier != null)
            {
                foreach (TypeReference tr in interaction.MessageType.GenericSupplier)
                {
                    sw.WriteLine(GenerateFactoryMethod(tr, ownerPackage));
                }
            }

            #endregion


            #region Interaction members

            if (isIInteraction)
            {
                sw.WriteLine("\t\t/** Implementation of generic IInteraction.ControlActEvent Property */");
                // Create the control act event
                if (interaction.MessageType.GenericSupplier != null && interaction.MessageType.GenericSupplier.Count > 0)
                {
                    Property cactProperty = interaction.MessageType.Class.Content.Find(o => o is Property && (o as Property).Type.Name == interaction.MessageType.Class.TypeParameters[0].ParameterName) as Property;
                    if (cactProperty == null)
                    {
                        ;
                    }

                    string cactName = Util.Util.PascalCase(cactProperty.Name);
                    sw.WriteLine("\t\tObject getControlAct() {");
                    sw.WriteLine("\t\t\treturn this.get{0}();", cactName);
                    sw.WriteLine("\t\t}");
                }
                else
                {
                    sw.WriteLine("\t\tObject getControlAct() {");
                    sw.WriteLine("\t\t\treturn null;");
                    sw.WriteLine("\t\t}");
                }
            }
            #endregion

            sw.WriteLine("}");

            #region Usings

            // Interactions package
            tw.WriteLine("package {0}.interaction;", ownerPackage);

            #region Render the imports
            string[] apiImports = { "annotations.*", "datatypes.*", "datatypes.generic.*", "interfaces.IGraphable", "interfaces.IInteraction" },
            jImports = { "java.lang.*", "java.util.*" };
            foreach (var import in apiImports)
            {
                tw.WriteLine("import {0}.{1};", apiNs, import);
            }
            foreach (var import in jImports)
            {
                tw.WriteLine("import {0};", import);
            }
            foreach (var import in ClassRenderer.s_imports)
            {
                tw.WriteLine("import {0};", import);
            }
            #endregion

            tw.WriteLine(sw.ToString());
        }
Esempio n. 6
0
        /// <summary>
        /// Render the factory
        /// </summary>
        public void Render(string ownerPackage, string apiNs, Feature f, System.IO.TextWriter tw)
        {
            ClassRenderer.s_imports.Clear();
            // Validate arguments
            if (String.IsNullOrEmpty(ownerPackage))
            {
                throw new ArgumentNullException("ownerPackage");
            }
            if (String.IsNullOrEmpty(apiNs))
            {
                throw new ArgumentNullException("apiNs");
            }
            if (f == null || !(f is Class))
            {
                throw new ArgumentException("Parameter must be of type Class", "f");
            }

            // Create a local copy of the class
            Class cls = f as Class;

            StringWriter sw = new StringWriter();

            tw.WriteLine("package {0}.{1};", ownerPackage, cls.ContainerName.ToLower());


            #region Render Class Signature

            // Documentation
            if (DocumentationRenderer.Render(cls.Documentation, 0).Length == 0)
            {
                sw.WriteLine("\t/** No Summary Documentation Found */");
            }
            else
            {
                sw.Write(DocumentationRenderer.Render(cls.Documentation, 0));
            }

            // Create class signature
            sw.Write("public final class {0}Factory", Util.Util.PascalCase(cls.Name));

            // If class is generic class
            string genericString = String.Empty;
            foreach (TypeParameter tp in cls.TypeParameters ?? new List <TypeParameter>())
            {
                genericString += tp + ",";
            }
            if (!String.IsNullOrEmpty(genericString))
            {
                genericString = String.Format("<{0}>", genericString.Substring(0, genericString.Length - 1)); // get rid of trailing ,
            }
            sw.WriteLine("{");

            #endregion

            sw.WriteLine("\tprivate {0}Factory() {{ super(); }}\r\n", Util.Util.PascalCase(cls.Name));


            // Create newInstanceMethod
            sw.WriteLine("\tpublic static final {0} {1}Factory newInstance() {{", cls.TypeParameters != null && cls.TypeParameters.Count > 0 ? string.Format("<{0}>", genericString) : "", Util.Util.PascalCase(cls.Name));
            sw.WriteLine("\t\treturn new {0}Factory{1}();", Util.Util.PascalCase(cls.Name), genericString);
            sw.WriteLine("\t}");

            // Move to a factory
            // Is this an emtpy class that facilitates a choice?
            if (cls.SpecializedBy != null && cls.SpecializedBy.Count > 0 &&
                cls.IsAbstract)
            {
                //// NB: In Java apparently super classes' static methods are acceessable
                ////     in child classes which is different than .NET, so we're not going to cascade specializers
                foreach (TypeReference tr in cls.SpecializedBy)
                {
                    if (tr.Class == null || tr.Class.ContainerName == "RIM" && !RimbaJavaRenderer.GenerateRim ||
                        tr.Class.IsAbstract)
                    {
                        continue;
                    }

                    Class child = tr.Class;

                    // Create factory for the child
                    Dictionary <String, String[]> ctors = ClassRenderer.CreateFactoryMethod(tr, "retVal", ownerPackage);
                    // Write factory
                    foreach (var kv in ctors)
                    {
                        string methodSignature = String.Format("{1}.{0}.{2}.create{3}", cls.ContainerName, ownerPackage, Util.Util.PascalCase(cls.Name), Util.Util.PascalCase(child.Name)),
                                 publicName    = methodSignature;

                        // Regex for extracting the parameter type rather than the type/name
                        Regex           parmRegex   = new Regex(@"(([\w<>,.]*)\s(\w*)),?\s?");
                        MatchCollection parmMatches = parmRegex.Matches(kv.Value[0]);
                        foreach (Match match in parmMatches)
                        {
                            methodSignature += match.Groups[1].Value.Substring(0, match.Groups[1].Value.IndexOf(" "));
                        }


                        // JF: Added to protected against rendering the same factory method
                        if (s_methodDeclarations.Contains(methodSignature))
                        {
                            continue;
                        }
                        s_methodDeclarations.Add(methodSignature);

                        // Render if there is even any content
                        if (kv.Value[0].Length > 0)
                        {
                            string clsDoc = DocumentationRenderer.Render(child.Documentation, 1);

                            string ctorClassName = String.Format("{0}.{2}.{1}", ownerPackage, tr.Class.Name, tr.Class.ContainerName.ToLower());
                            //// import already exists?
                            //if(!s_imports.Exists(o=>o.EndsWith(Util.Util.PascalCase(tr.Class.Name))))
                            //{
                            //    s_imports.Add(ctorClassName);
                            //    ctorClassName = ctorClassName.Substring(ctorClassName.LastIndexOf(".") + 1);
                            //}
                            //if (s_imports.Contains(ctorClassName))
                            //    ctorClassName = ctorClassName.Substring(ctorClassName.LastIndexOf(".") + 1);

                            if (clsDoc.Contains("*/"))
                            {
                                sw.Write(clsDoc.Substring(0, clsDoc.LastIndexOf("*/")));
                            }
                            sw.WriteLine("* This function creates a new instance of {5}.{1}\r\n\t {4}\r\n\t*/\t\n\tpublic final {0} create{2}({3}) {{ ", ctorClassName, tr.Class.Name, Util.Util.PascalCase(child.Name), kv.Value[0].Substring(0, kv.Value[0].Length - 1), kv.Value[2], tr.Class.ContainerName.ToLower(), Util.Util.PascalCase(cls.Name)
                                         );
                            sw.WriteLine("\t\t{0} retVal = new {0}();", ctorClassName);
                            sw.WriteLine("{0}", kv.Value[1]);
                            sw.WriteLine("\t\treturn retVal;");
                            sw.WriteLine("\t}");

                            if (!factoryMethods.ContainsKey(tr.Name))
                            {
                                factoryMethods.Add(tr.Name, new List <MohawkCollege.EHR.gpmr.Pipeline.Renderer.Java.Renderer.ClassRenderer.FactoryMethodInfo>());
                            }

                            MohawkCollege.EHR.gpmr.Pipeline.Renderer.Java.Renderer.ClassRenderer.FactoryMethodInfo myInfo = new MohawkCollege.EHR.gpmr.Pipeline.Renderer.Java.Renderer.ClassRenderer.FactoryMethodInfo(publicName, kv.Value[2], methodSignature);


                            //Match the regular expression below and capture its match into backreference number 1 «(([\w<>,]*?)\s(\w*),?\s?)»
                            //Match the regular expression below and capture its match into backreference number 2 «([\w<>,]*?)»
                            //Match a single character present in the list below «[\w<>,]*?»
                            //Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
                            //A word character (letters, digits, etc.) «\w»
                            //One of the characters “<>,” «<>,»
                            //Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.) «\s»
                            //Match the regular expression below and capture its match into backreference number 3 «(\w*)»
                            //Match a single character that is a “word character” (letters, digits, etc.) «\w*»
                            //Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
                            //Match the character “,” literally «,?»
                            //Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
                            //Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.) «\s?»
                            //Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
                            foreach (Match match in parmMatches)
                            {
                                myInfo.parameters.Add(match.Groups[1].Value);
                            }

                            // ADd the factory signature to the dictionary
                            factoryMethods[tr.Name].Add(myInfo);
                        }
                    }
                }

                //#endregion
            }
            // End class
            sw.WriteLine("}");


            #region Render the imports
            string[] apiImports = { "annotations.*", "datatypes.*", "datatypes.generic.*" },
            jImports = { "java.lang.*", "java.util.*" };
            foreach (var import in apiImports)
            {
                tw.WriteLine("import {0}.{1};", apiNs, import);
            }
            foreach (var import in jImports)
            {
                tw.WriteLine("import {0};", import);
            }
            foreach (var import in ClassRenderer.s_imports)
            {
                if (!import.EndsWith(String.Format(".{0}", Util.Util.PascalCase(f.Name))))
                {
                    tw.WriteLine("import {0};", import);
                }
            }

            tw.WriteLine(sw.ToString());
            #endregion

            if (cls.ContainerName == "RIM" && String.Format("{0}.rim.{1}", ownerPackage, Util.Util.PascalCase(cls.Name)) != RimbaJavaRenderer.RootClass && !RimbaJavaRenderer.GenerateRim)
            {
                throw new NotSupportedException("RIM Elements will not be rendered");
            }
        }
Esempio n. 7
0
 public void TearDown()
 {
     _basic = null;
 }
Esempio n. 8
0
 public void SetUp()
 {
     _basic = new ClassRenderer("TestNamespace", "TestClass");
 }
Esempio n. 9
0
        /// <summary>
        /// Get overridden setters
        /// </summary>
        public static SetterOverrideData[] GetOverrideSetters(TypeReference tr, Property p, string ownerPackage)
        {
            // Not a datatype so we won't need overrides
            if (tr.Class != null)
            {
                return(new SetterOverrideData[0]);
            }

            // Get all the setter overrides
            var dataType = s_heuristicData.Datatypes.Find(o => o.MifDatatype == tr.Name);

            // Sanity check
            if (dataType == null || dataType.SetterOverride.Count == 0)
            {
                return(new SetterOverrideData[0]);
            }

            // Set generic paramaters
            Dictionary <String, String> bind = new Dictionary <string, string>();
            string fillParameter             = dataType.TemplateParameter;

            if (!String.IsNullOrEmpty(dataType.TemplateParameter))
            {
                int i = 0;
                foreach (string s in dataType.TemplateParameter.Split(','))
                {
                    TypeReference bindTypeRef = null;
                    if (tr.GenericSupplier != null) // Generic Supplier
                    {
                        bindTypeRef = tr.GenericSupplier.Find(o => o is TypeParameter && (o as TypeParameter).ParameterName == s);
                        if (bindTypeRef == null)
                        {
                            bindTypeRef = tr.GenericSupplier[i++];
                        }
                    }
                    else if (p != null && p.SupplierDomain != null && !String.IsNullOrEmpty(EnumerationRenderer.WillRender(p.SupplierDomain)))
                    {
                        string vocabName     = Util.Util.MakeFriendly(EnumerationRenderer.WillRender(p.SupplierDomain));
                        string containerName = p.Container is Choice ? (p.Container as Choice).Container.Name : p.Container.Name;
                        if (vocabName.Equals(containerName))
                        {
                            vocabName = String.Format("{0}.vocabulary.{1}", ownerPackage, vocabName);
                        }
                        bindTypeRef = new TypeReference()
                        {
                            Name = String.Format("{0}", vocabName)
                        };
                    }
                    else
                    {
                        bindTypeRef = new TypeReference()
                        {
                            Name = dataType.DefaultBind
                        }
                    };

                    // Add Binding
                    bind.Add(s, ClassRenderer.CreateDatatypeRef(bindTypeRef ?? new TypeReference()
                    {
                        Name = null
                    }, null, ownerPackage));
                    fillParameter = fillParameter.Replace(s, bind[s]);
                }
            }

            // Create setter override and return
            List <SetterOverrideData> overrides = new List <SetterOverrideData>(dataType.SetterOverride.Count);

            foreach (var sod in dataType.SetterOverride)
            {
                // Correct parameters
                SetterOverrideData templatedSod = new SetterOverrideData();
                templatedSod.Parameters = new List <PropertyInfoData>();
                foreach (var parameterData in sod.Parameters)
                {
                    string dt = String.Empty;
                    if (!bind.TryGetValue(parameterData.DataType, out dt))
                    {
                        dt = parameterData.DataType;
                    }


                    templatedSod.Parameters.Add(new PropertyInfoData()
                    {
                        Name = parameterData.Name, DataType = dt.Replace(string.Format("<{0}>", dataType.TemplateParameter), String.Format("<{0}>", fillParameter))
                    });
                }

                // Correct Body
                templatedSod.Throws        = new List <ThrowsData>(sod.Throws);
                templatedSod.SetterText    = sod.SetterText.Replace(string.Format("<{0}>", dataType.TemplateParameter), String.Format("<{0}>", fillParameter));
                templatedSod.ValueInstance = sod.ValueInstance;
                overrides.Add(templatedSod);
            }

            return(overrides.ToArray());
        }