/// <summary>
        /// generate code for cascading deletions etc
        /// </summary>
        /// <param name="AStore"></param>
        /// <param name="AFilePath"></param>
        /// <param name="ANamespaceName"></param>
        /// <param name="AFileName"></param>
        /// <returns></returns>
        public static Boolean WriteTypedDataCascading(TDataDefinitionStore AStore, string AFilePath, string ANamespaceName, string AFileName)
        {
            Console.WriteLine("writing namespace " + ANamespaceName);

            string          templateDir = TAppSettingsManager.GetValue("TemplateDir", true);
            ProcessTemplate Template    = new ProcessTemplate(templateDir + Path.DirectorySeparatorChar +
                                                              "ORM" + Path.DirectorySeparatorChar +
                                                              "DataCascading.cs");

            Template.AddToCodelet("NAMESPACE", ANamespaceName);

            // load default header with license and copyright
            Template.SetCodelet("GPLFILEHEADER", ProcessTemplate.LoadEmptyFileComment(templateDir));

            foreach (TTable currentTable in AStore.GetTables())
            {
                ProcessTemplate snippet = Template.GetSnippet("TABLECASCADING");

                if (InsertMainProcedures(AStore, currentTable, Template, snippet))
                {
                    Template.AddToCodelet("USINGNAMESPACES",
                                          CodeGenerationAccess.GetNamespace(currentTable.strGroup), false);
                    Template.AddToCodelet("USINGNAMESPACES",
                                          CodeGenerationAccess.GetNamespace(currentTable.strGroup).Replace(
                                              ".Data;", ".Data.Access;").
                                          Replace("Ict.Petra.Shared.", "Ict.Petra.Server."), false);

                    Template.InsertSnippet("TABLECASCADINGLOOP", snippet);
                }
            }

            Template.FinishWriting(AFilePath + AFileName + "-generated.cs", ".cs", true);

            return(true);
        }
        /// <summary>
        /// create the code for validation of a typed table
        /// </summary>
        /// <param name="AStore"></param>
        /// <param name="strGroup"></param>
        /// <param name="AFilePath"></param>
        /// <param name="ANamespaceName"></param>
        /// <param name="AFileName"></param>
        /// <returns></returns>
        public static Boolean WriteValidation(TDataDefinitionStore AStore, string strGroup, string AFilePath, string ANamespaceName, string AFileName)
        {
            Console.WriteLine("processing validation of Typed Tables " + strGroup.Substring(0, 1).ToUpper() + strGroup.Substring(1));

            string          templateDir = TAppSettingsManager.GetValue("TemplateDir", true);
            ProcessTemplate Template    = new ProcessTemplate(templateDir + Path.DirectorySeparatorChar +
                                                              "ORM" + Path.DirectorySeparatorChar +
                                                              "DataTableValidation.cs");

            Template.AddToCodelet("NAMESPACE", ANamespaceName);
            Template.AddToCodelet("DATATABLENAMESPACE", ANamespaceName.Replace("Validation", "Data"));

            // load default header with license and copyright
            Template.SetCodelet("GPLFILEHEADER", ProcessTemplate.LoadEmptyFileComment(templateDir));

            foreach (TTable currentTable in AStore.GetTables())
            {
                if (currentTable.strGroup == strGroup)
                {
                    InsertTableValidation(Template, currentTable, null, "TABLELOOP");
                }
            }

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

            Template.FinishWriting(AFilePath + AFileName + "-generated.cs", ".cs", true);

            return(true);
        }
Beispiel #3
0
        private void CreateConnectors(TNamespace tn, String AOutputPath, String ATemplateDir)
        {
            String OutputFile = AOutputPath + Path.DirectorySeparatorChar + "M" + tn.Name +
                                Path.DirectorySeparatorChar + "Instantiator.Connectors-generated.cs";

            if (Directory.Exists(AOutputPath + Path.DirectorySeparatorChar + "M" + tn.Name +
                                 Path.DirectorySeparatorChar + "connect"))
            {
                OutputFile = AOutputPath + Path.DirectorySeparatorChar + "M" + tn.Name +
                             Path.DirectorySeparatorChar + "connect" +
                             Path.DirectorySeparatorChar + "Instantiator.Connectors-generated.cs";
            }

            Console.WriteLine("working on " + OutputFile);

            SortedList <string, TypeDeclaration> connectors = TCollectConnectorInterfaces.GetConnectors(tn.Name);

            ProcessTemplate Template = new ProcessTemplate(ATemplateDir + Path.DirectorySeparatorChar +
                                                           "ClientServerGlue" + Path.DirectorySeparatorChar +
                                                           "Connector.cs");

            // load default header with license and copyright
            Template.SetCodelet("GPLFILEHEADER", ProcessTemplate.LoadEmptyFileComment(ATemplateDir));

            Template.SetCodelet("TOPLEVELMODULE", tn.Name);

            Template.AddToCodelet("USINGNAMESPACES", "using Ict.Petra.Shared.Interfaces.M" + tn.Name + ";" + Environment.NewLine);

            UsingConnectorNamespaces = new List <string>();

            string InterfacePath = Path.GetFullPath(AOutputPath).Replace(Path.DirectorySeparatorChar, '/');

            InterfacePath = InterfacePath.Substring(0, InterfacePath.IndexOf("csharp/ICT/Petra")) + "csharp/ICT/Petra/Shared/lib/Interfaces";
            Template.AddToCodelet("USINGNAMESPACES", (CreateInterfaces.AddNamespacesFromYmlFile(InterfacePath, tn.Name)));

            Template.SetCodelet("CONNECTORCLASSES", string.Empty);

            foreach (TNamespace sn in tn.Children.Values)
            {
                WriteConnectorClass(
                    Template,
                    "Ict.Petra.Shared.M" + tn.Name + "." + sn.Name,
                    sn.Name,
                    sn.Name,
                    sn.Children,
                    connectors);
            }

            foreach (string n in UsingConnectorNamespaces)
            {
                Template.AddToCodelet("USINGNAMESPACES", "using " + n + ";" + Environment.NewLine);
            }

            Template.FinishWriting(OutputFile, ".cs", true);
        }
Beispiel #4
0
        /// <summary>
        /// create the code for a typed table
        /// </summary>
        /// <param name="AStore"></param>
        /// <param name="strGroup"></param>
        /// <param name="AFilePath"></param>
        /// <param name="ANamespaceName"></param>
        /// <param name="AFileName"></param>
        /// <returns></returns>
        public static Boolean WriteTypedTable(TDataDefinitionStore AStore, string strGroup, string AFilePath, string ANamespaceName, string AFileName)
        {
            Console.WriteLine("processing namespace Typed Tables " + strGroup.Substring(0, 1).ToUpper() + strGroup.Substring(1));

            string          templateDir = TAppSettingsManager.GetValue("TemplateDir", true);
            ProcessTemplate Template    = new ProcessTemplate(templateDir + Path.DirectorySeparatorChar +
                                                              "ORM" + Path.DirectorySeparatorChar +
                                                              "DataTable.cs");

            Template.AddToCodelet("NAMESPACE", ANamespaceName);

            // load default header with license and copyright
            Template.SetCodelet("GPLFILEHEADER", ProcessTemplate.LoadEmptyFileComment(templateDir));

            foreach (TTable currentTable in AStore.GetTables())
            {
                if (currentTable.strGroup == strGroup)
                {
                    if (!currentTable.HasPrimaryKey())
                    {
                        TLogging.Log("Warning: there is no primary key for table " + currentTable.strName);
                    }

                    InsertTableDefinition(Template, currentTable, null, "TABLELOOP");
                    InsertRowDefinition(Template, currentTable, null, "TABLELOOP");
                }
            }

            Template.FinishWriting(AFilePath + AFileName + "-generated.cs", ".cs", true);

            return(true);
        }
Beispiel #5
0
        private static ProcessTemplate GenerateUIConnector(ProcessTemplate ATemplate, TypeDeclaration connectorClass, string interfacename)
        {
            ProcessTemplate snippet = ATemplate.GetSnippet("UICONNECTORCLASS");

            snippet.SetCodelet("UICONNECTORINTERFACE", interfacename);
            snippet.SetCodelet("UICONNECTORCLASSNAME", connectorClass.Name);
            snippet.SetCodelet("CONSTRUCTORS", string.Empty);

            int constructorCounter = 0;

            foreach (ConstructorDeclaration m in CSParser.GetConstructors(connectorClass))
            {
                if (TCollectConnectorInterfaces.IgnoreMethod(m.Attributes, m.Modifier))
                {
                    continue;
                }

                constructorCounter++;

                ProcessTemplate snippetConstructor = ATemplate.GetSnippet("UICONNECTORCONSTRUCTOR");

                string ParameterDefinition = string.Empty;
                string ActualParameters    = string.Empty;

                AutoGenerationTools.FormatParameters(m.Parameters, out ActualParameters, out ParameterDefinition);

                snippetConstructor.SetCodelet("PARAMETERDEFINITION", ParameterDefinition);
                snippetConstructor.SetCodelet("UICONNECTORCLASSNAME", connectorClass.Name);
                snippetConstructor.SetCodelet("ACTUALPARAMETERS", ActualParameters);
                snippetConstructor.SetCodelet("ADDACTUALPARAMETERS", string.Empty);

                foreach (ParameterDeclarationExpression p in m.Parameters)
                {
                    if (((ParameterModifiers.Ref & p.ParamModifier) > 0) || ((ParameterModifiers.Out & p.ParamModifier) > 0))
                    {
                        throw new Exception("we do not support ref or out parameters in UIConnector constructor calls! " + connectorClass.Name);
                    }

                    snippetConstructor.AddToCodelet("ADDACTUALPARAMETERS",
                                                    "ActualParameters.Add(\"" + p.ParameterName + "\", " +
                                                    p.ParameterName + ");" + Environment.NewLine);
                }

                string methodname = m.Name;

                if (constructorCounter > 1)
                {
                    methodname += constructorCounter.ToString();
                }

                snippetConstructor.SetCodelet("METHODNAME", methodname);

                snippet.InsertSnippet("CONSTRUCTORS", snippetConstructor);
            }

            InsertMethodsAndProperties(snippet, connectorClass);

            return(snippet);
        }
Beispiel #6
0
        /// <summary>
        /// write an ordered list of tables, ordered by foreign key dependancies
        /// </summary>
        /// <param name="AStore"></param>
        /// <param name="AFilename"></param>
        public static void WriteTableList(TDataDefinitionStore AStore, string AFilename)
        {
            string          templateDir = TAppSettingsManager.GetValue("TemplateDir", true);
            ProcessTemplate Template    = new ProcessTemplate(templateDir + Path.DirectorySeparatorChar +
                                                              "ORM" + Path.DirectorySeparatorChar +
                                                              "TableList.cs");

            // load default header with license and copyright
            Template.SetCodelet("GPLFILEHEADER", ProcessTemplate.LoadEmptyFileComment(templateDir));

            List <TTable> tables = AStore.GetTables();

            tables = TTableSort.TopologicalSort(AStore, tables);

            string namesCodelet             = string.Empty;
            string namesCodeletCustomReport = string.Empty;

            foreach (TTable t in tables)
            {
                namesCodelet += "list.Add(\"" + t.strName + "\");" + Environment.NewLine;

                if (t.AvailableForCustomReport)
                {
                    namesCodeletCustomReport += "list.Add(\"" + t.strName + "\");" + Environment.NewLine;
                }
            }

            Template.AddToCodelet("DBTableNames", namesCodelet);
            Template.AddToCodelet("DBTableNamesAvailableForCustomReport", namesCodeletCustomReport);

            List <TSequence> Sequences = AStore.GetSequences();

            namesCodelet = string.Empty;

            foreach (TSequence s in Sequences)
            {
                namesCodelet += "list.Add(\"" + s.strName + "\");" + Environment.NewLine;
            }

            Template.AddToCodelet("DBSequenceNames", namesCodelet);

            Template.FinishWriting(AFilename, ".cs", true);
        }
Beispiel #7
0
        /// <summary>
        /// generate the connector code for the client
        /// </summary>
        static public void GenerateConnectorCode(String AOutputPath, String ATemplateDir)
        {
            String OutputFile = AOutputPath + Path.DirectorySeparatorChar + "ClientGlue.Connector-generated.cs";

            Console.WriteLine("working on " + OutputFile);

            ProcessTemplate Template = new ProcessTemplate(FTemplateDir + Path.DirectorySeparatorChar +
                                                           "ClientServerGlue" + Path.DirectorySeparatorChar +
                                                           "ClientGlue.Connector.cs");

            // load default header with license and copyright
            Template.SetCodelet("GPLFILEHEADER", ProcessTemplate.LoadEmptyFileComment(FTemplateDir));
            Template.SetCodelet("USINGNAMESPACES", string.Empty);

            if (FCompileForStandalone)
            {
                Template.AddToCodelet("USINGNAMESPACES", "using Ict.Common.DB;" + Environment.NewLine);
                Template.AddToCodelet("USINGNAMESPACES", "using Ict.Common.Remoting.Server;" + Environment.NewLine);
                Template.AddToCodelet("USINGNAMESPACES", "using Ict.Petra.Server.App.Core;" + Environment.NewLine);
                Template.AddToCodelet("USINGNAMESPACES", "using Ict.Petra.Server.App.Delegates;" + Environment.NewLine);
                Template.AddToCodelet("USINGNAMESPACES", "using Ict.Petra.Shared;" + Environment.NewLine);
                Template.AddToCodelet("USINGNAMESPACES", "using System.Security.Principal;" + Environment.NewLine);
                Template.InsertSnippet("CONNECTOR", Template.GetSnippet("CONNECTORSTANDALONE"));
                Template.InsertSnippet("STANDALONECLIENTMANAGER", Template.GetSnippet("STANDALONECLIENTMANAGER"));
            }
            else
            {
                Template.InsertSnippet("CONNECTOR", Template.GetSnippet("CONNECTORCLIENTSERVER"));
                Template.SetCodelet("STANDALONECLIENTMANAGER", string.Empty);
                Template.SetCodelet("HTTPREMOTING", "true");
            }

            Template.FinishWriting(OutputFile, ".cs", true);
        }
Beispiel #8
0
        private static void AddTableToDataset(
            string tabletype,
            string variablename,
            ProcessTemplate snippetDataset)
        {
            string typedTableDeklaration = "private " +
                                           tabletype +
                                           "Table Table" +
                                           variablename +
                                           ";" + Environment.NewLine;

            snippetDataset.AddToCodelet("TYPEDDATATABLES", typedTableDeklaration);

            ProcessTemplate tempSnippet;

            tempSnippet = snippetDataset.GetSnippet("TYPEDTABLEPROPERTY");
            tempSnippet.SetCodelet("TABLETYPENAME", tabletype);
            tempSnippet.SetCodelet("TABLEVARIABLENAME", variablename);
            snippetDataset.InsertSnippet("TYPEDTABLEPROPERTY", tempSnippet);

            snippetDataset.AddToCodelet("INITTABLESFRESH", "this.Tables.Add(new " +
                                        tabletype + "Table(\"" + variablename +
                                        "\"));" + Environment.NewLine);

            tempSnippet = snippetDataset.GetSnippet("INITTABLESNOTALL");
            tempSnippet.SetCodelet("TABLETYPENAME", tabletype);
            tempSnippet.SetCodelet("TABLEVARIABLENAME", variablename);
            snippetDataset.InsertSnippet("INITTABLESNOTALL", tempSnippet);

            tempSnippet = snippetDataset.GetSnippet("MAPTABLES");
            tempSnippet.SetCodelet("TABLEVARIABLENAME", variablename);
            snippetDataset.InsertSnippet("MAPTABLES", tempSnippet);

            tempSnippet = snippetDataset.GetSnippet("INITVARSTABLE");
            tempSnippet.SetCodelet("TABLETYPENAME", tabletype);
            tempSnippet.SetCodelet("TABLEVARIABLENAME", variablename);
            snippetDataset.InsertSnippet("INITVARSTABLE", tempSnippet);
        }
        /// <summary>
        /// write the interfaces for the Connectors
        /// parses the instantiator files
        /// Although the instantiators are generated from the interfaces, they might contain ManualCode regions with specific functions
        /// </summary>
        /// <param name="ATemplate"></param>
        /// <param name="AMethodsAlreadyWritten"></param>
        /// <param name="AInstantiatorClasses">all instantiator classes that implement the interface</param>
        /// <param name="AInterfaceName"></param>
        /// <param name="AInterfaceNamespace"></param>
        /// <param name="AServerNamespace">for the comment in the autogenerated code</param>
        /// <returns></returns>
        private bool WriteInstantiatorMethods(
            ProcessTemplate ATemplate,
            StringCollection AMethodsAlreadyWritten,
            List <TypeDeclaration> AInstantiatorClasses, String AInterfaceName, String AInterfaceNamespace, String AServerNamespace)
        {
            foreach (TypeDeclaration t in AInstantiatorClasses)
            {
                // there should only be one class, eg. TSubscriptionsCacheableNamespace
                foreach (MethodDeclaration m in CSParser.GetMethods(t))
                {
                    // copy all public methods that are not constructor, destructor, or InitializeLifetimeService
                    // and that are not created yet
                    if ((m.Name != "InitializeLifetimeService") &&
                        ((m.Modifier & Modifiers.Public) != 0) &&
                        !AMethodsAlreadyWritten.Contains(m.Name))
                    {
                        ATemplate.AddToCodelet("CONTENT",
                                               "/// <summary>auto generated from Instantiator (" + AServerNamespace + "." + t.Type + ")</summary>" + Environment.NewLine);
                        string MethodDeclaration = AutoGenerationTools.TypeToString(m.TypeReference, "") + " " + m.Name + "(";
                        int    align             = MethodDeclaration.Length;

                        bool firstParameter = true;

                        foreach (ParameterDeclarationExpression p in m.Parameters)
                        {
                            AutoGenerationTools.AddParameter(ref MethodDeclaration, ref firstParameter, align, p.ParameterName, p.ParamModifier,
                                                             AutoGenerationTools.TypeToString(p.TypeReference, ""));
                        }

                        MethodDeclaration += ");";
                        ATemplate.AddToCodelet("CONTENT", MethodDeclaration + Environment.NewLine);
                    }
                }
            }

            return(true);
        }
Beispiel #10
0
        /// <summary>
        /// use CSParser to parse the Server files
        /// </summary>
        /// <param name="tn"></param>
        /// <param name="AOutputPath"></param>
        private void WriteInterfaces(TNamespace tn, String AOutputPath)
        {
            String OutputFile = AOutputPath + Path.DirectorySeparatorChar + tn.Name + ".Interfaces-generated.cs";

            // open file
            Console.WriteLine("working on file " + OutputFile);

            ProcessTemplate Template = new ProcessTemplate(FTemplateDir + Path.DirectorySeparatorChar +
                                                           "ClientServerGlue" + Path.DirectorySeparatorChar +
                                                           "Interface.cs");

            // load default header with license and copyright
            Template.SetCodelet("GPLFILEHEADER", ProcessTemplate.LoadEmptyFileComment(FTemplateDir));

            Template.AddToCodelet("USINGNAMESPACES", AddNamespacesFromYmlFile(AOutputPath, tn.Name));

            // get all csharp files that might hold implementations of remotable classes
            List <CSParser> CSFiles = null;

            if (AOutputPath.Contains("ICT/Petra/Plugins"))
            {
                // search for webconnectors in the directory of the plugin
                CSFiles = CSParser.GetCSFilesForDirectory(Path.GetFullPath(AOutputPath + "/../Server"),
                                                          SearchOption.AllDirectories);
            }
            else if (Directory.Exists(CSParser.ICTPath + "/Petra/Server/lib/M" + tn.Name))
            {
                // any class in the module can contain a webconnector
                CSFiles = CSParser.GetCSFilesForDirectory(CSParser.ICTPath + "/Petra/Server/lib/M" + tn.Name,
                                                          SearchOption.AllDirectories);
            }
            else
            {
                CSFiles = new List <CSParser>();
            }

            SortedList InterfaceNames = GetInterfaceNamesFromImplementation(CSFiles);

            Template.SetCodelet("INTERFACES", string.Empty);
            WriteNamespaces(Template, tn, InterfaceNames, CSFiles);

            if (Template.FCodelets["INTERFACES"].Length == 0)
            {
                Template.InsertSnippet("INTERFACES", Template.GetSnippet("DUMMYINTERFACE"));
            }

            Template.FinishWriting(OutputFile, ".cs", true);
        }
Beispiel #11
0
        /// <summary>write the code for the designer file where the properties of the control are written</summary>
        public override ProcessTemplate SetControlProperties(TFormWriter writer, TControlDef ACtrl)
        {
            ProcessTemplate ctrlSnippet = base.SetControlProperties(writer, ACtrl);

            ctrlSnippet.SetCodelet("PAGENUMBER", PageCounter.ToString());

            if (writer.FTemplate.FCodelets.Keys.Contains("CUSTOMFUNCTIONS"))
            {
                ctrlSnippet.SetCodelet("CUSTOMFUNCTIONS", writer.FTemplate.FCodelets["CUSTOMFUNCTIONS"].ToString());
                writer.FTemplate.FCodelets.Remove("CUSTOMFUNCTIONS");
            }
            else
            {
                ctrlSnippet.SetCodelet("CUSTOMFUNCTIONS", String.Empty);
            }

            if (writer.FTemplate.FCodelets.Keys.Contains("ONSHOW"))
            {
                ctrlSnippet.SetCodelet("ONSHOW", writer.FTemplate.FCodelets["ONSHOW"].ToString());
                writer.FTemplate.FCodelets.Remove("ONSHOW");
            }

            if (writer.FTemplate.FCodelets.Keys.Contains("ISVALID"))
            {
                ctrlSnippet.SetCodelet("ISVALID", writer.FTemplate.FCodelets["ISVALID"].ToString());
                writer.FTemplate.FCodelets.Remove("ISVALID");
            }

            if (writer.FTemplate.FCodelets.Keys.Contains("ONHIDE"))
            {
                ctrlSnippet.SetCodelet("ONHIDE", writer.FTemplate.FCodelets["ONHIDE"].ToString());
                writer.FTemplate.FCodelets.Remove("ONHIDE");
            }

            if (ACtrl.HasAttribute("Height"))
            {
                ctrlSnippet.AddToCodelet("ONSHOW", String.Format("MainForm.setHeight({0});", ACtrl.GetAttribute("Height")));
            }

            if (ACtrl.HasAttribute("LabelWidth"))
            {
                ctrlSnippet.SetCodelet("LABELWIDTH", ACtrl.GetAttribute("LabelWidth"));
            }

            PageCounter++;

            return(ctrlSnippet);
        }
        /// <summary>
        /// generate code for reading and writing typed data tables from and to the database
        /// </summary>
        /// <param name="AStore"></param>
        /// <param name="strGroup"></param>
        /// <param name="AFilePath"></param>
        /// <param name="ANamespaceName"></param>
        /// <param name="AFilename"></param>
        /// <returns></returns>
        public static Boolean WriteTypedDataAccess(TDataDefinitionStore AStore,
                                                   string strGroup,
                                                   string AFilePath,
                                                   string ANamespaceName,
                                                   string AFilename)
        {
            Console.WriteLine("processing namespace PetraTypedDataAccess." + strGroup.Substring(0, 1).ToUpper() + strGroup.Substring(1));

            string          templateDir = TAppSettingsManager.GetValue("TemplateDir", true);
            ProcessTemplate Template    = new ProcessTemplate(templateDir + Path.DirectorySeparatorChar +
                                                              "ORM" + Path.DirectorySeparatorChar +
                                                              "DataAccess.cs");

            Template.SetCodelet("NAMESPACE", ANamespaceName);

            // load default header with license and copyright
            Template.SetCodelet("GPLFILEHEADER", ProcessTemplate.LoadEmptyFileComment(templateDir));

            Template.AddToCodelet("USINGNAMESPACES", GetNamespace(strGroup), false);

            bool hasTables = false;

            foreach (TTable currentTable in AStore.GetTables())
            {
                if (currentTable.strGroup == strGroup)
                {
                    DirectReferences = new ArrayList();

                    ProcessTemplate snippet = Template.GetSnippet("TABLEACCESS");

                    InsertMainProcedures(AStore, currentTable, Template, snippet);
                    InsertViaOtherTable(AStore, currentTable, Template, snippet);
                    InsertViaLinkTable(AStore, currentTable, Template, snippet);

                    Template.InsertSnippet("TABLEACCESSLOOP", snippet);

                    hasTables = true;
                }
            }

            if (hasTables)
            {
                Template.FinishWriting(AFilePath + AFilename + "-generated.cs", ".cs", true);
            }

            return(true);
        }
        /// <summary>write the code for the designer file where the properties of the control are written</summary>
        public override ProcessTemplate SetControlProperties(TFormWriter writer, TControlDef ctrl)
        {
            ProcessTemplate snippetRowDefinition = writer.FTemplate.GetSnippet(FControlDefinitionSnippetName);

            ((TExtJsFormsWriter)writer).AddResourceString(snippetRowDefinition, "LABEL", ctrl, ctrl.Label);

            StringCollection Controls = FindContainedControls(writer, ctrl.xmlNode);

            snippetRowDefinition.AddToCodelet("ITEMS", "");

            if (Controls.Count > 0)
            {
                // used for radiogroupbox
                foreach (string ChildControlName in Controls)
                {
                    TControlDef       childCtrl   = FCodeStorage.FindOrCreateControl(ChildControlName, ctrl.controlName);
                    IControlGenerator ctrlGen     = writer.FindControlGenerator(childCtrl);
                    ProcessTemplate   ctrlSnippet = ctrlGen.SetControlProperties(writer, childCtrl);

                    ctrlSnippet.SetCodelet("COLUMNWIDTH", "");

                    ctrlSnippet.SetCodelet("ITEMNAME", ctrl.controlName);
                    ctrlSnippet.SetCodelet("ITEMID", childCtrl.controlName);

                    if (ctrl.GetAttribute("hideLabel") == "true")
                    {
                        ctrlSnippet.SetCodelet("HIDELABEL", "true");
                    }
                    else if (ChildControlName == Controls[0])
                    {
                        ((TExtJsFormsWriter)writer).AddResourceString(ctrlSnippet, "LABEL", ctrl, ctrl.Label);
                    }

                    snippetRowDefinition.InsertSnippet("ITEMS", ctrlSnippet, ",");
                }
            }
            else
            {
                // used for GroupBox, and Composite
                TExtJsFormsWriter.InsertControl(ctrl, snippetRowDefinition, "ITEMS", "HiddenValues", writer);
                TExtJsFormsWriter.InsertControl(ctrl, snippetRowDefinition, "ITEMS", "Controls", writer);
            }

            return(snippetRowDefinition);
        }
Beispiel #14
0
        /// <summary>
        /// add a string that is translatable
        /// </summary>
        /// <param name="ACtrlSnippet"></param>
        /// <param name="APlaceHolder"></param>
        /// <param name="ACtrl"></param>
        /// <param name="AText"></param>
        public void AddResourceString(ProcessTemplate ACtrlSnippet, string APlaceHolder, TControlDef ACtrl, string AText)
        {
            string strName;

            if (ACtrl == null)
            {
                strName = APlaceHolder;
            }
            else
            {
                strName = ACtrl.controlName + APlaceHolder;
            }

            ACtrlSnippet.SetCodelet(APlaceHolder, strName);
            FTemplate.AddToCodelet("RESOURCESTRINGS", strName + ":'" + AText + "'," + Environment.NewLine);

            // write to app-lang-en.js file
            FLanguageFileTemplate.AddToCodelet("RESOURCESTRINGS", strName + ":'" + AText + "'," + Environment.NewLine);
        }
Beispiel #15
0
        /// based on the code model, create the code;
        /// using the code generators that have been loaded
        public override void CreateCode(TCodeStorage ACodeStorage, string ATemplateFile)
        {
            FCodeStorage = ACodeStorage;
            TControlGenerator.FCodeStorage = ACodeStorage;
            FTemplate = new ProcessTemplate(ATemplateFile);
            FFormName = Path.GetFileNameWithoutExtension(YamlFilename).Replace("-", "_");

            // drop language specific part of the name
            if (FFormName.Contains("."))
            {
                FFormName = FFormName.Substring(0, FFormName.IndexOf("."));
            }

            FFormName  = FFormName.ToUpper()[0] + FFormName.Substring(1);
            FFormName += "Form";

            // load default header with license and copyright
            string templateDir = TAppSettingsManager.GetValue("TemplateDir", true);

            FTemplate.AddToCodelet("GPLFILEHEADER",
                                   ProcessTemplate.LoadEmptyFileComment(templateDir + Path.DirectorySeparatorChar + ".." +
                                                                        Path.DirectorySeparatorChar));

            FTemplate.SetCodelet("UPLOADFORM", "");
            FTemplate.SetCodelet("CHECKFORVALIDUPLOAD", "");

            FLanguageFileTemplate = FTemplate.GetSnippet("LANGUAGEFILE");

            // find the first control that is a panel or groupbox or tab control
            if (FCodeStorage.HasRootControl("content"))
            {
                AddRootControl("content");
            }

            InsertCodeIntoTemplate(YamlFilename);

            string languagefilepath = Path.GetDirectoryName(YamlFilename) + Path.DirectorySeparatorChar +
                                      Path.GetFileNameWithoutExtension(YamlFilename) + "-lang-template.js";

            File.WriteAllText(languagefilepath, FLanguageFileTemplate.FinishWriting(true));
        }
Beispiel #16
0
        static private void CreateServerGlue(TNamespace tn, SortedList <string, TypeDeclaration> connectors, string AOutputPath)
        {
            String OutputFile = AOutputPath + Path.DirectorySeparatorChar + "ServerGlue.M" + tn.Name +
                                "-generated.cs";

            Console.WriteLine("working on " + OutputFile);

            ProcessTemplate Template = new ProcessTemplate(FTemplateDir + Path.DirectorySeparatorChar +
                                                           "ClientServerGlue" + Path.DirectorySeparatorChar +
                                                           "ServerGlue.cs");

            // load default header with license and copyright
            Template.SetCodelet("GPLFILEHEADER", ProcessTemplate.LoadEmptyFileComment(FTemplateDir));

            Template.SetCodelet("TOPLEVELMODULE", tn.Name);
            Template.SetCodelet("WEBCONNECTORS", string.Empty);
            Template.SetCodelet("UICONNECTORS", string.Empty);

            string InterfacePath = Path.GetFullPath(AOutputPath).Replace(Path.DirectorySeparatorChar, '/');

            InterfacePath = InterfacePath.Substring(0, InterfacePath.IndexOf("csharp/ICT/Petra")) + "csharp/ICT/Petra/Shared/lib/Interfaces";
            Template.AddToCodelet("USINGNAMESPACES", CreateInterfaces.AddNamespacesFromYmlFile(InterfacePath, tn.Name));

            if (AOutputPath.Contains("ICT/Petra/Plugins/"))
            {
                Template.AddToCodelet("USINGNAMESPACES", "using Ict.Petra.Server.App.WebService;" + Environment.NewLine);

                // add namespaces that are required by the plugin
                InterfacePath = Path.GetFullPath(AOutputPath + "/../").Replace(Path.DirectorySeparatorChar, '/');
                Template.AddToCodelet("USINGNAMESPACES", CreateInterfaces.AddNamespacesFromYmlFile(InterfacePath, "Plugin"));
            }

            FUsingNamespaces = new SortedList <string, string>();
            FContainsAsynchronousExecutionProgress = false;

            foreach (string connector in connectors.Keys)
            {
                if (connector.EndsWith("UIConnector"))
                {
                    WriteUIConnector(connector, connectors[connector], Template);
                }
                else
                {
                    WriteWebConnector(connector, connectors[connector], Template);
                }
            }

            if (FContainsAsynchronousExecutionProgress)
            {
                Template.InsertSnippet("UICONNECTORS", Template.GetSnippet("ASYNCEXECPROCESSCONNECTOR"));

                if (!FUsingNamespaces.ContainsKey("Ict.Petra.Server.MCommon"))
                {
                    FUsingNamespaces.Add("Ict.Petra.Server.MCommon", "Ict.Petra.Server.MCommon");
                }
            }

            foreach (string usingNamespace in FUsingNamespaces.Keys)
            {
                Template.AddToCodelet("USINGNAMESPACES", "using " + usingNamespace + ";" + Environment.NewLine);
            }

            if (OutputFile.Replace("\\", "/").Contains("ICT/Petra/Plugins"))
            {
                string pluginWithNamespace = TAppSettingsManager.GetValue("plugin");
                Template.SetCodelet("WEBSERVICENAMESPACE", pluginWithNamespace + ".WebService");
            }
            else
            {
                Template.SetCodelet("WEBSERVICENAMESPACE", "Ict.Petra.Server.App.WebService");
            }

            Template.FinishWriting(OutputFile, ".cs", true);
        }
Beispiel #17
0
        private static void PrepareParametersForMethod(
            ProcessTemplate snippet,
            TypeReference AReturnType,
            List <ParameterDeclarationExpression> AParameters,
            string AMethodName,
            ref List <string> AMethodNames)
        {
            string ParameterDefinition = string.Empty;
            string ActualParameters    = string.Empty;

            snippet.SetCodelet("LOCALVARIABLES", string.Empty);
            string returnCodeJSClient = string.Empty;
            int    returnCounter      = 0;

            foreach (ParameterDeclarationExpression p in AParameters)
            {
                string parametertype  = p.TypeReference.ToString();
                bool   ArrayParameter = false;

                // check if the parametertype is not a generic type, eg. dictionary or list
                if (!parametertype.Contains("<"))
                {
                    if (parametertype.EndsWith("[]"))
                    {
                        ArrayParameter = true;
//Console.WriteLine("ArrayParameter found: " + parametertype);
                    }

                    parametertype = parametertype == "string" || parametertype == "String" ? "System.String" : parametertype;
                    parametertype = parametertype == "bool" || parametertype == "Boolean" ? "System.Boolean" : parametertype;

                    if (parametertype.Contains("UINT") || parametertype.Contains("unsigned"))
                    {
                        parametertype = parametertype.Contains("UInt32") || parametertype == "unsigned int" ? "System.UInt32" : parametertype;
                        parametertype = parametertype.Contains("UInt16") || parametertype == "unsigned short" ? "System.UInt16" : parametertype;
                        parametertype = parametertype.Contains("UInt64") || parametertype == "unsigned long" ? "System.UInt64" : parametertype;
                    }
                    else
                    {
                        parametertype = parametertype.Contains("Int32") || parametertype == "int" ? "System.Int32" : parametertype;
                        parametertype = parametertype.Contains("Int16") || parametertype == "short" ? "System.Int16" : parametertype;
                        parametertype = parametertype.Contains("Int64") || parametertype == "long" ? "System.Int64" : parametertype;
                    }

                    parametertype = parametertype.Contains("Decimal") || parametertype == "decimal" ? "System.Decimal" : parametertype;

                    if (ArrayParameter &&
                        !(parametertype.EndsWith("[]")))
                    {
                        // need to restore Array type!
                        parametertype += "[]";

//Console.WriteLine("ArrayParameter found - new parametertype = " + parametertype);
                    }
                }

                bool TypedDataSetParameter     = parametertype.EndsWith("TDS");
                bool DataTableParameter        = parametertype.EndsWith("DataTable");
                bool EnumParameter             = parametertype.EndsWith("Enum");
                bool DecimalParameter          = parametertype.StartsWith("System.Decimal") && !ArrayParameter;
                bool DateTimeParameter         = parametertype.EndsWith("DateTime");
                bool ListParameter             = parametertype.StartsWith("List<");
                bool NullableDateTimeParameter = parametertype.Contains("Nullable<DateTime>");
                bool BinaryParameter           =
                    p.ParameterName.EndsWith("Base64") ||
                    !((parametertype.StartsWith("System.Int64")) || (parametertype.StartsWith("System.Int32")) ||
                      (parametertype.StartsWith("System.Int16")) ||
                      (parametertype.StartsWith("System.String")) || (parametertype.StartsWith("System.Boolean")) ||
                      DecimalParameter ||
                      DateTimeParameter ||
                      NullableDateTimeParameter ||
                      EnumParameter ||
                      ListParameter);

                if (ActualParameters.Length > 0)
                {
                    ActualParameters += ", ";
                }

                // ignore out parameters in the web service method definition
                if ((ParameterModifiers.Out & p.ParamModifier) == 0)
                {
                    if (ParameterDefinition.Length > 0)
                    {
                        ParameterDefinition += ", ";
                    }

                    if ((!BinaryParameter) && (!ArrayParameter) && (!EnumParameter) && (!DateTimeParameter) && (!NullableDateTimeParameter) && (!DecimalParameter))
                    {
                        ParameterDefinition += parametertype + " " + p.ParameterName;
                    }
                    else
                    {
                        ParameterDefinition += "string " + p.ParameterName;
                    }
                }

                // for string parameters, check if they have been encoded binary due to special characters in the string;
                // this obviously does not apply to out parameters
                if ((parametertype == "System.String") && ((ParameterModifiers.Out & p.ParamModifier) == 0))
                {
                    snippet.AddToCodelet(
                        "LOCALVARIABLES",
                        p.ParameterName + " = (string) THttpBinarySerializer.DeserializeObject(" + p.ParameterName + ",\"System.String\");" +
                        Environment.NewLine);
                }
                else if (ListParameter && parametertype.Contains("System.String") && ((ParameterModifiers.Out & p.ParamModifier) == 0))
                {
                    if (!parametertype.Contains("[]"))
                    {
                        snippet.AddToCodelet(
                            "LOCALVARIABLES",
                            p.ParameterName + " = THttpBinarySerializer.DeserializeObject(" + p.ParameterName + ");" +
                            Environment.NewLine);
                    }
                }

                // EnumParameters are also binary encoded
                // this obviously does not apply to out parameters
                if (EnumParameter && ((ParameterModifiers.Out & p.ParamModifier) == 0))
                {
                    snippet.AddToCodelet(
                        "LOCALVARIABLES",
                        p.ParameterName + " = THttpBinarySerializer.DeserializeObject(" + p.ParameterName + ",\"System.String\").ToString();" +
                        Environment.NewLine);
                }

                if (DateTimeParameter && ((ParameterModifiers.Out & p.ParamModifier) == 0))
                {
                    snippet.AddToCodelet(
                        "LOCALVARIABLES",
                        parametertype + " Local" + p.ParameterName + " = DateTime.Parse(" + p.ParameterName + ", null, System.Globalization.DateTimeStyles.RoundtripKind);" +
                        Environment.NewLine);
                }

                if (NullableDateTimeParameter && ((ParameterModifiers.Out & p.ParamModifier) == 0))
                {
                    snippet.AddToCodelet(
                        "LOCALVARIABLES",
                        parametertype + " Local" + p.ParameterName + " = (" + p.ParameterName + " == \"null\" || " + p.ParameterName + " == null)?(DateTime?)null:DateTime.Parse(" + p.ParameterName + ", null, System.Globalization.DateTimeStyles.RoundtripKind);" +
                        Environment.NewLine);
                }

                if (DecimalParameter && ((ParameterModifiers.Out & p.ParamModifier) == 0))
                {
                    snippet.AddToCodelet(
                        "LOCALVARIABLES",
                        parametertype + " Local" + p.ParameterName + " = Decimal.Parse(" + p.ParameterName + ", System.Globalization.CultureInfo.InvariantCulture);" +
                        Environment.NewLine);
                }

                if (TypedDataSetParameter && (ParameterModifiers.Out & p.ParamModifier) == 0)
                {
                    snippet.AddToCodelet(
                        "LOCALVARIABLES",
                        parametertype + " Local" + p.ParameterName + " = new " + parametertype + "();" + Environment.NewLine +
                        "Local" + p.ParameterName + " = (" + parametertype + ") THttpBinarySerializer.DeserializeDataSet(" + p.ParameterName + ", Local" + p.ParameterName + ");" +
                        Environment.NewLine);
                }

                if ((ParameterModifiers.Out & p.ParamModifier) != 0)
                {
                    snippet.AddToCodelet("LOCALVARIABLES", parametertype + " " + p.ParameterName + ";" + Environment.NewLine);
                    ActualParameters += "out " + p.ParameterName;
                }
                else if ((ParameterModifiers.Ref & p.ParamModifier) != 0)
                {
                    if (TypedDataSetParameter || DateTimeParameter || NullableDateTimeParameter || DecimalParameter)
                    {
                        ActualParameters += "ref Local" + p.ParameterName;
                    }
                    else if (BinaryParameter)
                    {
                        snippet.AddToCodelet("LOCALVARIABLES", parametertype + " Local" + p.ParameterName + " = " +
                                             " (" + parametertype + ")THttpBinarySerializer.DeserializeObject(" + p.ParameterName + ",\"binary\");" +
                                             Environment.NewLine);
                        ActualParameters += "ref Local" + p.ParameterName;
                    }
                    else if (EnumParameter)
                    {
                        snippet.AddToCodelet("LOCALVARIABLES", parametertype + " Local" + p.ParameterName + " = " +
                                             " (" + parametertype + ") Enum.Parse(typeof(" + parametertype + "), " + p.ParameterName + ");" +
                                             Environment.NewLine);
                        ActualParameters += "ref Local" + p.ParameterName;
                    }
                    else
                    {
                        ActualParameters += "ref " + p.ParameterName;
                    }
                }
                else
                {
                    if (TypedDataSetParameter || DateTimeParameter || NullableDateTimeParameter || DecimalParameter)
                    {
                        ActualParameters += "Local" + p.ParameterName;
                    }
                    else if (DataTableParameter)
                    {
                        ActualParameters += "(" + parametertype + ")THttpBinarySerializer.DeserializeObject(" + p.ParameterName + ",\"System.Data.DataTable\")";
                    }
                    else if (BinaryParameter ||
                             ArrayParameter)
                    {
                        ActualParameters += "(" + parametertype + ")THttpBinarySerializer.DeserializeObject(" + p.ParameterName + ",\"binary\")";
                    }
                    else if (EnumParameter)
                    {
                        ActualParameters += " (" + parametertype + ") Enum.Parse(typeof(" + parametertype + "), " + p.ParameterName + ")";
                    }
                    else
                    {
                        ActualParameters += p.ParameterName;
                    }
                }

                if (((ParameterModifiers.Ref & p.ParamModifier) > 0) || ((ParameterModifiers.Out & p.ParamModifier) > 0))
                {
                    if (returnCounter == 0)
                    {
                        returnCodeJSClient = "\"{\" + ";
                    }
                    else
                    {
                        returnCodeJSClient += " + \",\" + ";
                    }

                    returnCodeJSClient += "\"\\\"" + p.ParameterName + "\\\": \" + ";
                    returnCodeJSClient +=
                        "THttpBinarySerializer.SerializeObject(" +
                        (((ParameterModifiers.Ref & p.ParamModifier) > 0 && BinaryParameter) ? "Local" : string.Empty) +
                        p.ParameterName + ")";

                    returnCounter++;
                }
            }

            if (AReturnType != null)
            {
                string returntype = AutoGenerationTools.TypeToString(AReturnType, "");

                if (!returntype.Contains("<"))
                {
                    returntype = returntype == "string" || returntype == "String" ? "System.String" : returntype;
                    returntype = returntype == "bool" || returntype == "Boolean" ? "System.Boolean" : returntype;

                    if (returntype.Contains("UINT") || returntype.Contains("unsigned"))
                    {
                        returntype = returntype.Contains("UInt32") || returntype == "unsigned int" ? "System.UInt32" : returntype;
                        returntype = returntype.Contains("UInt16") || returntype == "unsigned short" ? "System.UInt16" : returntype;
                        returntype = returntype.Contains("UInt64") || returntype == "unsigned long" ? "System.UInt64" : returntype;
                    }
                    else
                    {
                        returntype = returntype.Contains("Int32") || returntype == "int" ? "System.Int32" : returntype;
                        returntype = returntype.Contains("Int16") || returntype == "short" ? "System.Int16" : returntype;
                        returntype = returntype.Contains("Int64") || returntype == "long" ? "System.Int64" : returntype;
                    }

                    returntype = returntype.Contains("Decimal") || returntype == "decimal" ? "System.Decimal" : returntype;
                }

                if (returnCounter > 0)
                {
                    if (returntype != "void")
                    {
                        returnCodeJSClient += "+ \",\" + \"\\\"result\\\": \"+" +
                                              "THttpBinarySerializer.SerializeObject(Result)";

                        returnCounter++;
                    }

                    returntype = "string";
                }
                else if (returntype == "System.String")
                {
                    returntype         = "string";
                    returnCodeJSClient = "Result";
                }
                else if (!((returntype == "System.Int64") || (returntype == "System.Int32") || (returntype == "System.Int16") ||
                           (returntype == "System.UInt64") || (returntype == "System.UInt32") || (returntype == "System.UInt16") ||
                           (returntype == "System.Decimal") ||
                           (returntype == "System.Boolean")) && (returntype != "void"))
                {
                    returntype         = "string";
                    returnCodeJSClient = "\"{\\\"result\\\": \"+" +
                                         "THttpBinarySerializer.SerializeObject(Result)" + " + \"}\"";
                }

                string localreturn = AutoGenerationTools.TypeToString(AReturnType, "");

                if (localreturn == "void")
                {
                    localreturn = string.Empty;
                }
                else if (returnCodeJSClient.Length > 0)
                {
                    localreturn += " Result = ";
                }
                else
                {
                    localreturn = "return ";
                }

                if (returnCounter > 1)
                {
                    returnCodeJSClient += "+ \"}\"";
                }

                snippet.SetCodelet("RETURN", string.Empty);

                if (returnCodeJSClient.Length > 0)
                {
                    snippet.SetCodelet("RETURN",
                                       returntype != "void" ? "return " + returnCodeJSClient + ";" : string.Empty);
                }

                snippet.SetCodelet("RETURNTYPE", returntype);
                snippet.SetCodelet("LOCALRETURN", localreturn);
            }

//Console.WriteLine("Final ParameterDefinition = " + ParameterDefinition);
            snippet.SetCodelet("PARAMETERDEFINITION", ParameterDefinition);
            snippet.SetCodelet("ACTUALPARAMETERS", ActualParameters);

            // avoid duplicate names for webservice methods
            string methodname    = AMethodName;
            int    methodcounter = 1;

            while (AMethodNames.Contains(methodname))
            {
                methodcounter++;
                methodname = AMethodName + methodcounter.ToString();
            }

            AMethodNames.Add(methodname);

            snippet.SetCodelet("UNIQUEMETHODNAME", methodname);
        }
        /// <summary>
        /// code for cascading functions
        /// </summary>
        /// <param name="AStore"></param>
        /// <param name="ACurrentTable"></param>
        /// <param name="ATemplate"></param>
        /// <param name="ASnippet"></param>
        /// <returns>false if no cascading available</returns>
        private static bool InsertMainProcedures(TDataDefinitionStore AStore,
                                                 TTable ACurrentTable,
                                                 ProcessTemplate ATemplate,
                                                 ProcessTemplate ASnippet)
        {
            string csvListPrimaryKeyFields;
            string formalParametersPrimaryKey;
            string actualParametersPrimaryKey;

            Tuple <string, string, string>[] formalParametersPrimaryKeySeparate;
            string actualParametersPrimaryKeyFromPKArray = String.Empty;

            ASnippet.AddToCodelet("TABLENAME", TTable.NiceTableName(ACurrentTable.strName));
            ASnippet.AddToCodelet("THISTABLELABEL", ACurrentTable.strLabel);

            PrepareCodeletsPrimaryKey(ACurrentTable,
                                      out csvListPrimaryKeyFields,
                                      out formalParametersPrimaryKey,
                                      out actualParametersPrimaryKey,
                                      out formalParametersPrimaryKeySeparate);

            for (int Counter = 0; Counter < formalParametersPrimaryKeySeparate.Length; Counter++)
            {
                actualParametersPrimaryKeyFromPKArray +=
                    "(" + formalParametersPrimaryKeySeparate[Counter].Item1 + ")" +
                    "APrimaryKeyValues[" + Counter.ToString() + "], ";
            }

            // Strip off trailing ", "
            actualParametersPrimaryKeyFromPKArray = actualParametersPrimaryKeyFromPKArray.Substring(0,
                                                                                                    actualParametersPrimaryKeyFromPKArray.Length - 2);

            ASnippet.AddToCodelet("CSVLISTPRIMARYKEYFIELDS", csvListPrimaryKeyFields);
            ASnippet.AddToCodelet("FORMALPARAMETERSPRIMARYKEY", formalParametersPrimaryKey);
            ASnippet.AddToCodelet("ACTUALPARAMETERSPRIMARYKEY", actualParametersPrimaryKey);
            ASnippet.AddToCodelet("ACTUALPARAMETERSPRIMARYKEYFROMPKARRAY", actualParametersPrimaryKeyFromPKArray);

            for (int Counter = 0; Counter < ACurrentTable.GetPrimaryKey().strThisFields.Count; Counter++)
            {
                ProcessTemplate PKInfoDictBuilding = ASnippet.GetSnippet("PRIMARYKEYINFODICTBUILDING");
                PKInfoDictBuilding.SetCodelet("PKCOLUMNLABEL", formalParametersPrimaryKeySeparate[Counter].Item3);
                PKInfoDictBuilding.SetCodelet("PKCOLUMNCONTENT", formalParametersPrimaryKeySeparate[Counter].Item2);
                ASnippet.InsertSnippet("PRIMARYKEYINFODICTBUILDING", PKInfoDictBuilding);
            }

            ASnippet.AddToCodelet("PRIMARYKEYCOLUMNCOUNT", ACurrentTable.GetPrimaryKey().strThisFields.Count.ToString());

            foreach (TConstraint constraint in ACurrentTable.FReferenced)
            {
                if (AStore.GetTable(constraint.strThisTable).HasPrimaryKey())
                {
                    string csvListOtherPrimaryKeyFields;
                    string notUsed;
                    Tuple <string, string, string>[] formalParametersPrimaryKeySeparate2;

                    TTable OtherTable = AStore.GetTable(constraint.strThisTable);

                    PrepareCodeletsPrimaryKey(OtherTable,
                                              out csvListOtherPrimaryKeyFields,
                                              out notUsed,
                                              out notUsed,
                                              out formalParametersPrimaryKeySeparate2);

                    // check if other foreign key exists that references the same table, e.g.
                    // PBankAccess.LoadViaPPartnerPartnerKey
                    // PBankAccess.LoadViaPPartnerContactPartnerKey
                    string DifferentField = CodeGenerationAccess.FindOtherConstraintSameOtherTable(
                        OtherTable.grpConstraint,
                        constraint);
                    string LoadViaProcedureName = TTable.NiceTableName(ACurrentTable.strName);
                    string MyOtherTableName     = "My" + TTable.NiceTableName(constraint.strThisTable);

                    if (DifferentField.Length != 0)
                    {
                        LoadViaProcedureName += TTable.NiceFieldName(DifferentField);
                        MyOtherTableName     += TTable.NiceFieldName(DifferentField);
                    }

                    // for the moment, don't implement it for too big tables, e.g. s_user)
                    if ((ACurrentTable.HasPrimaryKey() || (ACurrentTable.FReferenced.Count <= CASCADING_DELETE_MAX_REFERENCES)) &&
                        ((constraint.strThisTable != "a_ledger") &&
                         (!LoadViaProcedureName.StartsWith("SUser"))))
                    {
                        ProcessTemplate snippetDelete = ASnippet.GetSnippet("DELETEBYPRIMARYKEYCASCADING");
                        snippetDelete.SetCodelet("OTHERTABLENAME", TTable.NiceTableName(constraint.strThisTable));
                        snippetDelete.SetCodelet("MYOTHERTABLENAME", MyOtherTableName);
                        snippetDelete.SetCodelet("VIAPROCEDURENAME", "Via" + LoadViaProcedureName);
                        snippetDelete.SetCodelet("CSVLISTOTHERPRIMARYKEYFIELDS", csvListOtherPrimaryKeyFields);
                        snippetDelete.SetCodelet("OTHERTABLEALSOCASCADING", "true");


                        ASnippet.InsertSnippet("DELETEBYPRIMARYKEYCASCADING", snippetDelete);

                        snippetDelete = ASnippet.GetSnippet("DELETEBYTEMPLATECASCADING");
                        snippetDelete.SetCodelet("OTHERTABLENAME", TTable.NiceTableName(constraint.strThisTable));
                        snippetDelete.SetCodelet("MYOTHERTABLENAME", MyOtherTableName);
                        snippetDelete.SetCodelet("VIAPROCEDURENAME", "Via" + LoadViaProcedureName);
                        snippetDelete.SetCodelet("CSVLISTOTHERPRIMARYKEYFIELDS", csvListOtherPrimaryKeyFields);
                        snippetDelete.SetCodelet("OTHERTABLEALSOCASCADING", "true");


                        ASnippet.InsertSnippet("DELETEBYTEMPLATECASCADING", snippetDelete);
                    }

                    if ((constraint.strThisTable != "a_ledger") &&
                        (!LoadViaProcedureName.StartsWith("SUser")))
                    {
                        ProcessTemplate snippetCount = ASnippet.GetSnippet("COUNTBYPRIMARYKEYCASCADING");
                        snippetCount.SetCodelet("OTHERTABLENAME", TTable.NiceTableName(constraint.strThisTable));
                        snippetCount.SetCodelet("MYOTHERTABLENAME", MyOtherTableName);
                        snippetCount.SetCodelet("VIAPROCEDURENAME", "Via" + LoadViaProcedureName);
                        snippetCount.SetCodelet("CSVLISTOTHERPRIMARYKEYFIELDS", csvListOtherPrimaryKeyFields);
                        snippetCount.SetCodelet("OTHERTABLEALSOCASCADING", "true");

                        for (int Counter = 0; Counter < OtherTable.GetPrimaryKey().strThisFields.Count; Counter++)
                        {
                            ProcessTemplate PKInfoDictBuilding2 = ASnippet.GetSnippet("PRIMARYKEYINFODICTBUILDING");
                            PKInfoDictBuilding2.SetCodelet("PKCOLUMNLABEL", formalParametersPrimaryKeySeparate2[Counter].Item3);
                            PKInfoDictBuilding2.SetCodelet("PKCOLUMNCONTENT", "\"\"");
                            snippetCount.InsertSnippet("PRIMARYKEYINFODICTBUILDING2", PKInfoDictBuilding2);
                        }

                        snippetCount.SetCodelet("PRIMARYKEYCOLUMNCOUNT2", OtherTable.GetPrimaryKey().strThisFields.Count.ToString());

                        ASnippet.InsertSnippet("COUNTBYPRIMARYKEYCASCADING", snippetCount);

                        snippetCount = ASnippet.GetSnippet("COUNTBYTEMPLATECASCADING");
                        snippetCount.SetCodelet("OTHERTABLENAME", TTable.NiceTableName(constraint.strThisTable));
                        snippetCount.SetCodelet("OTHERTABLELABEL", OtherTable.strLabel);
                        snippetCount.SetCodelet("MYOTHERTABLENAME", MyOtherTableName);
                        snippetCount.SetCodelet("VIAPROCEDURENAME", "Via" + LoadViaProcedureName);
                        snippetCount.SetCodelet("CSVLISTOTHERPRIMARYKEYFIELDS", csvListOtherPrimaryKeyFields);
                        snippetCount.SetCodelet("OTHERTABLEALSOCASCADING", "true");

                        for (int Counter = 0; Counter < OtherTable.GetPrimaryKey().strThisFields.Count; Counter++)
                        {
                            ProcessTemplate PKInfoDictBuilding2 = ASnippet.GetSnippet("PRIMARYKEYINFODICTBUILDING");
                            PKInfoDictBuilding2.SetCodelet("PKCOLUMNLABEL", formalParametersPrimaryKeySeparate2[Counter].Item3);
                            PKInfoDictBuilding2.SetCodelet("PKCOLUMNCONTENT", "\"\"");
                            snippetCount.InsertSnippet("PRIMARYKEYINFODICTBUILDING2", PKInfoDictBuilding2);
                        }

                        snippetCount.SetCodelet("PRIMARYKEYCOLUMNCOUNT2", OtherTable.GetPrimaryKey().strThisFields.Count.ToString());

                        ASnippet.InsertSnippet("COUNTBYTEMPLATECASCADING", snippetCount);
                    }
                }
            }

            return(true);
        }
Beispiel #19
0
        /// <summary>
        /// code for generating typed datasets
        /// </summary>
        /// <param name="AInputXmlfile"></param>
        /// <param name="AOutputPath"></param>
        /// <param name="ANameSpace"></param>
        /// <param name="store"></param>
        /// <param name="groups"></param>
        /// <param name="AFilename"></param>
        public static void CreateTypedDataSets(String AInputXmlfile,
                                               String AOutputPath,
                                               String ANameSpace,
                                               TDataDefinitionStore store,
                                               string[] groups,
                                               string AFilename)
        {
            Console.WriteLine("processing dataset " + ANameSpace);

            string          templateDir = TAppSettingsManager.GetValue("TemplateDir", true);
            ProcessTemplate Template    = new ProcessTemplate(templateDir + Path.DirectorySeparatorChar +
                                                              "ORM" + Path.DirectorySeparatorChar +
                                                              "DataSet.cs");

            Template.AddSnippetsFromOtherFile(templateDir + Path.DirectorySeparatorChar +
                                              "ORM" + Path.DirectorySeparatorChar +
                                              "DataTable.cs");

            DataSetTableIdCounter = Convert.ToInt16(TAppSettingsManager.GetValue("StartTableId"));

            // load default header with license and copyright
            Template.SetCodelet("GPLFILEHEADER", ProcessTemplate.LoadEmptyFileComment(templateDir));

            Template.SetCodelet("NAMESPACE", ANameSpace);

            // if no dataset is defined yet in the xml file, the following variables can be empty
            Template.AddToCodelet("USINGNAMESPACES", "");
            Template.AddToCodelet("CONTENTDATASETSANDTABLESANDROWS", "");

            TXMLParser  parserDataSet = new TXMLParser(AInputXmlfile, false);
            XmlDocument myDoc         = parserDataSet.GetDocument();
            XmlNode     startNode     = myDoc.DocumentElement;

            if (startNode.Name.ToLower() == "petradatasets")
            {
                XmlNode cur = TXMLParser.NextNotBlank(startNode.FirstChild);

                while ((cur != null) && (cur.Name.ToLower() == "importunit"))
                {
                    Template.AddToCodelet("USINGNAMESPACES", "using " + TXMLParser.GetAttribute(cur, "name") + ";" + Environment.NewLine);
                    cur = TXMLParser.GetNextEntity(cur);
                }

                while ((cur != null) && (cur.Name.ToLower() == "dataset"))
                {
                    ProcessTemplate snippetDataset = Template.GetSnippet("TYPEDDATASET");
                    string          datasetname    = TXMLParser.GetAttribute(cur, "name");
                    snippetDataset.SetCodelet("DATASETNAME", datasetname);

                    // INITCONSTRAINTS and INITRELATIONS can be empty
                    snippetDataset.AddToCodelet("INITCONSTRAINTS", "");
                    snippetDataset.AddToCodelet("INITRELATIONS", "");

                    SortedList <string, TDataSetTable> tables = new SortedList <string, TDataSetTable>();

                    XmlNode curChild = cur.FirstChild;

                    while (curChild != null)
                    {
                        if ((curChild.Name.ToLower() == "table") && TXMLParser.HasAttribute(curChild, "sqltable"))
                        {
                            bool   OverloadTable = false;
                            string tabletype     = TTable.NiceTableName(TXMLParser.GetAttribute(curChild, "sqltable"));
                            string variablename  = (TXMLParser.HasAttribute(curChild, "name") ?
                                                    TXMLParser.GetAttribute(curChild, "name") :
                                                    tabletype);

                            TDataSetTable table = new TDataSetTable(
                                TXMLParser.GetAttribute(curChild, "sqltable"),
                                tabletype,
                                variablename,
                                store.GetTable(tabletype));
                            XmlNode tableNodes = curChild.FirstChild;

                            while (tableNodes != null)
                            {
                                if (tableNodes.Name.ToLower() == "customfield")
                                {
                                    // eg. BestAddress in PartnerEditTDS.PPartnerLocation
                                    TTableField customField = new TTableField();
                                    customField.strName        = TXMLParser.GetAttribute(tableNodes, "name");
                                    customField.strTypeDotNet  = TXMLParser.GetAttribute(tableNodes, "type");
                                    customField.strDescription = TXMLParser.GetAttribute(tableNodes, "comment");
                                    customField.strDefault     = TXMLParser.GetAttribute(tableNodes, "initial");
                                    table.grpTableField.Add(customField);

                                    OverloadTable = true;
                                }

                                if (tableNodes.Name.ToLower() == "field")
                                {
                                    // eg. UnitName in PartnerEditTDS.PPerson
                                    TTableField field = new TTableField(store.GetTable(TXMLParser.GetAttribute(tableNodes, "sqltable")).
                                                                        GetField(TXMLParser.GetAttribute(tableNodes, "sqlfield")));

                                    if (TXMLParser.HasAttribute(tableNodes, "name"))
                                    {
                                        field.strNameDotNet = TXMLParser.GetAttribute(tableNodes, "name");
                                    }

                                    if (TXMLParser.HasAttribute(tableNodes, "comment"))
                                    {
                                        field.strDescription = TXMLParser.GetAttribute(tableNodes, "comment");
                                    }

                                    table.grpTableField.Add(field);

                                    OverloadTable = true;
                                }

                                if (tableNodes.Name.ToLower() == "primarykey")
                                {
                                    TConstraint primKeyConstraint = table.GetPrimaryKey();
                                    primKeyConstraint.strThisFields = StringHelper.StrSplit(TXMLParser.GetAttribute(tableNodes,
                                                                                                                    "thisFields"), ",");

                                    OverloadTable = true;
                                }

                                tableNodes = tableNodes.NextSibling;
                            }

                            if (OverloadTable)
                            {
                                tabletype = datasetname + TTable.NiceTableName(table.strName);

                                if (TXMLParser.HasAttribute(curChild, "name"))
                                {
                                    tabletype = datasetname + TXMLParser.GetAttribute(curChild, "name");
                                }

                                table.strDotNetName            = tabletype;
                                table.strVariableNameInDataset = variablename;

                                // set tableid
                                table.iOrder = DataSetTableIdCounter++;

                                // TODO: can we derive from the base table, and just overload a few functions?
                                CodeGenerationTable.InsertTableDefinition(snippetDataset, table, store.GetTable(table.tableorig), "TABLELOOP", true);
                                CodeGenerationTable.InsertRowDefinition(snippetDataset, table, store.GetTable(table.tableorig), "TABLELOOP");
                            }

                            tables.Add(variablename, table);

                            AddTableToDataset(tabletype, variablename,
                                              snippetDataset);
                        }
                        else if ((curChild.Name.ToLower() == "table") && TXMLParser.HasAttribute(curChild, "customtable"))
                        {
                            // this refers to a custom table of another dataset, eg. BestAddressTDSLocation
                            // for the moment, such a table cannot have additional fields
                            if (curChild.HasChildNodes)
                            {
                                throw new Exception(
                                          String.Format(
                                              "CreateTypedDataSets(): At the moment, a custom table referenced from another dataset cannot have additional fields. Dataset: {0}, Table: {1}",
                                              datasetname,
                                              TXMLParser.HasAttribute(curChild, "customtable")));
                            }

                            // customtable has to contain the name of the dataset, eg. BestAddressTDSLocation
                            string tabletype    = TXMLParser.GetAttribute(curChild, "customtable");
                            string variablename = (TXMLParser.HasAttribute(curChild, "name") ?
                                                   TXMLParser.GetAttribute(curChild, "name") :
                                                   tabletype);

                            AddTableToDataset(tabletype, variablename,
                                              snippetDataset);
                        }

                        if (curChild.Name.ToLower() == "customrelation")
                        {
                            ProcessTemplate tempSnippet = Template.GetSnippet("INITRELATIONS");
                            tempSnippet.SetCodelet("RELATIONNAME", TXMLParser.GetAttribute(curChild, "name"));
                            tempSnippet.SetCodelet("TABLEVARIABLENAMEPARENT", TXMLParser.GetAttribute(curChild, "parentTable"));
                            tempSnippet.SetCodelet("TABLEVARIABLENAMECHILD", TXMLParser.GetAttribute(curChild, "childTable"));
                            tempSnippet.SetCodelet("COLUMNNAMESPARENT",
                                                   StringCollectionToValuesFormattedForArray(tables, TXMLParser.GetAttribute(curChild, "parentTable"),
                                                                                             StringHelper.StrSplit(TXMLParser.GetAttribute(curChild, "parentFields"), ",")));
                            tempSnippet.SetCodelet("COLUMNNAMESCHILD",
                                                   StringCollectionToValuesFormattedForArray(tables, TXMLParser.GetAttribute(curChild, "childTable"),
                                                                                             StringHelper.StrSplit(TXMLParser.GetAttribute(curChild, "childFields"), ",")));
                            tempSnippet.SetCodelet("CREATECONSTRAINTS", TXMLParser.GetBoolAttribute(curChild, "createConstraints") ? "true" : "false");
                            snippetDataset.InsertSnippet("INITRELATIONS", tempSnippet);
                        }

                        if (curChild.Name.ToLower() == "customtable")
                        {
                            string variablename = TXMLParser.GetAttribute(curChild, "name");
                            string tabletype    = datasetname + TXMLParser.GetAttribute(curChild, "name");

                            XmlNode       customTableNodes = curChild.FirstChild;
                            TDataSetTable customTable      = new TDataSetTable(
                                tabletype,
                                tabletype,
                                variablename,
                                null);

                            // set TableId
                            customTable.iOrder                   = DataSetTableIdCounter++;
                            customTable.strDescription           = TXMLParser.GetAttribute(curChild, "comment");
                            customTable.strName                  = tabletype;
                            customTable.strDotNetName            = tabletype;
                            customTable.strVariableNameInDataset = variablename;

                            while (customTableNodes != null)
                            {
                                if (customTableNodes.Name.ToLower() == "customfield")
                                {
                                    TTableField customField = new TTableField();
                                    customField.strName        = TXMLParser.GetAttribute(customTableNodes, "name");
                                    customField.strTypeDotNet  = TXMLParser.GetAttribute(customTableNodes, "type");
                                    customField.strDescription = TXMLParser.GetAttribute(customTableNodes, "comment");
                                    customField.strDefault     = TXMLParser.GetAttribute(customTableNodes, "initial");
                                    customTable.grpTableField.Add(customField);
                                }

                                if (customTableNodes.Name.ToLower() == "field")
                                {
                                    // eg. SelectedSiteKey in PartnerEditTDS.MiscellaneousData
                                    TTableField field = new TTableField(store.GetTable(TXMLParser.GetAttribute(customTableNodes, "sqltable")).
                                                                        GetField(TXMLParser.GetAttribute(customTableNodes, "sqlfield")));

                                    if (TXMLParser.HasAttribute(customTableNodes, "name"))
                                    {
                                        field.strNameDotNet = TXMLParser.GetAttribute(customTableNodes, "name");
                                    }

                                    if (TXMLParser.HasAttribute(customTableNodes, "comment"))
                                    {
                                        field.strDescription = TXMLParser.GetAttribute(customTableNodes, "comment");
                                    }

                                    customTable.grpTableField.Add(field);
                                }

                                if (customTableNodes.Name.ToLower() == "primarykey")
                                {
                                    TConstraint primKeyConstraint = new TConstraint();
                                    primKeyConstraint.strName       = "PK";
                                    primKeyConstraint.strType       = "primarykey";
                                    primKeyConstraint.strThisFields = StringHelper.StrSplit(TXMLParser.GetAttribute(customTableNodes,
                                                                                                                    "thisFields"), ",");
                                    customTable.grpConstraint.Add(primKeyConstraint);
                                }

                                customTableNodes = customTableNodes.NextSibling;
                            }

                            tables.Add(tabletype, customTable);

                            AddTableToDataset(tabletype, variablename, snippetDataset);

                            CodeGenerationTable.InsertTableDefinition(snippetDataset, customTable, null, "TABLELOOP", true);
                            CodeGenerationTable.InsertRowDefinition(snippetDataset, customTable, null, "TABLELOOP");
                        }

                        curChild = curChild.NextSibling;
                    }

                    foreach (TDataSetTable table in tables.Values)
                    {
                        // todo? also other constraints, not only from original table?
                        foreach (TConstraint constraint in table.grpConstraint)
                        {
                            if ((constraint.strType == "foreignkey") && tables.ContainsKey(constraint.strOtherTable))
                            {
                                TDataSetTable otherTable = (TDataSetTable)tables[constraint.strOtherTable];

                                ProcessTemplate tempSnippet = Template.GetSnippet("INITCONSTRAINTS");

                                tempSnippet.SetCodelet("TABLEVARIABLENAME1", table.tablealias);
                                tempSnippet.SetCodelet("TABLEVARIABLENAME2", otherTable.tablealias);
                                tempSnippet.SetCodelet("CONSTRAINTNAME", TTable.NiceKeyName(constraint));

                                tempSnippet.SetCodelet("COLUMNNAMES1", StringCollectionToValuesFormattedForArray(constraint.strThisFields));
                                tempSnippet.SetCodelet("COLUMNNAMES2", StringCollectionToValuesFormattedForArray(constraint.strOtherFields));
                                snippetDataset.InsertSnippet("INITCONSTRAINTS", tempSnippet);
                            }
                        }
                    }

                    Template.InsertSnippet("CONTENTDATASETSANDTABLESANDROWS", snippetDataset);

                    cur = TXMLParser.GetNextEntity(cur);
                }
            }

            Template.FinishWriting(AOutputPath + Path.DirectorySeparatorChar + AFilename + "-generated.cs", ".cs", true);
        }
        /// <summary>
        /// write the definition for the code of a typed row
        /// </summary>
        /// <param name="Template"></param>
        /// <param name="currentTable"></param>
        /// <param name="origTable"></param>
        /// <param name="WhereToInsert"></param>
        public static void InsertRowDefinition(ProcessTemplate Template, TTable currentTable, TTable origTable, string WhereToInsert)
        {
            ProcessTemplate snippet = Template.GetSnippet("TYPEDROW");

            if (origTable != null)
            {
                snippet.SetCodelet("BASECLASSROW", TTable.NiceTableName(currentTable.strName) + "Row");
                snippet.SetCodelet("OVERRIDE", "override ");
            }
            else
            {
                snippet.SetCodelet("BASECLASSROW", "System.Data.DataRow");
                snippet.SetCodelet("OVERRIDE", "virtual ");
            }

            snippet.SetCodeletComment("TABLE_DESCRIPTION", currentTable.strDescription);
            snippet.SetCodelet("TABLENAME", currentTable.strDotNetName);

            foreach (TTableField col in currentTable.grpTableField)
            {
                ProcessTemplate tempTemplate    = null;
                string          columnOverwrite = "";

                if ((origTable != null) && (origTable.GetField(col.strName, false) != null))
                {
                    columnOverwrite = "new ";
                }

                if (columnOverwrite.Length == 0)
                {
                    tempTemplate = Template.GetSnippet("ROWCOLUMNPROPERTY");
                    tempTemplate.SetCodelet("COLUMNDBNAME", col.strName);
                    tempTemplate.SetCodelet("COLUMNNAME", col.strNameDotNet);
                    tempTemplate.SetCodelet("COLUMNHELP", col.strDescription.Replace(Environment.NewLine, " "));
                    tempTemplate.SetCodelet("COLUMNLABEL", col.strLabel);
                    tempTemplate.SetCodelet("COLUMNLENGTH", col.iLength.ToString());
                    tempTemplate.SetCodelet("COLUMNDOTNETTYPE", col.GetDotNetType());

                    if (!col.bNotNull)
                    {
                        if (col.GetDotNetType().Contains("DateTime?"))
                        {
                            tempTemplate.SetCodelet("TESTFORNULL", "!value.HasValue");
                        }
                        else if (col.GetDotNetType().Contains("String"))
                        {
                            tempTemplate.SetCodelet("TESTFORNULL", "(value == null) || (value.Length == 0)");
                        }
                    }

                    if (col.GetDotNetType().Contains("DateTime?"))
                    {
                        tempTemplate.SetCodelet("ACTIONGETNULLVALUE", "return null;");
                    }
                    else if (col.GetDotNetType().Contains("DateTime"))
                    {
                        tempTemplate.SetCodelet("ACTIONGETNULLVALUE", "return DateTime.MinValue;");
                    }
                    else if (col.GetDotNetType().ToLower().Contains("string"))
                    {
                        tempTemplate.SetCodelet("ACTIONGETNULLVALUE", "return String.Empty;");
                    }
                    else
                    {
                        tempTemplate.SetCodelet("ACTIONGETNULLVALUE", "throw new System.Data.StrongTypingException(\"Error: DB null\", null);");
                    }

                    tempTemplate.SetCodeletComment("COLUMN_DESCRIPTION", col.strDescription);
                    snippet.InsertSnippet("ROWCOLUMNPROPERTIES", tempTemplate);

                    tempTemplate = Template.GetSnippet("FUNCTIONSFORNULLVALUES");
                    tempTemplate.SetCodelet("COLUMNNAME", TTable.NiceFieldName(col));
                    snippet.InsertSnippet("FUNCTIONSFORNULLVALUES", tempTemplate);
                }

                if ((col.strDefault.Length > 0) && (col.strDefault != "NULL"))
                {
                    string defaultValue = col.strDefault;

                    if (defaultValue == "SYSDATE")
                    {
                        defaultValue = "DateTime.Today";
                    }
                    else if ((col.strType == "bit") || ((col.strTypeDotNet != null) && col.strTypeDotNet.ToLower().Contains("bool")))
                    {
                        defaultValue = (defaultValue == "1" || defaultValue.ToLower() == "true").ToString().ToLower();
                    }
                    else if ((col.strType == "varchar") || ((col.strTypeDotNet != null) && col.strTypeDotNet.ToLower().Contains("string")))
                    {
                        defaultValue = '"' + defaultValue + '"';
                    }

                    snippet.AddToCodelet("ROWSETNULLORDEFAULT", "this[this.myTable.Column" + TTable.NiceFieldName(
                                             col) + ".Ordinal] = " + defaultValue + ";" + Environment.NewLine);
                }
                else
                {
                    snippet.AddToCodelet("ROWSETNULLORDEFAULT", "this.SetNull(this.myTable.Column" + TTable.NiceFieldName(
                                             col) + ");" + Environment.NewLine);
                }
            }

            Template.InsertSnippet(WhereToInsert, snippet);
        }
Beispiel #21
0
        static private void CreateClientGlue(TNamespace tn, SortedList <string, TypeDeclaration> connectors, string AOutputPath)
        {
            String OutputFile = AOutputPath + Path.DirectorySeparatorChar + "ClientGlue.M" + tn.Name +
                                "-generated.cs";

            Console.WriteLine("working on " + OutputFile);

            ProcessTemplate Template = new ProcessTemplate(FTemplateDir + Path.DirectorySeparatorChar +
                                                           "ClientServerGlue" + Path.DirectorySeparatorChar +
                                                           "ClientGlue.cs");

            FUsingNamespaces      = new SortedList <string, string>();
            FModuleHasUIConnector = false;
            FUIConnectorsAdded    = new List <string>();

            // load default header with license and copyright
            Template.SetCodelet("GPLFILEHEADER", ProcessTemplate.LoadEmptyFileComment(FTemplateDir));

            Template.SetCodelet("TOPLEVELMODULE", tn.Name);

            string InterfacePath = Path.GetFullPath(AOutputPath).Replace(Path.DirectorySeparatorChar, '/');

            InterfacePath = InterfacePath.Substring(0, InterfacePath.IndexOf("csharp/ICT/Petra")) + "csharp/ICT/Petra/Shared/lib/Interfaces";
            Template.AddToCodelet("USINGNAMESPACES", CreateInterfaces.AddNamespacesFromYmlFile(InterfacePath, tn.Name));

            if (AOutputPath.Contains("ICT/Petra/Plugins/"))
            {
                // add namespaces that are required by the plugin
                InterfacePath = Path.GetFullPath(AOutputPath + "/../").Replace(Path.DirectorySeparatorChar, '/');
                Template.AddToCodelet("USINGNAMESPACES", CreateInterfaces.AddNamespacesFromYmlFile(InterfacePath, "Plugin"));
            }

            string SharedPathName = "Ict.Petra.Shared.M" + tn.Name;

            if (SharedPathName.Contains("ServerAdmin"))
            {
                SharedPathName = "Ict.Petra.Server.App.Core." + tn.Name;
            }
            else if (OutputFile.Contains("ICT/Petra/Plugins"))
            {
                SharedPathName = "Ict.Petra.Plugins." + tn.Name;
            }

            InsertSubNamespaces(Template, connectors, tn.Name, SharedPathName, tn);

            if (FModuleHasUIConnector)
            {
                Template.AddToCodelet("USINGNAMESPACES", "using Ict.Petra.Shared.Interfaces.M" + tn.Name + ";" + Environment.NewLine);
            }

            foreach (string usingNamespace in FUsingNamespaces.Keys)
            {
                Template.AddToCodelet("USINGNAMESPACES", "using " + usingNamespace + ";" + Environment.NewLine);
            }

            if (OutputFile.Contains("ClientGlue.MServerAdmin"))
            {
                Template.SetCodelet("REMOTEOBJECTSNAMESPACE", "Ict.Petra.ServerAdmin.App.Core.RemoteObjects");
            }
            else if (OutputFile.Contains("ICT/Petra/Plugins"))
            {
                string pluginWithNamespace = TAppSettingsManager.GetValue("plugin");
                Template.SetCodelet("REMOTEOBJECTSNAMESPACE", pluginWithNamespace + ".RemoteObjects");
            }
            else
            {
                Template.SetCodelet("REMOTEOBJECTSNAMESPACE", "Ict.Petra.Client.App.Core.RemoteObjects");
            }

            Template.FinishWriting(OutputFile, ".cs", true);
        }
        /// <summary>
        /// write the interfaces for the Connectors
        /// parses the connector files
        /// </summary>
        /// <param name="ATemplate">template that the code should be added to</param>
        /// <param name="AMethodsAlreadyWritten">a string list of method names that have been written</param>
        /// <param name="AConnectorClasses">all connector classes that implement the interface</param>
        /// <param name="AInterfaceName">the name of the interface we are writing to; it ends with ConnectorsNamespace</param>
        /// <param name="AInterfaceNamespace"></param>
        /// <param name="AServerNamespace">for the comment in the autogenerated code</param>
        /// <returns></returns>
        private bool WriteConnectorConstructors(
            ProcessTemplate ATemplate,
            ref StringCollection AMethodsAlreadyWritten,
            List <TypeDeclaration> AConnectorClasses, String AInterfaceName, String AInterfaceNamespace, String AServerNamespace)
        {
            string ServerNamespace = AInterfaceNamespace.Replace("Ict.Petra.Shared.Interfaces", "Ict.Petra.Server");

            foreach (TypeDeclaration t in AConnectorClasses)
            {
                string ConnectorClassName = t.Name;

                // cacheable will not work yet; careful: when building MethodName, connectorName does not have a plural s
                // but that cacheable constructor is not needed anyways???

                if (ConnectorClassName.StartsWith("T") &&
                    (ConnectorClassName.EndsWith("UIConnector") ||
                     ConnectorClassName.EndsWith("LogicConnector") ||
                     ConnectorClassName.EndsWith("Lookup") ||
                     ConnectorClassName.EndsWith("Reader")))
                {
                    // create a method for the interface, that returns the interface that the connector class is derived from,
                    // and takes the parameters from the constructor of the connector class
                    // it is named: remove first character T and trailing UIConnector/LogicConnector from the name of the connector class

                    // get the connector name from the namespace
                    StringCollection namespaceList = StringHelper.StrSplit(ServerNamespace, ".");

                    // connectorName eg. UIConnectors, LogicConnectors, ServerLookups, Cacheable
                    string connectorName = namespaceList[namespaceList.Count - 1];
                    string MethodName    = ConnectorClassName.Substring(1,
                                                                        ConnectorClassName.Length - 1 - (connectorName.Length - 1));
                    string MethodType = "";

                    foreach (TypeReference ti in t.BaseTypes)
                    {
                        // problem, eg. in MCommon, TOfficeSpecificDataLabelsUIConnector implements 2 interfaces
                        if ((ti.Type != "TConfigurableMBRObject") &&
                            (ti.Type == AInterfaceName))
                        {
                            MethodType = ti.Type;
                        }
                    }

                    if (MethodType.Length == 0)
                    {
                        // no valid interface has been derived; eg. Hospitality not finished yet
                        continue;
                    }

                    List <ConstructorDeclaration> constructors = CSParser.GetConstructors(t);

                    if (constructors.Count == 0)
                    {
                        // will cause compile error if the constructor is missing, because it is not implementing the interface completely
                        throw new Exception("missing a connector constructor in " + ServerNamespace + "." + ConnectorClassName);

//                    WriteLine("/// <summary>auto generated - there was no Connector constructor (" + ServerNamespace + "." + ConnectorClassName + ")</summary>");
//                    AMethodsAlreadyWritten.Add(MethodName);
//                    string MethodDeclaration = MethodType + " " + MethodName + "();";
//                    WriteLine(MethodDeclaration);
                    }
                    else
                    {
                        // find constructor and copy the parameters
                        foreach (ConstructorDeclaration m in constructors)
                        {
                            ATemplate.AddToCodelet(
                                "CONTENT",
                                "/// <summary>auto generated from Connector constructor (" + ServerNamespace + "." + ConnectorClassName + ")</summary>" +
                                Environment.NewLine);
                            AMethodsAlreadyWritten.Add(MethodName);
                            string MethodDeclaration = MethodType + " " + MethodName + "(";
                            int    align             = MethodDeclaration.Length;
                            bool   firstParameter    = true;

                            foreach (ParameterDeclarationExpression p in m.Parameters)
                            {
                                AutoGenerationTools.AddParameter(ref MethodDeclaration,
                                                                 ref firstParameter,
                                                                 align,
                                                                 p.ParameterName,
                                                                 p.ParamModifier,
                                                                 p.TypeReference.Type);
                            }

                            MethodDeclaration += ");";
                            ATemplate.AddToCodelet("CONTENT", MethodDeclaration + Environment.NewLine);
                        }
                    }
                }
            }

            return(true);
        }
        /// <summary>
        /// write the interfaces for the methods that need to be reflected
        /// check connector files
        /// </summary>
        /// <param name="ATemplate"></param>
        /// <param name="AMethodsAlreadyWritten">write methods only once</param>
        /// <param name="AConnectorClasses">the classes that are implementing the methods</param>
        /// <param name="AInterfaceName">the interface that is written at the moment</param>
        /// <param name="AInterfaceNamespace">only needed to shorten the type names to improve readability</param>
        /// <param name="AServerNamespace">for the comment in the autogenerated code</param>
        /// <returns></returns>
        private bool WriteConnectorMethods(
            ProcessTemplate ATemplate,
            ref StringCollection AMethodsAlreadyWritten,
            List <TypeDeclaration> AConnectorClasses, String AInterfaceName, String AInterfaceNamespace, String AServerNamespace)
        {
            foreach (TypeDeclaration t in AConnectorClasses)
            {
                string ConnectorClassName = t.Name;

                foreach (PropertyDeclaration p in CSParser.GetProperties(t))
                {
                    if (TCollectConnectorInterfaces.IgnoreMethod(p.Attributes, p.Modifier))
                    {
                        continue;
                    }

                    if (!p.GetRegion.Block.ToString().Contains("TCreateRemotableObject"))
                    {
                        TLogging.Log("Warning: properties in UIConnectors must use the class TCreateRemotableObject: " +
                                     AServerNamespace + "." + t.Name + "." + p.Name);
                    }

                    // don't write namespace hierarchy here
                    if (p.TypeReference.Type.IndexOf("Namespace") == -1)
                    {
                        String returnType = AutoGenerationTools.TypeToString(p.TypeReference, AInterfaceNamespace);

                        // this interface got implemented somewhere on the server
                        ProcessTemplate snippet = ATemplate.GetSnippet("CONNECTORPROPERTY");
                        snippet.SetCodelet("CONNECTORCLASSNAME", ConnectorClassName);
                        snippet.SetCodelet("SERVERNAMESPACE", AServerNamespace);
                        snippet.SetCodelet("TYPE", returnType);
                        snippet.SetCodelet("NAME", p.Name);

                        if (p.HasGetRegion)
                        {
                            snippet.SetCodelet("GETTER", "true");
                        }

                        if (p.HasSetRegion)
                        {
                            snippet.SetCodelet("SETTER", "true");
                        }

                        ATemplate.InsertSnippet("CONTENT", snippet);
                    }
                }

                foreach (MethodDeclaration m in CSParser.GetMethods(t))
                {
                    string MethodName = m.Name;

                    if (TCollectConnectorInterfaces.IgnoreMethod(m.Attributes, m.Modifier))
                    {
                        continue;
                    }

                    String formattedMethod = "";
                    String returnType      = AutoGenerationTools.TypeToString(m.TypeReference, AInterfaceNamespace);

                    int align = (returnType + " " + m.Name).Length + 1;

                    // this interface got implemented somewhere on the server
                    formattedMethod = "/// <summary> auto generated from Connector method(" + AServerNamespace + "." + ConnectorClassName +
                                      ")</summary>" + Environment.NewLine;
                    formattedMethod += returnType + " " + m.Name + "(";

                    bool firstParameter = true;

                    foreach (ParameterDeclarationExpression p in m.Parameters)
                    {
                        if (!firstParameter)
                        {
                            ATemplate.AddToCodelet("CONTENT", formattedMethod + "," + Environment.NewLine);
                            formattedMethod = new String(' ', align);
                        }

                        firstParameter = false;
                        String parameterType = AutoGenerationTools.TypeToString(p.TypeReference, "");

                        if ((p.ParamModifier & ParameterModifiers.Ref) != 0)
                        {
                            formattedMethod += "ref ";
                        }
                        else if ((p.ParamModifier & ParameterModifiers.Out) != 0)
                        {
                            formattedMethod += "out ";
                        }

                        formattedMethod += parameterType + " " + p.ParameterName;
                    }

                    formattedMethod += ");";
                    AMethodsAlreadyWritten.Add(MethodName);
                    ATemplate.AddToCodelet("CONTENT", formattedMethod + Environment.NewLine);
                }
            }

            return(true);
        }
Beispiel #24
0
        /// <summary>
        /// main function for generating access methods for typed data sets
        /// </summary>
        /// <param name="AInputXmlfile"></param>
        /// <param name="AOutputPath"></param>
        /// <param name="ANameSpace"></param>
        /// <param name="store"></param>
        /// <param name="groups"></param>
        /// <param name="AFilename"></param>
        public static void CreateTypedDataSets(String AInputXmlfile,
                                               String AOutputPath,
                                               String ANameSpace,
                                               TDataDefinitionStore store,
                                               string[] groups,
                                               string AFilename)
        {
            Console.WriteLine("processing dataset " + ANameSpace);

            string          templateDir = TAppSettingsManager.GetValue("TemplateDir", true);
            ProcessTemplate Template    = new ProcessTemplate(templateDir + Path.DirectorySeparatorChar +
                                                              "ORM" + Path.DirectorySeparatorChar +
                                                              "DataSetAccess.cs");

            // load default header with license and copyright
            Template.SetCodelet("GPLFILEHEADER", ProcessTemplate.LoadEmptyFileComment(templateDir));

            Template.SetCodelet("NAMESPACE", ANameSpace);

            // if no dataset is defined yet in the xml file, the following variables can be empty
            Template.AddToCodelet("USINGNAMESPACES", "");
            Template.AddToCodelet("CONTENTDATASETSANDTABLESANDROWS", "");

            Template.AddToCodelet("USINGNAMESPACES", "using " + ANameSpace.Replace(".Server.", ".Shared.") + ";" + Environment.NewLine, false);

            TXMLParser  parserDataSet = new TXMLParser(AInputXmlfile, false);
            XmlDocument myDoc         = parserDataSet.GetDocument();
            XmlNode     startNode     = myDoc.DocumentElement;

            if (startNode.Name.ToLower() == "petradatasets")
            {
                XmlNode cur = TXMLParser.NextNotBlank(startNode.FirstChild);

                while ((cur != null) && (cur.Name.ToLower() == "importunit"))
                {
                    Template.AddToCodelet("USINGNAMESPACES", "using " + TXMLParser.GetAttribute(cur, "name") + ";" + Environment.NewLine, false);
                    Template.AddToCodelet("USINGNAMESPACES", "using " + TXMLParser.GetAttribute(cur, "name").Replace(".Shared.",
                                                                                                                     ".Server.") + ".Access;" + Environment.NewLine, false);
                    cur = TXMLParser.GetNextEntity(cur);
                }

                while ((cur != null) && (cur.Name.ToLower() == "dataset"))
                {
                    ProcessTemplate snippetDataset = Template.GetSnippet("TYPEDDATASET");
                    string          datasetname    = TXMLParser.GetAttribute(cur, "name");
                    snippetDataset.SetCodelet("DATASETNAME", datasetname);

                    ProcessTemplate snippetSubmitChanges = snippetDataset.GetSnippet("SUBMITCHANGESFUNCTION");
                    snippetSubmitChanges.AddToCodelet("DATASETNAME", datasetname);

                    List <TDataSetTable> tables = new List <TDataSetTable>();

                    XmlNode curChild = cur.FirstChild;

                    // first collect the tables
                    while (curChild != null)
                    {
                        if (curChild.Name.ToLower() == "table")
                        {
                            string tabletype    = TTable.NiceTableName(TXMLParser.GetAttribute(curChild, "sqltable"));
                            string variablename = (TXMLParser.HasAttribute(curChild, "name") ?
                                                   TXMLParser.GetAttribute(curChild, "name") :
                                                   tabletype);

                            TDataSetTable table = new TDataSetTable(
                                TXMLParser.GetAttribute(curChild, "sqltable"),
                                tabletype,
                                variablename,
                                store.GetTable(tabletype));

                            tables.Add(table);
                        }

                        curChild = curChild.NextSibling;
                    }

                    foreach (TDataSetTable table in tables)
                    {
                        AddTableToDataset(tables,
                                          store.GetTable(table.tableorig),
                                          table.tablename,
                                          table.tablealias,
                                          snippetDataset,
                                          snippetSubmitChanges);
                    }

                    // there is one codelet for the dataset name.
                    // only add the full submitchanges function if there are any table to submit
                    if (snippetSubmitChanges.FCodelets.Count > 1)
                    {
                        snippetDataset.InsertSnippet("SUBMITCHANGESFUNCTION", snippetSubmitChanges);
                    }
                    else
                    {
                        snippetDataset.AddToCodelet("SUBMITCHANGESFUNCTION", "");
                    }

                    Template.InsertSnippet("CONTENTDATASETSANDTABLESANDROWS", snippetDataset);

                    cur = TXMLParser.GetNextEntity(cur);
                }
            }

            Template.FinishWriting(AOutputPath + Path.DirectorySeparatorChar + AFilename + "-generated.cs", ".cs", true);
        }
        /// <summary>
        /// situation 2: bridging tables
        /// for example p_location and p_partner are connected through p_partner_location
        /// it would be helpful, to be able to do:
        /// location.LoadViaPartner(partnerkey) to get all locations of the partner
        /// partner.loadvialocation(locationkey) to get all partners living at that location
        /// general solution: pick up all foreign keys from other tables (B) to the primary key of the current table (A),
        /// where the other table has a foreign key to another table (C), using other fields in the primary key of (B) than the link to (A).
        /// get all tables that reference the current table
        /// </summary>
        /// <param name="AStore"></param>
        /// <param name="ACurrentTable"></param>
        /// <param name="ATemplate"></param>
        /// <param name="ASnippet"></param>
        private static void InsertViaLinkTable(TDataDefinitionStore AStore, TTable ACurrentTable, ProcessTemplate ATemplate, ProcessTemplate ASnippet)
        {
            // step 1: collect all the valid constraints of such link tables
            ArrayList OtherLinkConstraints = new ArrayList();
            ArrayList References           = new ArrayList();

            foreach (TConstraint Reference in ACurrentTable.GetReferences())
            {
                TTable LinkTable = AStore.GetTable(Reference.strThisTable);
                try
                {
                    TConstraint LinkPrimaryKey = LinkTable.GetPrimaryKey();

                    if (StringHelper.Contains(LinkPrimaryKey.strThisFields, Reference.strThisFields))
                    {
                        // check how many constraints from the link table are from fields in the primary key
                        // a link table only should have 2
                        // so find the other one
                        TConstraint OtherLinkConstraint = null;
                        bool        IsLinkTable         = false;

                        foreach (TConstraint LinkConstraint in LinkTable.grpConstraint)
                        {
                            // check if there is another constraint for the primary key of the link table.
                            if (ValidForeignKeyConstraintForLoadVia(LinkConstraint) && (LinkConstraint != Reference) &&
                                (StringHelper.Contains(LinkPrimaryKey.strThisFields, LinkConstraint.strThisFields)))
                            {
                                if (OtherLinkConstraint == null)
                                {
                                    OtherLinkConstraint = LinkConstraint;
                                    IsLinkTable         = true;
                                }
                                else
                                {
                                    IsLinkTable = false;
                                }
                            }
                            else if (ValidForeignKeyConstraintForLoadVia(LinkConstraint) && (LinkConstraint != Reference) &&
                                     (!StringHelper.Contains(LinkPrimaryKey.strThisFields, LinkConstraint.strThisFields)) &&
                                     StringHelper.ContainsSome(LinkPrimaryKey.strThisFields, LinkConstraint.strThisFields))
                            {
                                // if there is a key that partly is in the primary key, then this is not a link table.
                                OtherLinkConstraint = LinkConstraint;
                                IsLinkTable         = false;
                            }
                        }

                        if ((IsLinkTable) && (OtherLinkConstraint.strOtherTable != Reference.strOtherTable))
                        {
                            // collect the links. then we are able to name them correctly, once we need them
                            OtherLinkConstraints.Add(OtherLinkConstraint);
                            References.Add(Reference);
                        }
                    }
                }
                catch (Exception)
                {
                    // Console.WriteLine(e.Message);
                }
            }

            // step2: implement the link tables, using correct names for the procedures
            int Count = 0;

            foreach (TConstraint OtherLinkConstraint in OtherLinkConstraints)
            {
                TTable OtherTable    = AStore.GetTable(OtherLinkConstraint.strOtherTable);
                string ProcedureName = "Via" + TTable.NiceTableName(OtherTable.strName);

                // check if other foreign key exists that references the same table, e.g.
                // PPartnerAccess.LoadViaSUserPRecentPartners
                // PPartnerAccess.LoadViaSUserPCustomisedGreeting
                // also PFoundationProposalAccess.LoadViaPFoundationPFoundationProposalDetail and
                // TODO AlreadyExistsProcedureSameName necessary for PPersonAccess.LoadViaPUnit (p_field_key_n) and PPersonAccess.LoadViaPUnitPmGeneralApplication
                // Question: does PPersonAccess.LoadViaPUnitPmGeneralApplication make sense?
                if (FindOtherConstraintSameOtherTable2(OtherLinkConstraints,
                                                       OtherLinkConstraint) ||
                    LoadViaHasAlreadyBeenImplemented(OtherLinkConstraint)

                    // TODO || AlreadyExistsProcedureSameName(ProcedureName)
                    || ((ProcedureName == "ViaPUnit") && (OtherLinkConstraint.strThisTable == "pm_general_application"))
                    )
                {
                    ProcedureName += TTable.NiceTableName(OtherLinkConstraint.strThisTable);
                }

                ATemplate.AddToCodelet("USINGNAMESPACES",
                                       GetNamespace(OtherTable.strGroup), false);

                ProcessTemplate snippetLinkTable = ATemplate.GetSnippet("VIALINKTABLE");

                snippetLinkTable.SetCodelet("VIAPROCEDURENAME", ProcedureName);
                snippetLinkTable.SetCodelet("OTHERTABLENAME", TTable.NiceTableName(OtherTable.strName));
                snippetLinkTable.SetCodelet("SQLOTHERTABLENAME", OtherTable.strName);
                snippetLinkTable.SetCodelet("SQLLINKTABLENAME", OtherLinkConstraint.strThisTable);

                string notUsed;
                int    notUsedInt;
                string formalParametersOtherPrimaryKey;
                string actualParametersOtherPrimaryKey;

                PrepareCodeletsPrimaryKey(OtherTable,
                                          out formalParametersOtherPrimaryKey,
                                          out actualParametersOtherPrimaryKey,
                                          out notUsed,
                                          out notUsedInt);

                PrepareCodeletsPrimaryKey(ACurrentTable,
                                          out notUsed,
                                          out notUsed,
                                          out notUsed,
                                          out notUsedInt);

                string whereClauseForeignKey;
                string whereClauseViaOtherTable;
                string odbcParametersForeignKey;
                PrepareCodeletsForeignKey(
                    OtherTable,
                    OtherLinkConstraint,
                    out whereClauseForeignKey,
                    out whereClauseViaOtherTable,
                    out odbcParametersForeignKey,
                    out notUsedInt,
                    out notUsed);

                string whereClauseViaLinkTable;
                string whereClauseAllViaTables;
                PrepareCodeletsViaLinkTable(
                    (TConstraint)References[Count],
                    OtherLinkConstraint,
                    out whereClauseViaLinkTable,
                    out whereClauseAllViaTables);

                snippetLinkTable.SetCodelet("FORMALPARAMETERSOTHERPRIMARYKEY", formalParametersOtherPrimaryKey);
                snippetLinkTable.SetCodelet("ACTUALPARAMETERSOTHERPRIMARYKEY", actualParametersOtherPrimaryKey);
                snippetLinkTable.SetCodelet("ODBCPARAMETERSFOREIGNKEY", odbcParametersForeignKey);
                snippetLinkTable.SetCodelet("WHERECLAUSEVIALINKTABLE", whereClauseViaLinkTable);
                snippetLinkTable.SetCodelet("WHERECLAUSEALLVIATABLES", whereClauseAllViaTables);

                ASnippet.InsertSnippet("VIALINKTABLE", snippetLinkTable);

                Count = Count + 1;
            }
        }
        /// <summary>
        /// insert the viaothertable functions for one specific constraint
        /// </summary>
        /// <param name="AStore"></param>
        /// <param name="AConstraint"></param>
        /// <param name="ACurrentTable"></param>
        /// <param name="AOtherTable"></param>
        /// <param name="ATemplate"></param>
        /// <param name="ASnippet"></param>
        private static void InsertViaOtherTableConstraint(TDataDefinitionStore AStore,
                                                          TConstraint AConstraint,
                                                          TTable ACurrentTable,
                                                          TTable AOtherTable,
                                                          ProcessTemplate ATemplate,
                                                          ProcessTemplate ASnippet)
        {
            ATemplate.AddToCodelet("USINGNAMESPACES",
                                   GetNamespace(AOtherTable.strGroup), false);

            ProcessTemplate snippetViaTable = ATemplate.GetSnippet("VIAOTHERTABLE");

            snippetViaTable.SetCodelet("OTHERTABLENAME", TTable.NiceTableName(AOtherTable.strName));
            snippetViaTable.SetCodelet("SQLOTHERTABLENAME", AOtherTable.strName);

            string ProcedureName = "Via" + TTable.NiceTableName(AOtherTable.strName);

            // check if other foreign key exists that references the same table, e.g.
            // PBankAccess.CountViaPPartnerPartnerKey
            // PBankAccess.CountViaPPartnerContactPartnerKey
            string DifferentField = FindOtherConstraintSameOtherTable(ACurrentTable.grpConstraint, AConstraint);

            if (DifferentField.Length != 0)
            {
                ProcedureName += TTable.NiceFieldName(DifferentField);
            }

            int    notUsedInt;
            string formalParametersOtherPrimaryKey;
            string actualParametersOtherPrimaryKey;
            string dummy;

            PrepareCodeletsPrimaryKey(AOtherTable,
                                      out formalParametersOtherPrimaryKey,
                                      out actualParametersOtherPrimaryKey,
                                      out dummy,
                                      out notUsedInt);

            int numberFields;

            string namesOfThisTableFields;
            string notUsed;

            PrepareCodeletsForeignKey(
                AOtherTable,
                AConstraint,
                out notUsed,
                out notUsed,
                out notUsed,
                out numberFields,
                out namesOfThisTableFields);

            snippetViaTable.SetCodelet("VIAPROCEDURENAME", ProcedureName);
            snippetViaTable.SetCodelet("FORMALPARAMETERSOTHERPRIMARYKEY", formalParametersOtherPrimaryKey);
            snippetViaTable.SetCodelet("ACTUALPARAMETERSOTHERPRIMARYKEY", actualParametersOtherPrimaryKey);
            snippetViaTable.SetCodelet("NUMBERFIELDS", numberFields.ToString());
            snippetViaTable.SetCodelet("NUMBERFIELDSOTHER", (actualParametersOtherPrimaryKey.Split(',').Length).ToString());
            snippetViaTable.SetCodelet("THISTABLEFIELDS", namesOfThisTableFields);

            AddDirectReference(AConstraint);

            ASnippet.InsertSnippet("VIAOTHERTABLE", snippetViaTable);
        }
Beispiel #27
0
        /// <summary>
        /// create code for a table that is part of a dataset
        /// </summary>
        /// <param name="ATables"></param>
        /// <param name="ASqltable"></param>
        /// <param name="tabletype"></param>
        /// <param name="variablename"></param>
        /// <param name="snippetDataset"></param>
        /// <param name="ASnippetSubmitChanges"></param>
        private static void AddTableToDataset(
            List <TDataSetTable> ATables,
            TTable ASqltable,
            string tabletype,
            string variablename,
            ProcessTemplate snippetDataset,
            ProcessTemplate ASnippetSubmitChanges)
        {
            ProcessTemplate tempSnippet;

            if (ASqltable != null)
            {
                string SequenceColumn = "";
                string SequenceName   = "";

                foreach (TTableField tablefield in ASqltable.grpTableField)
                {
                    // is there a field filled by a sequence?
                    // yes: get the next value of that sequence and assign to row
                    if (tablefield.strSequence.Length > 0)
                    {
                        SequenceName   = tablefield.strSequence;
                        SequenceColumn = tablefield.strName;

                        // assume only one sequence per table
                        break;
                    }
                }

                tempSnippet = snippetDataset.GetSnippet("SUBMITCHANGES");
                tempSnippet.SetCodelet("ORIGTABLENAME", TTable.NiceTableName(ASqltable.strName));
                tempSnippet.SetCodelet("TABLETYPENAME", tabletype);
                tempSnippet.SetCodelet("TABLEVARIABLENAME", variablename);
                tempSnippet.SetCodelet("SQLOPERATION", "eDelete");
                tempSnippet.SetCodelet("SEQUENCENAMEANDFIELD", "");
                ASnippetSubmitChanges.InsertSnippetPrepend("SUBMITCHANGESDELETE", tempSnippet);

                tempSnippet = snippetDataset.GetSnippet("SUBMITCHANGES");
                tempSnippet.SetCodelet("ORIGTABLENAME", TTable.NiceTableName(ASqltable.strName));
                tempSnippet.SetCodelet("TABLETYPENAME", tabletype);
                tempSnippet.SetCodelet("TABLEVARIABLENAME", variablename);
                tempSnippet.SetCodelet("SQLOPERATION", "eInsert | TTypedDataAccess.eSubmitChangesOperations.eUpdate");
                tempSnippet.SetCodelet("SEQUENCENAMEANDFIELD", "");

                if (SequenceName.Length > 0)
                {
                    tempSnippet.SetCodelet("SEQUENCENAMEANDFIELD", ", \"" + SequenceName + "\", \"" + SequenceColumn + "\"");

                    // look for other tables in the dataset that have a foreign key on the sequenced column
                    // eg. p_location_key_i is set when storing p_location.
                    //     now we should update p_partner_location, which still has negative values in p_location_key_i
                    foreach (TDataSetTable table in ATables)
                    {
                        foreach (TConstraint constraint in table.grpConstraint)
                        {
                            if ((constraint.strType == "foreignkey") &&
                                (constraint.strOtherTable == ASqltable.strName) &&
                                constraint.strOtherFields.Contains(SequenceColumn))
                            {
                                tempSnippet.SetCodelet("TABLEROWTYPE", TTable.NiceTableName(ASqltable.strName) + "Row");
                                tempSnippet.SetCodelet("SEQUENCEDCOLUMNNAME", TTable.NiceFieldName(SequenceColumn));

                                ProcessTemplate updateSnippet = snippetDataset.GetSnippet("UPDATESEQUENCEINOTHERTABLES");
                                bool            canbeNull     =
                                    !table.GetField(constraint.strThisFields[constraint.strOtherFields.IndexOf(SequenceColumn)]).bNotNull;
                                updateSnippet.SetCodelet("TESTFORNULL", canbeNull ? "!otherRow.Is{#REFCOLUMNNAME}Null() && " : "");
                                updateSnippet.SetCodelet("REFERENCINGTABLEROWTYPE", TTable.NiceTableName(table.tablename) + "Row");
                                updateSnippet.SetCodelet("REFERENCINGTABLENAME", table.tablealias);
                                updateSnippet.SetCodelet("REFCOLUMNNAME",
                                                         TTable.NiceFieldName(constraint.strThisFields[constraint.strOtherFields.IndexOf(SequenceColumn)]));
                                updateSnippet.SetCodelet("SEQUENCEDCOLUMNNAME", TTable.NiceFieldName(SequenceColumn));

                                tempSnippet.InsertSnippet("UPDATESEQUENCEINOTHERTABLES", updateSnippet);
                            }
                        }
                    }
                }

                ASnippetSubmitChanges.InsertSnippet("SUBMITCHANGESINSERT", tempSnippet);

                ASnippetSubmitChanges.AddToCodelet("SUBMITCHANGESUPDATE", "");
            }
        }
        /// <summary>
        /// create the code for the definition of a typed table
        /// </summary>
        /// <param name="Template"></param>
        /// <param name="currentTable"></param>
        /// <param name="origTable"></param>
        /// <param name="WhereToInsert"></param>
        /// <param name="CalledFromDataSet"></param>
        public static void InsertTableDefinition(ProcessTemplate Template,
                                                 TTable currentTable,
                                                 TTable origTable,
                                                 string WhereToInsert,
                                                 Boolean CalledFromDataSet)
        {
            ProcessTemplate snippet      = Template.GetSnippet("TYPEDTABLE");
            string          derivedTable = "";

            if (origTable != null)
            {
                snippet.SetCodelet("BASECLASSTABLE", TTable.NiceTableName(currentTable.strName) + "Table");
                derivedTable = "new ";
                snippet.SetCodelet("TABLEID", origTable.iOrder.ToString());
            }
            else
            {
                snippet.SetCodelet("BASECLASSTABLE", "TTypedDataTable");
                snippet.SetCodelet("TABLEID", currentTable.iOrder.ToString());
            }

            snippet.SetCodelet("NEW", derivedTable);
            snippet.SetCodeletComment("TABLE_DESCRIPTION", currentTable.strDescription);
            snippet.SetCodelet("TABLENAME", currentTable.strDotNetName);

            if (CalledFromDataSet)
            {
                snippet.SetCodelet("TABLEINTDS", "TableInTDS");
            }
            else
            {
                snippet.SetCodelet("TABLEINTDS", "");
            }

            if (currentTable.AvailableForCustomReport)
            {
                snippet.SetCodelet("AVAILABLEFORCUSTOMREPORT", "true");
            }
            else
            {
                snippet.SetCodelet("AVAILABLEFORCUSTOMREPORT", "false");
            }

            snippet.SetCodelet("CUSTOMREPORTPERMISSION", currentTable.CustomReportPermission);

            if (currentTable.strVariableNameInDataset != null)
            {
                snippet.SetCodelet("TABLEVARIABLENAME", currentTable.strVariableNameInDataset);
            }
            else
            {
                snippet.SetCodelet("TABLEVARIABLENAME", currentTable.strDotNetName);
            }

            snippet.SetCodelet("DBTABLENAME", currentTable.strName);

            snippet.SetCodelet("DBTABLELABEL", currentTable.strLabel);

            if (currentTable.HasPrimaryKey())
            {
                TConstraint primKey           = currentTable.GetPrimaryKey();
                bool        first             = true;
                string      primaryKeyColumns = "";
                int         prevIndex         = -1;

                // the fields in the primary key should be used in the same order as in the table.
                // otherwise this is causing confusion. eg. a_processed_fee
                foreach (TTableField column in currentTable.grpTableField)
                {
                    int newIndex = -1;

                    if (primKey.strThisFields.Contains(column.strName))
                    {
                        newIndex = primKey.strThisFields.IndexOf(column.strName);
                    }
                    else if (primKey.strThisFields.Contains(TTable.NiceFieldName(column)))
                    {
                        newIndex = primKey.strThisFields.IndexOf(TTable.NiceFieldName(column));
                    }

                    if (newIndex != -1)
                    {
                        if (newIndex < prevIndex)
                        {
                            throw new Exception("Please fix the order of the fields in the primary key of table " + currentTable.strName);
                        }

                        prevIndex = newIndex;
                    }
                }

                // the fields in the primary key should be used in the same order as in the table.
                // otherwise this is causing confusion. eg. a_processed_fee
                foreach (TTableField column in currentTable.grpTableField)
                {
                    if (primKey.strThisFields.Contains(column.strName) || primKey.strThisFields.Contains(TTable.NiceFieldName(column)))
                    {
                        string columnName = column.strName;

                        string toAdd = currentTable.grpTableField.IndexOf(currentTable.GetField(columnName)).ToString();

                        if (!first)
                        {
                            toAdd              = ", " + toAdd;
                            primaryKeyColumns += ",";
                        }

                        first = false;

                        snippet.AddToCodelet("COLUMNPRIMARYKEYORDER", toAdd);
                        primaryKeyColumns += "Column" + TTable.NiceFieldName(currentTable.GetField(columnName));
                    }
                }

                if (primaryKeyColumns.Length > 0)
                {
                    snippet.SetCodelet("PRIMARYKEYCOLUMNS", primaryKeyColumns);
                    snippet.SetCodelet("PRIMARYKEYCOLUMNSCOUNT", primKey.strThisFields.Count.ToString());
                }
            }
            else
            {
                snippet.AddToCodelet("COLUMNPRIMARYKEYORDER", "");
            }

            if (currentTable.HasUniqueKey())
            {
                TConstraint primKey = currentTable.GetFirstUniqueKey();
                bool        first   = true;

                foreach (string columnName in primKey.strThisFields)
                {
                    string toAdd = currentTable.grpTableField.IndexOf(currentTable.GetField(columnName)).ToString();

                    if (!first)
                    {
                        toAdd = ", " + toAdd;
                    }

                    first = false;

                    snippet.AddToCodelet("COLUMNUNIQUEKEYORDER", toAdd);
                }
            }
            else
            {
                snippet.AddToCodelet("COLUMNUNIQUEKEYORDER", "");
            }

            int             colOrder = 0;
            Boolean         CustomReportFieldAdded = false;
            ProcessTemplate tempTemplate           = null;

            foreach (TTableField col in currentTable.grpTableField)
            {
                col.strTableName = currentTable.strName;
                string columnOverwrite       = "";
                bool   writeColumnProperties = true;

                if ((origTable != null) && (origTable.GetField(col.strName, false) != null))
                {
                    columnOverwrite = "new ";

                    if (origTable.GetField(col.strName).iOrder == colOrder)
                    {
                        // same order number, save some lines of code by not writing them
                        writeColumnProperties = false;
                    }
                }

                if (writeColumnProperties && (columnOverwrite.Length == 0))
                {
                    tempTemplate = Template.GetSnippet("DATACOLUMN");
                    tempTemplate.SetCodeletComment("COLUMN_DESCRIPTION", col.strDescription);
                    tempTemplate.SetCodelet("COLUMNNAME", TTable.NiceFieldName(col));
                    snippet.InsertSnippet("DATACOLUMNS", tempTemplate);
                }

                if (writeColumnProperties)
                {
                    tempTemplate = Template.GetSnippet("COLUMNIDS");
                    tempTemplate.SetCodelet("COLUMNNAME", TTable.NiceFieldName(col));
                    tempTemplate.SetCodelet("COLUMNORDERNUMBER", colOrder.ToString());
                    tempTemplate.SetCodelet("NEW", columnOverwrite);
                    snippet.InsertSnippet("COLUMNIDS", tempTemplate);
                }

                if (origTable == null)
                {
                    tempTemplate = Template.GetSnippet("COLUMNINFO");
                    tempTemplate.SetCodelet("COLUMNORDERNUMBER", colOrder.ToString());
                    tempTemplate.SetCodelet("COLUMNNAME", TTable.NiceFieldName(col));
                    tempTemplate.SetCodelet("COLUMNDBNAME", col.strName);
                    tempTemplate.SetCodelet("COLUMNLABEL", col.strLabel);
                    tempTemplate.SetCodelet("COLUMNODBCTYPE", CodeGenerationPetra.ToOdbcTypeString(col));
                    tempTemplate.SetCodelet("COLUMNLENGTH", col.iLength.ToString());
                    tempTemplate.SetCodelet("COLUMNNOTNULL", col.bNotNull.ToString().ToLower());
                    tempTemplate.SetCodelet("COLUMNCOMMA", colOrder + 1 < currentTable.grpTableField.Count ? "," : "");
                    snippet.InsertSnippet("COLUMNINFO", tempTemplate);
                }

                tempTemplate = Template.GetSnippet("INITCLASSADDCOLUMN");
                tempTemplate.SetCodelet("COLUMNDBNAME", col.strName);
                tempTemplate.SetCodelet("COLUMNDOTNETTYPE", col.GetDotNetType());
                tempTemplate.SetCodelet("COLUMNDOTNETTYPENOTNULLABLE", col.GetDotNetType().Replace("?", ""));
                snippet.InsertSnippet("INITCLASSADDCOLUMN", tempTemplate);

                tempTemplate = Template.GetSnippet("INITVARSCOLUMN");
                tempTemplate.SetCodelet("COLUMNDBNAME", col.strName);
                tempTemplate.SetCodelet("COLUMNNAME", TTable.NiceFieldName(col));
                snippet.InsertSnippet("INITVARSCOLUMN", tempTemplate);

                if (col.bAvailableForCustomReport)
                {
                    tempTemplate = Template.GetSnippet("INITVARSCUSTOMREPORTFIELDLIST");

                    if (CustomReportFieldAdded)
                    {
                        tempTemplate.SetCodelet("LISTDELIMITER", ",");
                    }
                    else
                    {
                        tempTemplate.SetCodelet("LISTDELIMITER", "");
                    }

                    tempTemplate.SetCodelet("COLUMNDBNAME", col.strName);

                    snippet.InsertSnippet("INITVARSCUSTOMREPORTFIELDLIST", tempTemplate);

                    CustomReportFieldAdded = true;
                }

                if (writeColumnProperties)
                {
                    tempTemplate = Template.GetSnippet("STATICCOLUMNPROPERTIES");
                    tempTemplate.SetCodelet("COLUMNDBNAME", col.strName);
                    tempTemplate.SetCodelet("COLUMNNAME", TTable.NiceFieldName(col));
                    tempTemplate.SetCodelet("COLUMNHELP", col.strHelp.Replace("\"", "\\\""));
                    tempTemplate.SetCodelet("COLUMNLENGTH", col.iLength.ToString());
                    tempTemplate.SetCodelet("NEW", columnOverwrite);
                    snippet.InsertSnippet("STATICCOLUMNPROPERTIES", tempTemplate);
                }

                colOrder++;
            }

            if (!CustomReportFieldAdded)
            {
                // fill snippet if nothing was added yet
                tempTemplate = Template.GetSnippet("INITVARSCUSTOMREPORTFIELDLISTEMPTY");
                tempTemplate.SetCodelet("EMPTY", "");
                snippet.InsertSnippet("INITVARSCUSTOMREPORTFIELDLIST", tempTemplate);
            }

            Template.InsertSnippet(WhereToInsert, snippet);
        }
        /// creates a file with enums in Shared and one file per submodule in Server for cached tables
        public static void WriteCachedTables(TDataDefinitionStore AStore,
                                             string ACacheYamlFilename,
                                             string ASharedPath,
                                             string ATemplateDir)
        {
            // Load yaml file with list of tables that should be cached
            TYml2Xml    ymlParser = new TYml2Xml(ACacheYamlFilename);
            XmlDocument xmlDoc    = ymlParser.ParseYML2XML();

            XmlNode module = xmlDoc.DocumentElement.FirstChild.FirstChild;

            while (module != null)
            {
                XmlNode subModule         = module.FirstChild;
                bool    severalSubModules = (subModule != null && subModule.NextSibling != null);

                // write the shared file with the enum definitions
                ProcessTemplate SharedTemplate = new ProcessTemplate(ATemplateDir + Path.DirectorySeparatorChar +
                                                                     "ORM" + Path.DirectorySeparatorChar +
                                                                     "Cacheable.Shared.cs");

                SharedTemplate.SetCodelet("GPLFILEHEADER", ProcessTemplate.LoadEmptyFileComment(ATemplateDir));
//                SharedTemplate.SetCodelet("NAMESPACE", "Ict.Petra.Shared.M" + module.Name);
                SharedTemplate.SetCodelet("NAMESPACE", "Ict.Petra.Shared");

                while (subModule != null)
                {
                    List <string> UsingNamespaces = new List <string>();

                    // write the server file for each submodule
                    ProcessTemplate ServerTemplate = new ProcessTemplate(ATemplateDir + Path.DirectorySeparatorChar +
                                                                         "ORM" + Path.DirectorySeparatorChar +
                                                                         "Cacheable.Server.cs");

                    ServerTemplate.SetCodelet("GPLFILEHEADER", ProcessTemplate.LoadEmptyFileComment(ATemplateDir));
                    ServerTemplate.SetCodelet("NAMESPACE", "Ict.Petra.Server.M" + module.Name + "." + subModule.Name + ".Cacheable");
                    ServerTemplate.SetCodelet("SUBNAMESPACE", "M" + module.Name + "." + subModule.Name);
                    ServerTemplate.SetCodelet("CACHEABLECLASS", "T" + module.Name + "Cacheable");
                    ServerTemplate.SetCodelet("SUBMODULE", subModule.Name);
                    ServerTemplate.SetCodelet("GETCALCULATEDLISTFROMDB", "");
                    ServerTemplate.SetCodelet("LEDGERGETCACHEABLE", "");
                    ServerTemplate.SetCodelet("LEDGERSAVECACHEABLE", "");

                    if (!severalSubModules)
                    {
                        // for MCommon
                        ServerTemplate.SetCodelet("NAMESPACE", "Ict.Petra.Server.M" + module.Name + ".Cacheable");
                        ServerTemplate.SetCodelet("SUBNAMESPACE", "M" + module.Name);
                        ServerTemplate.SetCodelet("CACHEABLECLASS", "TCacheable");
                    }

                    ProcessTemplate snippetSubmodule = SharedTemplate.GetSnippet("SUBMODULEENUM");
                    snippetSubmodule.SetCodelet("SUBMODULE", subModule.Name);
                    snippetSubmodule.SetCodelet("MODULE", module.Name);

                    ProcessTemplate snippetLedgerGetTable  = null;
                    ProcessTemplate snippetLedgerSaveTable = null;

                    XmlNode TableOrListElement = subModule.FirstChild;

                    while (TableOrListElement != null)
                    {
                        XmlNode enumElement = TableOrListElement.FirstChild;

                        while (enumElement != null)
                        {
                            bool DependsOnLedger = false;

                            if (TYml2Xml.GetAttributeRecursive(enumElement, "DependsOnLedger") == "true")
                            {
                                if (snippetLedgerGetTable == null)
                                {
                                    snippetLedgerGetTable = ServerTemplate.GetSnippet("LEDGERGETCACHEABLE");
                                    snippetLedgerGetTable.SetCodelet("SUBMODULE", subModule.Name);
                                }

                                if ((snippetLedgerSaveTable == null) && (TableOrListElement.Name == "DatabaseTables"))
                                {
                                    snippetLedgerSaveTable = ServerTemplate.GetSnippet("LEDGERSAVECACHEABLE");
                                    snippetLedgerSaveTable.SetCodelet("SUBMODULE", subModule.Name);
                                }

                                DependsOnLedger = true;

                                ServerTemplate.SetCodelet("WITHLEDGER", "true");
                            }

                            ProcessTemplate snippetElement = SharedTemplate.GetSnippet("ENUMELEMENT");

                            if ((enumElement.NextSibling == null) &&
                                ((TableOrListElement.NextSibling == null) || (TableOrListElement.NextSibling.FirstChild == null)))
                            {
                                snippetElement = SharedTemplate.GetSnippet("ENUMELEMENTLAST");
                            }

                            string Comment = TXMLParser.GetAttribute(enumElement, "Comment");

                            if (TableOrListElement.Name == "DatabaseTables")
                            {
                                TTable Table = AStore.GetTable(enumElement.Name);

                                string Namespace = "Ict.Petra.Shared." + TTable.GetNamespace(Table.strGroup) + ".Data";

                                if (!UsingNamespaces.Contains(Namespace))
                                {
                                    UsingNamespaces.Add(Namespace);
                                }

                                Namespace = "Ict.Petra.Server." + TTable.GetNamespace(Table.strGroup) + ".Validation";

                                if (!UsingNamespaces.Contains(Namespace))
                                {
                                    UsingNamespaces.Add(Namespace);
                                }

                                Namespace = "Ict.Petra.Server." + TTable.GetNamespace(Table.strGroup) + ".Data.Access";

                                if (!UsingNamespaces.Contains(Namespace))
                                {
                                    UsingNamespaces.Add(Namespace);
                                }

                                if (Table == null)
                                {
                                    throw new Exception("Error: cannot find table " + enumElement.Name + " for caching in module " + module.Name);
                                }

                                if (Comment.Length == 0)
                                {
                                    Comment = Table.strDescription;
                                }
                            }

                            if (Comment.Length == 0)
                            {
                                Comment = "todoComment";
                            }

                            snippetElement.SetCodelet("ENUMCOMMENT", Comment);

                            string enumName = enumElement.Name;

                            if (TXMLParser.HasAttribute(enumElement, "Enum"))
                            {
                                enumName = TXMLParser.GetAttribute(enumElement, "Enum");
                            }
                            else if (TableOrListElement.Name == "DatabaseTables")
                            {
                                string character2 = enumElement.Name.Substring(1, 1);

                                if (character2.ToLower() == character2)
                                {
                                    // this is a table name that has a 2 digit prefix
                                    enumName = enumElement.Name.Substring(2) + "List";
                                }
                                else
                                {
                                    enumName = enumElement.Name.Substring(1) + "List";
                                }
                            }

                            snippetElement.SetCodelet("ENUMNAME", enumName);
                            snippetElement.SetCodelet("DATATABLENAME", enumElement.Name);

                            snippetSubmodule.InsertSnippet("ENUMELEMENTS", snippetElement);

                            if (TableOrListElement.Name == "DatabaseTables")
                            {
                                ProcessTemplate snippetLoadTable = ServerTemplate.GetSnippet("LOADTABLE");

                                if (DependsOnLedger)
                                {
                                    snippetLoadTable = ServerTemplate.GetSnippet("LOADTABLEVIALEDGER");
                                }

                                snippetLoadTable.SetCodelet("ENUMNAME", enumName);
                                snippetLoadTable.SetCodelet("DATATABLENAME", enumElement.Name);

                                if (DependsOnLedger)
                                {
                                    snippetLedgerGetTable.InsertSnippet("LOADTABLESANDLISTS", snippetLoadTable);
                                }
                                else
                                {
                                    ServerTemplate.InsertSnippet("LOADTABLESANDLISTS", snippetLoadTable);
                                }

                                ProcessTemplate snippetSaveTable = ServerTemplate.GetSnippet("SAVETABLE");
                                snippetSaveTable.SetCodelet("ENUMNAME", enumName);
                                snippetSaveTable.SetCodelet("SUBMODULE", subModule.Name);
                                snippetSaveTable.SetCodelet("DATATABLENAME", enumElement.Name);

                                if (DependsOnLedger)
                                {
                                    snippetLedgerSaveTable.InsertSnippet("SAVETABLE", snippetSaveTable);
                                }
                                else
                                {
                                    ServerTemplate.InsertSnippet("SAVETABLE", snippetSaveTable);
                                }

                                ProcessTemplate snippetDataValidation = ServerTemplate.GetSnippet("DATAVALIDATION");
                                snippetDataValidation.SetCodelet("ENUMNAME", enumName);
                                snippetDataValidation.SetCodelet("DATATABLENAME", enumElement.Name);

                                if (DependsOnLedger)
                                {
                                    snippetLedgerSaveTable.InsertSnippet("DATAVALIDATION", snippetDataValidation);
                                }
                                else
                                {
                                    ServerTemplate.InsertSnippet("DATAVALIDATION", snippetDataValidation);
                                }
                            }
                            else
                            {
                                ProcessTemplate snippetLoadList = ServerTemplate.GetSnippet("LOADCALCULATEDLIST");

                                if (DependsOnLedger)
                                {
                                    snippetLoadList = ServerTemplate.GetSnippet("LOADCALCULATEDLISTFORLEDGER");
                                }

                                snippetLoadList.SetCodelet("ENUMNAME", enumName);
                                snippetLoadList.SetCodelet("CALCULATEDLISTNAME", enumName);

                                if (DependsOnLedger)
                                {
                                    snippetLedgerGetTable.InsertSnippet("LOADTABLESANDLISTS", snippetLoadList);
                                }
                                else
                                {
                                    ServerTemplate.InsertSnippet("LOADTABLESANDLISTS", snippetLoadList);
                                }

                                if (TYml2Xml.GetAttributeRecursive(enumElement, "IsStorableToDBTable") != String.Empty)
                                {
                                    ProcessTemplate snippetSaveTable = ServerTemplate.GetSnippet("SAVETABLE");
                                    snippetSaveTable.SetCodelet("ENUMNAME", enumName);
                                    snippetSaveTable.SetCodelet("SUBMODULE", subModule.Name);
                                    snippetSaveTable.SetCodelet("DATATABLENAME", TYml2Xml.GetAttributeRecursive(enumElement, "IsStorableToDBTable"));

                                    if (DependsOnLedger)
                                    {
                                        snippetLedgerSaveTable.InsertSnippet("SAVETABLE", snippetSaveTable);
                                    }
                                    else
                                    {
                                        ServerTemplate.InsertSnippet("SAVETABLE", snippetSaveTable);
                                    }

                                    ProcessTemplate snippetDataValidation = ServerTemplate.GetSnippet("DATAVALIDATION");
                                    snippetDataValidation.SetCodelet("ENUMNAME", enumName);
                                    snippetDataValidation.SetCodelet("DATATABLENAME",
                                                                     TYml2Xml.GetAttributeRecursive(enumElement, "IsStorableToDBTable"));

                                    if (DependsOnLedger)
                                    {
                                        snippetLedgerSaveTable.InsertSnippet("DATAVALIDATION", snippetDataValidation);
                                    }
                                    else
                                    {
                                        ServerTemplate.InsertSnippet("DATAVALIDATION", snippetDataValidation);
                                    }
                                }
                            }

                            enumElement = enumElement.NextSibling;

                            if (enumElement != null)
                            {
                                snippetSubmodule.AddToCodelet("ENUMELEMENTS", Environment.NewLine);
                            }
                        }

                        TableOrListElement = TableOrListElement.NextSibling;
                    }

                    SharedTemplate.InsertSnippet("ENUMS", snippetSubmodule);

                    if (snippetLedgerGetTable != null)
                    {
                        ServerTemplate.InsertSnippet("LEDGERGETCACHEABLE", snippetLedgerGetTable);
                    }

                    if (snippetLedgerSaveTable != null)
                    {
                        ServerTemplate.InsertSnippet("LEDGERSAVECACHEABLE", snippetLedgerSaveTable);
                    }

                    ServerTemplate.SetCodelet("USINGNAMESPACES", string.Empty);

                    foreach (string UsingNamespace in UsingNamespaces)
                    {
                        ServerTemplate.AddToCodelet("USINGNAMESPACES", "using " + UsingNamespace + ";" + Environment.NewLine);
                    }

                    string path = ASharedPath +
                                  Path.DirectorySeparatorChar + ".." +
                                  Path.DirectorySeparatorChar + "Server" +
                                  Path.DirectorySeparatorChar + "lib" +
                                  Path.DirectorySeparatorChar + "M" + module.Name +
                                  Path.DirectorySeparatorChar;

                    if (File.Exists(path + "Cacheable.ManualCode.cs"))
                    {
                        path += "Cacheable-generated.cs";
                    }
                    else
                    {
                        if (File.Exists(path + "data" + Path.DirectorySeparatorChar + subModule.Name + "." + "Cacheable.ManualCode.cs"))
                        {
                            path += "data" + Path.DirectorySeparatorChar + subModule.Name + "." + "Cacheable-generated.cs";
                        }
                        else if (File.Exists(path + "data" + Path.DirectorySeparatorChar + "Cacheable.ManualCode.cs"))
                        {
                            path += "data" + Path.DirectorySeparatorChar + "Cacheable-generated.cs";
                        }
                        else
                        {
                            path += subModule.Name + "." + "Cacheable-generated.cs";
                        }
                    }

                    ServerTemplate.FinishWriting(path, ".cs", true);

                    subModule = subModule.NextSibling;
                }

                SharedTemplate.FinishWriting(ASharedPath +
                                             Path.DirectorySeparatorChar + "M" + module.Name + ".Cacheable-generated.cs",
                                             ".cs", true);

                module = module.NextSibling;
            }
        }
Beispiel #30
0
        /// <summary>
        /// insert a method call
        /// </summary>
        private static void InsertMethodCall(ProcessTemplate snippet, TypeDeclaration connectorClass, MethodDeclaration m,
                                             ref List <string> AMethodNames)
        {
            string ParameterDefinition = string.Empty;
            string ActualParameters    = string.Empty;

            AutoGenerationTools.FormatParameters(m.Parameters, out ActualParameters, out ParameterDefinition);

            // for standalone: add actual parameters directly
            snippet.AddToCodelet("ACTUALPARAMETERS", ActualParameters);

            string returntype = AutoGenerationTools.TypeToString(m.TypeReference, "");

            if (!returntype.Contains("<"))
            {
                returntype = returntype == "string" || returntype == "String" ? "System.String" : returntype;
                returntype = returntype == "bool" || returntype == "Boolean" ? "System.Boolean" : returntype;

                if (returntype.Contains("UINT") || returntype.Contains("unsigned"))
                {
                    returntype = returntype.Contains("UInt32") || returntype == "unsigned int" ? "System.UInt32" : returntype;
                    returntype = returntype.Contains("UInt16") || returntype == "unsigned short" ? "System.UInt16" : returntype;
                    returntype = returntype.Contains("UInt64") || returntype == "unsigned long" ? "System.UInt64" : returntype;
                }
                else
                {
                    returntype = returntype.Contains("Int32") || returntype == "int" ? "System.Int32" : returntype;
                    returntype = returntype.Contains("Int16") || returntype == "short" ? "System.Int16" : returntype;
                    returntype = returntype.Contains("Int64") || returntype == "long" ? "System.Int64" : returntype;
                }

                returntype = returntype.Contains("Decimal") || returntype == "decimal" ? "System.Decimal" : returntype;
            }

            snippet.SetCodelet("RETURN", returntype != "void" ? "return " : string.Empty);

            // avoid duplicate names for webservice methods
            string methodname    = m.Name;
            int    methodcounter = 1;

            while (AMethodNames.Contains(methodname))
            {
                methodcounter++;
                methodname = m.Name + methodcounter.ToString();
            }

            AMethodNames.Add(methodname);

            snippet.SetCodelet("UNIQUEMETHODNAME", methodname);
            snippet.SetCodelet("METHODNAME", m.Name);
            snippet.SetCodelet("PARAMETERDEFINITION", ParameterDefinition);
            snippet.SetCodelet("RETURNTYPE", returntype);
            snippet.SetCodelet("WEBCONNECTORCLASS", connectorClass.Name);
            snippet.SetCodelet("ASSIGNRESULTANDRETURN", string.Empty);
            snippet.SetCodelet("ADDACTUALPARAMETERS", string.Empty);

            int ResultCounter = 0;

            if (CheckServerAdminToken(m))
            {
                snippet.AddToCodelet("ADDACTUALPARAMETERS",
                                     "ActualParameters.Add(\"AServerAdminSecurityToken\", THttpConnector.ServerAdminSecurityToken" +
                                     ");" + Environment.NewLine);
            }

            foreach (ParameterDeclarationExpression p in m.Parameters)
            {
                if (((ParameterModifiers.Ref & p.ParamModifier) > 0) || ((ParameterModifiers.Out & p.ParamModifier) > 0))
                {
                    // need to assign the result to the ref and the out parameter
                    snippet.AddToCodelet("ASSIGNRESULTANDRETURN",
                                         p.ParameterName + " = (" + p.TypeReference.ToString() + ") Result[" + ResultCounter.ToString() + "];" +
                                         Environment.NewLine);
                    ResultCounter++;
                }

                if ((ParameterModifiers.Out & p.ParamModifier) == 0)
                {
                    snippet.AddToCodelet("ADDACTUALPARAMETERS",
                                         "ActualParameters.Add(\"" + p.ParameterName + "\", " +
                                         p.ParameterName + ");" + Environment.NewLine);
                }
            }

            string expectedreturntype = GetExpectedReturnType(ResultCounter, returntype);

            snippet.SetCodelet("EXPECTEDRETURNTYPE", expectedreturntype);
            snippet.SetCodelet("RESULT", string.Empty);

            if ((returntype != "void") || (ResultCounter > 0))
            {
                snippet.SetCodelet("RESULT", "List<object> Result = ");
            }

            if (returntype != "void")
            {
                snippet.AddToCodelet("ASSIGNRESULTANDRETURN",
                                     "return (" + returntype + ") Result[" + ResultCounter.ToString() + "];" + Environment.NewLine);
            }
        }