Exemplo n.º 1
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;

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

            Template.AddToCodelet("DBTableNames", namesCodelet);

            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);
        }
Exemplo n.º 2
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);
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// insert a method call
        /// </summary>
        private static void InsertWebConnectorMethodCall(ProcessTemplate snippet,
            TypeDeclaration connectorClass,
            MethodDeclaration m,
            ref List <string>AMethodNames)
        {
            PrepareParametersForMethod(snippet, m.TypeReference, m.Parameters, m.Name, ref AMethodNames);

            snippet.SetCodelet("METHODNAME", m.Name);
            snippet.SetCodelet("WEBCONNECTORCLASS", connectorClass.Name);
            snippet.InsertSnippet("CHECKUSERMODULEPERMISSIONS",
                CreateModuleAccessPermissionCheck(
                    snippet,
                    connectorClass.Name,
                    m));
        }
Exemplo n.º 4
0
    private void CreateAutoHierarchy(TNamespace tn, String AOutputPath)
    {
        String OutputFile = AOutputPath + Path.DirectorySeparatorChar + "M" + tn.Name +
                            Path.DirectorySeparatorChar + "Instantiator.AutoHierarchy-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.AutoHierarchy-generated.cs";
        }

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

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

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

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

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

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

        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));

        ProcessTemplate topLevelNamespaceSnippet = Template.GetSnippet("TOPLEVELNAMESPACE");
        topLevelNamespaceSnippet.SetCodelet("SUBNAMESPACEREMOTABLECLASSES", "");
        topLevelNamespaceSnippet.SetCodelet("TOPLEVELMODULE", tn.Name);
        topLevelNamespaceSnippet.InsertSnippet("LOADERCLASS", WriteLoaderClass(Template, tn.Name));
        topLevelNamespaceSnippet.InsertSnippet("MAINREMOTABLECLASS",
            WriteRemotableClass(
                topLevelNamespaceSnippet,
                "Ict.Petra.Shared.M" + tn.Name,
                "TM" + tn.Name,
                "M" + tn.Name,
                true,
                tn.Children,
                connectors));

        foreach (TNamespace sn in tn.Children.Values)
        {
            topLevelNamespaceSnippet.InsertSnippet("SUBNAMESPACEREMOTABLECLASSES",
                WriteRemotableClass(
                    topLevelNamespaceSnippet,
                    "Ict.Petra.Shared.M" + tn.Name + "." + sn.Name,
                    sn.Name,
                    sn.Name,
                    false,
                    sn.Children,
                    connectors));
        }

        Template.InsertSnippet("CONTENT", topLevelNamespaceSnippet);

        Template.FinishWriting(OutputFile, ".cs", true);
    }
Exemplo n.º 5
0
        private static void LayoutCellInForm(TControlDef ACtrl,
            Int32 AChildrenCount,
            ProcessTemplate ACtrlSnippet,
            ProcessTemplate ASnippetCellDefinition)
        {
            if (ACtrl.HasAttribute("labelWidth"))
            {
                ASnippetCellDefinition.SetCodelet("LABELWIDTH", ACtrl.GetAttribute("labelWidth"));
            }

            if (ACtrl.HasAttribute("columnWidth"))
            {
                ASnippetCellDefinition.SetCodelet("COLUMNWIDTH", ACtrl.GetAttribute("columnWidth").Replace(",", "."));
            }
            else
            {
                ASnippetCellDefinition.SetCodelet("COLUMNWIDTH", (1.0 / AChildrenCount).ToString().Replace(",", "."));
            }

            string Anchor = ANCHOR_DEFAULT_COLUMN;

            if (AChildrenCount == 1)
            {
                Anchor = ANCHOR_SINGLE_COLUMN;
            }

            if (ACtrl.HasAttribute("columnWidth"))
            {
                Anchor = "94%";
            }

            if (ACtrl.GetAttribute("hideLabel") == "true")
            {
                ACtrlSnippet.SetCodelet("HIDELABEL", "true");
                Anchor = ANCHOR_HIDDEN_LABEL;
            }

            ACtrlSnippet.SetCodelet("ANCHOR", Anchor);
        }
Exemplo n.º 6
0
        /// based on the code model, create the code;
        /// using the code generators that have been loaded
        public override void CreateCode(TCodeStorage ACodeStorage, string AXAMLFilename, string ATemplateFile)
        {
            ResetAllValues();
            FCodeStorage = ACodeStorage;
            TControlGenerator.FCodeStorage = ACodeStorage;
            FTemplate = new ProcessTemplate(ATemplateFile);

            // load default header with license and copyright
            string templateDir = TAppSettingsManager.GetValue("TemplateDir", true);
            FTemplate.AddToCodelet("GPLFILEHEADER",
                ProcessTemplate.LoadEmptyFileComment(templateDir + Path.DirectorySeparatorChar + ".." +
                    Path.DirectorySeparatorChar));

            // init some template variables that can be empty
            FTemplate.AddToCodelet("INITUSERCONTROLS", "");
            FTemplate.AddToCodelet("INITMANUALCODE", "");
            FTemplate.AddToCodelet("GRIDMULTISELECTION", "");
            FTemplate.AddToCodelet("GRIDHEADERTOOLTIP", "");
            FTemplate.AddToCodelet("RUNONCEONACTIVATIONMANUAL", "");
            FTemplate.AddToCodelet("RUNONCEONPARENTACTIVATIONMANUAL", "");
            FTemplate.AddToCodelet("USERCONTROLSRUNONCEONACTIVATION", "");
            FTemplate.AddToCodelet("SETINITIALFOCUS", "");
            FTemplate.AddToCodelet("EXITMANUALCODE", "");
            FTemplate.AddToCodelet("CANCLOSEMANUAL", "");
            FTemplate.AddToCodelet("INITNEWROWMANUAL", "");
            FTemplate.AddToCodelet("DELETERECORD", "");
            FTemplate.AddToCodelet("DELETEREFERENCECOUNT", "");
            FTemplate.AddToCodelet("MULTIDELETEREFERENCECOUNT", "");
            FTemplate.AddToCodelet("ENABLEDELETEBUTTON", "");
            FTemplate.AddToCodelet("CANDELETESELECTION", "");
            FTemplate.AddToCodelet("CANDELETEROW", "");
            FTemplate.AddToCodelet("SELECTTABMANUAL", "");
            FTemplate.AddToCodelet("STOREMANUALCODE", "");
            FTemplate.AddToCodelet("FINDANDFILTERHOOKUPEVENTS", "");
            FTemplate.AddToCodelet("ACTIONENABLINGDISABLEMISSINGFUNCS", "");
            FTemplate.AddToCodelet("PRIMARYKEYCONTROLSREADONLY", "");
            FTemplate.AddToCodelet("SHOWDETAILSMANUAL", "");
            FTemplate.AddToCodelet("PREPROCESSCMDKEY", "");
            FTemplate.AddToCodelet("PROCESSCMDKEY", "");
            FTemplate.AddToCodelet("PROCESSCMDKEYCTRLF", "");
            FTemplate.AddToCodelet("PROCESSCMDKEYCTRLR", "");
            FTemplate.AddToCodelet("PROCESSCMDKEYMANUAL", "");
            FTemplate.AddToCodelet("FOCUSFIRSTEDITABLEDETAILSPANELCONTROL", "");
            FTemplate.AddToCodelet("CLEARDETAILS", "");
            FTemplate.AddToCodelet("CATALOGI18N", "");
            FTemplate.AddToCodelet("DYNAMICTABPAGEUSERCONTROLENUM", "");
            FTemplate.AddToCodelet("DYNAMICTABPAGEUSERCONTROLINITIALISATION", "");
            FTemplate.AddToCodelet("DYNAMICTABPAGEUSERCONTROLLOADING", "");
            FTemplate.AddToCodelet("ASSIGNFONTATTRIBUTES", "");
            FTemplate.AddToCodelet("CUSTOMDISPOSING", "");
            FTemplate.AddToCodelet("DYNAMICTABPAGEUSERCONTROLDECLARATION", "");
            FTemplate.AddToCodelet("DYNAMICTABPAGEBASICS", "");
            FTemplate.AddToCodelet("IGNOREFIRSTTABPAGESELECTIONCHANGEDEVENT", "");
            FTemplate.AddToCodelet("DYNAMICTABPAGEUSERCONTROLSETUPMETHODS", "");
            FTemplate.AddToCodelet("ELSESTATEMENT", "");
//          FTemplate.AddToCodelet("VALIDATEDETAILS", "");


            FTemplate.AddToCodelet("INITACTIONSTATE", "FPetraUtilsObject.InitActionState();" + Environment.NewLine);

            CallHandlerIfProvided("void BeforeShowDetailsManual", "SHOWDETAILS", "BeforeShowDetailsManual(ARow);");
            CallHandlerIfProvided("InitializeManualCode", "INITMANUALCODE", "InitializeManualCode();");
            CallHandlerIfProvided("RunOnceOnActivationManual", "RUNONCEONACTIVATIONMANUAL", "RunOnceOnActivationManual();");
            CallHandlerIfProvided("RunOnceOnParentActivationManual", "RUNONCEONPARENTACTIVATIONMANUAL", "RunOnceOnParentActivationManual();");
            CallHandlerIfProvided("ExitManualCode", "EXITMANUALCODE", "ExitManualCode();");
            CallHandlerIfProvided("CanCloseManual", "CANCLOSEMANUAL", " && CanCloseManual()");
            CallHandlerIfProvided("NewRowManual", "INITNEWROWMANUAL", "NewRowManual(ref NewRow);");
            CallHandlerIfProvided("StoreManualCode", "STOREMANUALCODE", "SubmissionResult = StoreManualCode(ref SubmitDS, out VerificationResult);");
            CallHandlerIfProvided("FindAndFilterHookUpEvents", "FINDANDFILTERHOOKUPEVENTS", "FindAndFilterHookUpEvents();");
            CallHandlerIfProvided("PreProcessCommandKey", "PREPROCESSCMDKEY", "PreProcessCommandKey();");

            if (FCodeStorage.ManualFileExistsAndContains("SelectTabManual"))
            {
                FTemplate.AddToCodelet("SELECTTABMANUAL",
                    "//Call code to execute on selection of new tab" + Environment.NewLine);
            }

            if (FCodeStorage.ManualFileExistsAndContains("PreDeleteManual"))
            {
                FTemplate.AddToCodelet("HASPREDELETEMANUAL", "true");
            }

            if (FCodeStorage.ManualFileExistsAndContains("DeleteRowManual"))
            {
                FTemplate.AddToCodelet("HASDELETEROWMANUAL", "true");
            }

            if (FCodeStorage.ManualFileExistsAndContains("PostDeleteManual"))
            {
                FTemplate.AddToCodelet("HASPOSTDELETEMANUAL", "true");
            }

            if (FCodeStorage.ManualFileExistsAndContains("GetChangedRecordCountManual"))
            {
                FTemplate.AddToCodelet("GETCHANGEDRECORDCOUNT", "return GetChangedRecordCountManual(out AMessage);");
            }
            else
            {
                FTemplate.AddToCodelet("GETCHANGEDRECORDCOUNT", "return FPetraUtilsObject.GetChangedRecordCount(FMainDS, out AMessage);");
            }

            if (FTemplate.FSnippets.ContainsKey("PROCESSCMDKEYCTRLL"))
            {
                if (FCodeStorage.FControlList.ContainsKey("grdDetails") && !FCodeStorage.FControlList["grdDetails"].HasAttribute("IgnoreEditMove]"))
                {
                    ProcessTemplate snipCtrlL = FTemplate.GetSnippet("PROCESSCMDKEYCTRLL");
                    FTemplate.InsertSnippet("PROCESSCMDKEY", snipCtrlL);

                    if (FCodeStorage.FControlList.ContainsKey("pnlDetails"))
                    {
                        ProcessTemplate snipCtrlE = FTemplate.GetSnippet("PROCESSCMDKEYCTRLE");
                        FTemplate.InsertSnippet("PROCESSCMDKEY", snipCtrlE);

                        ProcessTemplate snipSelectRow = FTemplate.GetSnippet("PROCESSCMDKEYSELECTROW");
                        FTemplate.InsertSnippet("PROCESSCMDKEY", snipSelectRow);

                        if (FCodeStorage.ManualFileExistsAndContains("void FocusFirstEditableControlManual()"))
                        {
                            FTemplate.SetCodelet("FOCUSFIRSTEDITABLEDETAILSPANELCONTROL", "FocusFirstEditableControlManual();" + Environment.NewLine);
                        }
                        else
                        {
                            ProcessTemplate snipFocusFirstControl = FTemplate.GetSnippet("FOCUSFIRSTDETAILSPANELCONTROL");
                            FTemplate.InsertSnippet("FOCUSFIRSTEDITABLEDETAILSPANELCONTROL", snipFocusFirstControl);
                        }
                    }
                }

                if (FCodeStorage.ManualFileExistsAndContains("ProcessCmdKeyManual(ref"))
                {
                    ProcessTemplate snipCmdKeyManual = FTemplate.GetSnippet("PROCESSCMDKEYMANUAL");
                    FTemplate.InsertSnippet("PROCESSCMDKEYMANUAL", snipCmdKeyManual);
                }
            }

            if ((FTemplate.FSnippets.ContainsKey("PROCESSCMDKEYCTRLF")) && (FCodeStorage.FControlList.ContainsKey("pnlFilterAndFind")))
            {
                ProcessTemplate snipCtrlF = FTemplate.GetSnippet("PROCESSCMDKEYCTRLF");

                if (FCodeStorage.FActionList.ContainsKey("actEditFind"))
                {
                    snipCtrlF.SetCodelet("ACTIONCLICK", FCodeStorage.FActionList["actEditFind"].actionClick);
                }
                else
                {
                    snipCtrlF.SetCodelet("ACTIONCLICK", "MniFilterFind_Click");
                }

                FTemplate.InsertSnippet("PROCESSCMDKEY", snipCtrlF);
            }

            if ((FTemplate.FSnippets.ContainsKey("PROCESSCMDKEYCTRLR")) && (FCodeStorage.FControlList.ContainsKey("pnlFilterAndFind")))
            {
                ProcessTemplate snipCtrlR = FTemplate.GetSnippet("PROCESSCMDKEYCTRLR");

                if (FCodeStorage.FActionList.ContainsKey("actEditFilter"))
                {
                    snipCtrlR.SetCodelet("ACTIONCLICK", FCodeStorage.FActionList["actEditFilter"].actionClick);
                }
                else
                {
                    snipCtrlR.SetCodelet("ACTIONCLICK", "MniFilterFind_Click");
                }

                FTemplate.InsertSnippet("PROCESSCMDKEY", snipCtrlR);
            }

            if (FCodeStorage.HasAttribute("DatasetType"))
            {
                FTemplate.SetCodelet("DATASETTYPE", FCodeStorage.GetAttribute("DatasetType"));
                FTemplate.SetCodelet("SHORTDATASETTYPE",
                    FCodeStorage.GetAttribute("DatasetType").Substring(FCodeStorage.GetAttribute("DatasetType").LastIndexOf(".") + 1));
                FTemplate.SetCodelet("MANAGEDDATASETORTYPE", "true");
            }
            else
            {
                FTemplate.SetCodelet("DATASETTYPE", String.Empty);
            }

//    FTemplate.SetCodelet("MANAGEDDATASETORTYPE", "true");

            XmlNode UsingNamespacesNode = TYml2Xml.GetChild(FCodeStorage.FRootNode, "UsingNamespaces");

            if (UsingNamespacesNode != null)
            {
                foreach (string s in TYml2Xml.GetElements(FCodeStorage.FRootNode, "UsingNamespaces"))
                {
                    FTemplate.AddToCodelet("USINGNAMESPACES", "using " + s + ";" + Environment.NewLine);
                }
            }
            else
            {
                FTemplate.AddToCodelet("USINGNAMESPACES", "");
            }

            SortedList <string, TTable>DataSetTables = null;

            // load the dataset if there is a dataset defined for this screen. this allows us to reference customtables and custom fields
            if (FCodeStorage.HasAttribute("DatasetType"))
            {
                DataSetTables = TDataBinding.LoadDatasetTables(CSParser.ICTPath, FCodeStorage.GetAttribute("DatasetType"), FCodeStorage);
            }
            else
            {
                TDataBinding.FCodeStorage = FCodeStorage;
                TDataBinding.ResetCurrentDataset();
            }

            if (FCodeStorage.HasAttribute("MasterTable"))
            {
                if ((DataSetTables != null) && DataSetTables.ContainsKey(FCodeStorage.GetAttribute("MasterTable")))
                {
                    TTable table = DataSetTables[FCodeStorage.GetAttribute("MasterTable")];
                    FTemplate.AddToCodelet("MASTERTABLE", table.strVariableNameInDataset);
                    FTemplate.AddToCodelet("MASTERTABLETYPE", table.strDotNetName);
                    FTemplate.SetCodelet("SHAREDVALIDATIONNAMESPACEMODULE",
                        String.Format("Ict.Petra.Shared.{0}.Validation",
                            TTable.GetNamespace(table.strGroup)));
                }
                else
                {
                    FTemplate.AddToCodelet("MASTERTABLE", FCodeStorage.GetAttribute("MasterTable"));

                    TTable table = TDataBinding.FPetraXMLStore.GetTable(FCodeStorage.GetAttribute("MasterTable"));
                    FTemplate.SetCodelet("SHAREDVALIDATIONNAMESPACEMODULE",
                        String.Format("Ict.Petra.Shared.{0}.Validation",
                            TTable.GetNamespace(table.strGroup)));

                    if (FCodeStorage.HasAttribute("MasterTableType"))
                    {
                        FTemplate.AddToCodelet("MASTERTABLETYPE", FCodeStorage.GetAttribute("MasterTableType"));
                    }
                    else
                    {
                        FTemplate.AddToCodelet("MASTERTABLETYPE", FCodeStorage.GetAttribute("MasterTable"));
                    }
                }
            }
            else
            {
                FTemplate.AddToCodelet("MASTERTABLE", "");
                FTemplate.AddToCodelet("MASTERTABLETYPE", "");
            }

            if (FCodeStorage.HasAttribute("DetailTable"))
            {
                string detailTable;

                if ((DataSetTables != null) && DataSetTables.ContainsKey(FCodeStorage.GetAttribute("DetailTable")))
                {
                    TTable table = DataSetTables[FCodeStorage.GetAttribute("DetailTable")];

                    if (table == null)
                    {
                        throw new Exception("invalid DetailTable, does not exist: " + FCodeStorage.GetAttribute("DetailTable"));
                    }

                    FTemplate.SetCodelet("SHAREDVALIDATIONNAMESPACEMODULE",
                        String.Format("Ict.Petra.Shared.{0}.Validation",
                            TTable.GetNamespace(table.strGroup)));

                    detailTable = table.strVariableNameInDataset;
                    FTemplate.AddToCodelet("DETAILTABLE", detailTable);
                    FTemplate.AddToCodelet("DETAILTABLETYPE", table.strDotNetName);
                }
                else
                {
                    detailTable = FCodeStorage.GetAttribute("DetailTable");
                    FTemplate.AddToCodelet("DETAILTABLE", detailTable);
                    FTemplate.AddToCodelet("DETAILTABLETYPE", detailTable);

                    TTable table = TDataBinding.FPetraXMLStore.GetTable(detailTable);
                    FTemplate.SetCodelet("SHAREDVALIDATIONNAMESPACEMODULE",
                        String.Format("Ict.Petra.Shared.{0}.Validation",
                            TTable.GetNamespace(table.strGroup)));
                }

                if ((FTemplate.FSnippets.Keys.Contains("INLINETYPEDDATASET"))
                    && (!FCodeStorage.HasAttribute("DatasetType")))
                {
                    ProcessTemplate inlineTypedDataSetSnippet = FTemplate.GetSnippet("INLINETYPEDDATASET");
                    inlineTypedDataSetSnippet.SetCodelet("DETAILTABLE", detailTable);

                    FTemplate.InsertSnippet("INLINETYPEDDATASET", inlineTypedDataSetSnippet);
                }
            }
            else
            {
                FTemplate.AddToCodelet("DETAILTABLE", "");
                FTemplate.AddToCodelet("DETAILTABLETYPE", "");
            }

            if (FCodeStorage.HasAttribute("TempTableName"))
            {
                FTemplate.AddToCodelet("TEMPTABLENAME", FCodeStorage.GetAttribute("TempTableName"));
            }

            if (FCodeStorage.HasAttribute("CacheableTable"))
            {
                FTemplate.AddToCodelet("CACHEABLETABLE", "\"" + FCodeStorage.GetAttribute("CacheableTable") + "\"");

                if (FCodeStorage.HasAttribute("CacheableTableSpecificFilter"))
                {
                    FTemplate.AddToCodelet("FILTERVAR", "object FFilter;");

                    string CacheableTableSpecificFilter = FCodeStorage.GetAttribute("CacheableTableSpecificFilter");

                    if (CacheableTableSpecificFilter.StartsWith("\""))
                    {
                        FTemplate.AddToCodelet("LOADDATAONCONSTRUCTORRUN", "LoadDataAndFinishScreenSetup();");
                        FTemplate.AddToCodelet("CACHEABLETABLERETRIEVEMETHOD", "GetCacheableDataTableFromCache");
                        FTemplate.AddToCodelet("DISPLAYFILTERINFORMTITLE", "this.Text = this.Text + \"   [Filtered]\";");
                        FTemplate.AddToCodelet("CACHEABLETABLESPECIFICFILTERLOAD", "" + CacheableTableSpecificFilter + ", FFilter");
                        FTemplate.AddToCodelet("CACHEABLETABLESPECIFICFILTERSAVE", ", " + CacheableTableSpecificFilter + ", FFilter");
                    }
                    else
                    {
                        FTemplate.AddToCodelet("LOADDATAONCONSTRUCTORRUN",
                            "// LoadDataAndFinishScreenSetup() needs to be called manually after setting FFilter!");
                        FTemplate.AddToCodelet("CACHEABLETABLERETRIEVEMETHOD", "GetSpecificallyFilteredCacheableDataTableFromCache");
                        FTemplate.AddToCodelet("DISPLAYFILTERINFORMTITLE",
                            "this.Text = this.Text + \"   [" + CacheableTableSpecificFilter + " = \" + FFilter.ToString() + \"]\";");
                        FTemplate.AddToCodelet("CACHEABLETABLESPECIFICFILTERLOAD", "\"" + CacheableTableSpecificFilter + "\", FFilter");
                        FTemplate.AddToCodelet("CACHEABLETABLESPECIFICFILTERSAVE", ", FFilter");
                    }

                    FTemplate.AddToCodelet("CACHEABLETABLESAVEMETHOD", "SaveSpecificallyFilteredCacheableDataTableToPetraServer");
                    //FTemplate.AddToCodelet("CACHEABLETABLESPECIFICFILTERSAVE", "FFilter, out VerificationResult");
                }
                else
                {
                    FTemplate.AddToCodelet("FILTERVAR", "");
                    FTemplate.AddToCodelet("DISPLAYFILTERINFORMTITLE", "");
                    FTemplate.AddToCodelet("LOADDATAONCONSTRUCTORRUN", "LoadDataAndFinishScreenSetup();");
                    FTemplate.AddToCodelet("CACHEABLETABLERETRIEVEMETHOD", "GetCacheableDataTableFromCache");
                    FTemplate.AddToCodelet("CACHEABLETABLESPECIFICFILTERLOAD", "String.Empty, null");
                    FTemplate.AddToCodelet("CACHEABLETABLESPECIFICFILTERSAVE", "");
                    FTemplate.AddToCodelet("CACHEABLETABLESAVEMETHOD", "SaveChangedCacheableDataTableToPetraServer");
                    //FTemplate.AddToCodelet("CACHEABLETABLESPECIFICFILTERSAVE", "out VerificationResult");
                }
            }

            if (FCodeStorage.HasAttribute("GenerateGetSelectedDetailRow")
                && (FCodeStorage.GetAttribute("GenerateGetSelectedDetailRow") == "true"))
            {
                FTemplate.AddToCodelet("GENERATEGETSELECTEDDETAILROW", "true");
            }

            if (FCodeStorage.HasAttribute("MultipleMasterRows")
                && (FCodeStorage.GetAttribute("MultipleMasterRows") == "true"))
            {
                FTemplate.AddToCodelet("MULTIPLEMASTERROWS", "true");
            }

            // Note - this IF clause needs to be the same as the one in generateReferenceCountConnectors.cs which is generating the server side code
            // Do Ctrl+F to find: this IF clause needs to be the same
            // in that file
            if ((FCodeStorage.GetAttribute("DetailTable") != String.Empty)
                && (FCodeStorage.FControlList.ContainsKey("btnDelete")
                    || FCodeStorage.FControlList.ContainsKey("btnDeleteType")
                    || FCodeStorage.FControlList.ContainsKey("btnDeleteExtract")
                    || FCodeStorage.FControlList.ContainsKey("btnDeleteDetail")
                    || (FCodeStorage.FControlList.ContainsKey("btnRemoveDetail") && (FCodeStorage.GetAttribute("FormType") != "report"))))
            {
                // We always auto-generate code to calculate the record reference count when a delete button exists unless specified in YAML
                if (TYml2Xml.GetAttribute((XmlNode)FCodeStorage.FXmlNodes["actDelete"], "SkipReferenceCheck").ToLower() != "true")
                {
                    AddDeleteReferenceCountImplementation();
                }

                // The generated code only writes the delete button event handler if there is a delete button and there is no manual code to handle the event
                if ((FCodeStorage.FActionList.ContainsKey("actDelete") && (FCodeStorage.FActionList["actDelete"].actionClick != "DeleteRecord"))
                    || FCodeStorage.ManualFileExistsAndContains("btnDelete.Click +=")
                    || FCodeStorage.ManualFileExistsAndContains("void DeleteRecord(")
                    || FCodeStorage.ManualFileExistsAndContains("void DeleteDetail(")
                    || FCodeStorage.ManualFileExistsAndContains("void DeleteRow(")
                    || FCodeStorage.ManualFileExistsAndContains("void RemoveDetail("))
                {
                    // Handled by manual code
                    Console.WriteLine("Skipping DeleteRecord() handler because it is handled by " +
                        Path.GetFileNameWithoutExtension(FCodeStorage.FManualCodeFilename));
                }
                else
                {
                    // Write the event handler to call the DeleteTableName() method
                    string deleteRecord = String.Format(
                        "{1}{0}private void DeleteRecord(Object sender, EventArgs e){1}{0}{{{1}{0}{0}Delete{2}();{1}{0}}}{1}{1}",
                        "    ",
                        Environment.NewLine,
                        FCodeStorage.GetAttribute("DetailTable"));
                    FTemplate.AddToCodelet("DELETERECORD", deleteRecord);

                    ProcessTemplate snippetCanDelete = FTemplate.GetSnippet("SNIPCANDELETESELECTION");
                    ProcessTemplate snippetCanDeleteRow = FTemplate.GetSnippet("SNIPCANDELETEROW");
                    bool bRequiresCanDeleteSelection = false;

                    // Write the one-line codelet that handles enable/disable of the delete button
                    string enableDelete = "btnDelete.Enabled = pnlDetails.Enabled";
                    string enableDeleteExtra = " && CanDeleteSelection()";

                    if (FCodeStorage.FControlList.ContainsKey("chkDetailDeletable")
                        || FCodeStorage.FControlList.ContainsKey("chkDeletable"))
                    {
                        enableDelete += enableDeleteExtra;
                        snippetCanDelete.SetCodelet("DELETEABLEFLAG", "Deletable");
                        snippetCanDeleteRow.SetCodelet("DELETEABLEFLAG", "Deletable");
                        bRequiresCanDeleteSelection = true;
                    }
                    else if (FCodeStorage.FControlList.ContainsKey("chkDetailDeletableFlag")
                             || FCodeStorage.FControlList.ContainsKey("chkDeletableFlag"))
                    {
                        enableDelete += enableDeleteExtra;
                        snippetCanDelete.SetCodelet("DELETEABLEFLAG", "DeletableFlag");
                        snippetCanDeleteRow.SetCodelet("DELETEABLEFLAG", "DeletableFlag");
                        bRequiresCanDeleteSelection = true;
                    }
                    else if (FCodeStorage.FControlList.ContainsKey("chkDetailTypeDeletable"))
                    {
                        enableDelete += enableDeleteExtra;
                        snippetCanDelete.SetCodelet("DELETEABLEFLAG", "TypeDeletable");
                        snippetCanDeleteRow.SetCodelet("DELETEABLEFLAG", "TypeDeletable");
                        bRequiresCanDeleteSelection = true;
                    }

                    enableDelete += ";" + Environment.NewLine;
                    FTemplate.AddToCodelet("ENABLEDELETEBUTTON", enableDelete);

                    if (bRequiresCanDeleteSelection)
                    {
                        snippetCanDelete.SetCodelet("DETAILTABLE", FCodeStorage.GetAttribute("DetailTable"));
                        FTemplate.InsertSnippet("CANDELETESELECTION", snippetCanDelete);
                        snippetCanDeleteRow.SetCodelet("DETAILTABLE", FCodeStorage.GetAttribute("DetailTable"));
                        FTemplate.InsertSnippet("CANDELETEROW", snippetCanDeleteRow);
                    }
                }
            }

            if (FTemplate.FCodelets["CANDELETEROW"].ToString() == String.Empty)
            {
                FTemplate.SetCodelet("CANDELETEROW", "return true;");
            }

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

            // Toolbar
            if (FCodeStorage.HasRootControl("tbr"))
            {
                AddRootControl("tbr");
            }

            // Main Menu
            if (FCodeStorage.HasRootControl("mnu"))
            {
                AddRootControl("mnu");
            }

            // Statusbar
            if (FCodeStorage.HasRootControl("stb"))
            {
                AddRootControl("stb");
            }

            // check for controls that have no parent
            List <TControlDef>orphans = FCodeStorage.GetOrphanedControls();

            if (orphans.Count > 0)
            {
                string msg = String.Empty;

                foreach (TControlDef o in orphans)
                {
                    msg += o.controlName + " ";
                }

                TLogging.Log("Warning !!! There are some controls that will not be part of the screen (missing parent control?): " + msg);
            }

            // add form events
            foreach (TEventHandler handler in FCodeStorage.FEventList.Values)
            {
                SetEventHandlerForForm(handler);
            }

            foreach (TReportParameter ReportPara in FCodeStorage.FReportParameterList.Values)
            {
                AddReportParameterImplementaion(ReportPara);
            }

            XmlNode rootNode = (XmlNode)FCodeStorage.FXmlNodes[TParseYAMLFormsDefinition.ROOTNODEYML];

            if (TYml2Xml.HasAttribute(rootNode, "UIConnectorType") && TYml2Xml.HasAttribute(rootNode, "UIConnectorCreate"))
            {
                FTemplate.AddToCodelet("UICONNECTORTYPE", TYml2Xml.GetAttribute(rootNode, "UIConnectorType"));
                FTemplate.AddToCodelet("UICONNECTORCREATE", TYml2Xml.GetAttribute(rootNode, "UIConnectorCreate"));
            }

            HandleWebConnectors(TYml2Xml.GetAttribute(rootNode, "Namespace"));

            if (TYml2Xml.HasAttribute(rootNode, "Icon"))
            {
                string iconFileName = TYml2Xml.GetAttribute(rootNode, "Icon");
                FTemplate.AddToCodelet("ADDMAINCONTROLS",
                    "this.Icon = (System.Drawing.Icon)resources.GetObject(\"$this.Icon\");" + Environment.NewLine);
                AddImageToResource("$this.Icon", iconFileName, "Icon");
            }

            if (FCodeStorage.FEventHandler.Contains("KeyEventHandler(this.Form_KeyDown)"))
            {
                // forms that have a KeyDown handler will need KeyPreview
                FTemplate.AddToCodelet("ADDMAINCONTROLS", "this.KeyPreview = true;" + Environment.NewLine);
            }

            string initialFocusControl = String.Empty;

            if (FCodeStorage.FControlList.ContainsKey("grdDetails"))
            {
                initialFocusControl = "grdDetails";
            }

            if (TYml2Xml.HasAttribute(rootNode, "InitialFocus"))
            {
                string tryFocus = TYml2Xml.GetAttribute(rootNode, "InitialFocus");

                if (FCodeStorage.FControlList.ContainsKey(tryFocus))
                {
                    initialFocusControl = tryFocus;
                }
                else
                {
                    TLogging.Log("Warning !!! Cannot set initial focus.  The specified control was not found: " + tryFocus);
                }
            }

            if (initialFocusControl != String.Empty)
            {
                FTemplate.SetCodelet("SETINITIALFOCUS", initialFocusControl + ".Focus();");
            }

            // add title
            if (ProperI18NCatalogGetString(FCodeStorage.FFormTitle))
            {
                FTemplate.AddToCodelet("CATALOGI18N",
                    "this.Text = Catalog.GetString(\"" + FCodeStorage.FFormTitle + "\");" + Environment.NewLine);
            }

            // add actions
            foreach (TActionHandler handler in FCodeStorage.FActionList.Values)
            {
                if (!handler.actionName.StartsWith("cnd"))
                {
                    AddActionHandlerImplementation(handler);
                }

                if (TYml2Xml.HasAttribute(handler.actionNode, "InitialValue"))
                {
                    string actionEnabling =
                        "if (e.ActionName == \"" + handler.actionName + "\")" + Environment.NewLine +
                        "{" + Environment.NewLine +
                        "    {#ENABLEDEPENDINGACTIONS_" + handler.actionName + "}" + Environment.NewLine +
                        "}" + Environment.NewLine + Environment.NewLine;
                    Template.AddToCodelet("ACTIONENABLING", actionEnabling);
                    Template.AddToCodelet(
                        "INITACTIONSTATE",
                        "ActionEnabledEvent(null, new ActionEventArgs(" +
                        "\"" + handler.actionName + "\", " + TYml2Xml.GetAttribute(handler.actionNode,
                            "InitialValue") + "));" + Environment.NewLine);
                }

                if (TYml2Xml.HasAttribute(handler.actionNode, "Enabled"))
                {
                    Template.AddToCodelet(
                        "ENABLEDEPENDINGACTIONS_" + TYml2Xml.GetAttribute(handler.actionNode, "Enabled"),
                        "FPetraUtilsObject.EnableAction(\"" + handler.actionName + "\", e.Enabled);" + Environment.NewLine);
                }
            }

            WriteAllControls();

            FinishUpInitialisingControls();

            if (FCodeStorage.ManualFileExistsAndContains("void ShowDataManual()"))
            {
                FTemplate.AddToCodelet("SHOWDATA", "ShowDataManual();" + Environment.NewLine);
            }
            else if (FCodeStorage.ManualFileExistsAndContains("void ShowDataManual("))
            {
                FTemplate.AddToCodelet("SHOWDATA", "ShowDataManual(ARow);" + Environment.NewLine);
            }

            if (FCodeStorage.FControlList.ContainsKey("pnlDetails"))
            {
                FTemplate.AddToCodelet("CLEARDETAILS", "FPetraUtilsObject.ClearControls(pnlDetails);" + Environment.NewLine);
            }

            if (FCodeStorage.ManualFileExistsAndContains("void ShowDetailsManual"))
            {
                FTemplate.AddToCodelet("SHOWDETAILS", "ShowDetailsManual(ARow);" + Environment.NewLine);
                FTemplate.AddToCodelet("CLEARDETAILS", "ShowDetailsManual(ARow);" + Environment.NewLine);
            }

            if (FCodeStorage.ManualFileExistsAndContains("GetDataFromControlsManual()"))
            {
                FTemplate.AddToCodelet("SAVEDATA", "GetDataFromControlsManual();" + Environment.NewLine);
            }
            else if (FCodeStorage.ManualFileExistsAndContains("GetDataFromControlsManual("))
            {
                FTemplate.AddToCodelet("SAVEDATA", "GetDataFromControlsManual(ARow);" + Environment.NewLine);
            }

            if (FCodeStorage.ManualFileExistsAndContains("GetDataFromControlsExtra()"))
            {
                FTemplate.AddToCodelet("SAVEDATAEXTRA", "GetDataFromControlsExtra();" + Environment.NewLine);
            }
            else if (FCodeStorage.ManualFileExistsAndContains("GetDataFromControlsExtra("))
            {
                FTemplate.AddToCodelet("SAVEDATAEXTRA", "GetDataFromControlsExtra(ARow);" + Environment.NewLine);
            }
            else
            {
                FTemplate.AddToCodelet("SAVEDATAEXTRA", "");
            }

//            if (FCodeStorage.ManualFileExistsAndContains("ValidateDetailsManual"))
//            {
//                ProcessTemplate validateSnippet = FTemplate.GetSnippet("VALIDATEDETAILS");
//                FTemplate.InsertSnippet("VALIDATEDETAILS", validateSnippet);
//            }
//
            if (FCodeStorage.ManualFileExistsAndContains("GetDetailDataFromControlsManual"))
            {
                FTemplate.AddToCodelet("SAVEDETAILS", "GetDetailDataFromControlsManual(ARow);" + Environment.NewLine);
            }

            if (FCodeStorage.ManualFileExistsAndContains("GetDetailDataFromControlsExtra"))
            {
                FTemplate.AddToCodelet("SAVEDETAILSEXTRA", "GetDetailDataFromControlsExtra(ARow);" + Environment.NewLine);
            }
            else
            {
                FTemplate.AddToCodelet("SAVEDETAILSEXTRA", "");
            }

            if (FCodeStorage.ManualFileExistsAndContains("void ReadControlsManual"))
            {
                FTemplate.AddToCodelet("READCONTROLS", "ReadControlsManual(ACalc, AReportAction);" + Environment.NewLine);
            }

            if (FCodeStorage.ManualFileExistsAndContains("void SetControlsManual"))
            {
                FTemplate.AddToCodelet("SETCONTROLS", "SetControlsManual(AParameters);" + Environment.NewLine);
            }

            if (FCodeStorage.ManualFileExistsAndContains("ValidateDataManual"))
            {
                FTemplate.SetCodelet("VALIDATEDATAMANUAL", "true");
            }

            if (FCodeStorage.ManualFileExistsAndContains("GetDetailsFromControlsManual"))
            {
                FTemplate.SetCodelet("GETDETAILSMANUAL", "true");
            }

            if (FCodeStorage.ManualFileExistsAndContains("ValidateDataDetailsManual"))
            {
                FTemplate.SetCodelet("VALIDATEDATADETAILSMANUAL", "true");
            }

            if (FCodeStorage.ManualFileExistsAndContains("GetSelectedDetailRowManual"))
            {
                FTemplate.AddToCodelet("GETSELECTEDDETAILROW", "return GetSelectedDetailRowManual();" + Environment.NewLine);
            }
            else
            {
                string getSelectedDetailRow =
                    "DataRowView[] SelectedGridRow = grdDetails.SelectedDataRowsAsDataRowView;" + Environment.NewLine + Environment.NewLine +
                    "if (SelectedGridRow.Length >= 1)" + Environment.NewLine +
                    "{" + Environment.NewLine +
                    "    return ({#DETAILTABLETYPE}Row)SelectedGridRow[0].Row;" + Environment.NewLine +
                    "}" + Environment.NewLine + Environment.NewLine +
                    "return null;" + Environment.NewLine + Environment.NewLine;

                FTemplate.SetCodelet("GETSELECTEDDETAILROW", getSelectedDetailRow);
            }

            InsertCodeIntoTemplate(AXAMLFilename);
        }
Exemplo n.º 7
0
        private static void InsertMainProcedures(TDataDefinitionStore AStore,
            TTable ACurrentTable,
            ProcessTemplate ATemplate,
            ProcessTemplate ASnippet)
        {
            ASnippet.SetCodelet("TABLENAME", TTable.NiceTableName(ACurrentTable.strName));
            ASnippet.SetCodeletComment("TABLE_DESCRIPTION", ACurrentTable.strDescription);
            ASnippet.SetCodelet("SQLTABLENAME", ACurrentTable.strName);
            ASnippet.SetCodelet("VIAOTHERTABLE", "");
            ASnippet.SetCodelet("VIALINKTABLE", "");

            string formalParametersPrimaryKey;
            string actualParametersPrimaryKey;
            string actualParametersPrimaryKeyToString;
            int numberPrimaryKeyColumns;

            PrepareCodeletsPrimaryKey(ACurrentTable,
                out formalParametersPrimaryKey,
                out actualParametersPrimaryKey,
                out actualParametersPrimaryKeyToString,
                out numberPrimaryKeyColumns);

            ASnippet.SetCodelet("FORMALPARAMETERSPRIMARYKEY", formalParametersPrimaryKey);
            ASnippet.SetCodelet("ACTUALPARAMETERSPRIMARYKEY", actualParametersPrimaryKey);
            ASnippet.SetCodelet("ACTUALPARAMETERSPRIMARYKEYTOSTRING", actualParametersPrimaryKeyToString);
            ASnippet.SetCodelet("PRIMARYKEYNUMBERCOLUMNS", numberPrimaryKeyColumns.ToString());

            string formalParametersUniqueKey;
            string actualParametersUniqueKey;
            int numberUniqueKeyColumns;

            PrepareCodeletsUniqueKey(ACurrentTable,
                out formalParametersUniqueKey,
                out actualParametersUniqueKey,
                out numberUniqueKeyColumns);

            ASnippet.SetCodelet("FORMALPARAMETERSUNIQUEKEY", formalParametersUniqueKey);
            ASnippet.SetCodelet("ACTUALPARAMETERSUNIQUEKEY", actualParametersUniqueKey);
            ASnippet.SetCodelet("UNIQUEKEYNUMBERCOLUMNS", numberUniqueKeyColumns.ToString());


            ASnippet.SetCodelet("SEQUENCENAMEANDFIELD", "");

            foreach (TTableField tablefield in ACurrentTable.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)
                {
                    ASnippet.SetCodelet("SEQUENCENAMEANDFIELD", ", \"" + tablefield.strSequence + "\", \"" + tablefield.strName + "\"");

                    // assume only one sequence per table
                    break;
                }
            }
        }
Exemplo n.º 8
0
        /// 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.Shared." + 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;
            }
        }
Exemplo n.º 9
0
        public void TestTemplateEngine()
        {
            ProcessTemplate template = new ProcessTemplate();

            template.FTemplateCode = new StringBuilder("my test" + Environment.NewLine +
                "{#IFDEF TEST1}" + Environment.NewLine +
                "test1" + Environment.NewLine +
                "{#ENDIF TEST1}" + Environment.NewLine);

            template.SetCodelet("TEST1", "test");

            Assert.AreEqual("my test" + Environment.NewLine + "test1" + Environment.NewLine,
                template.FinishWriting(true),
                "TEST1");

            template = new ProcessTemplate();
            template.FTemplateCode = new StringBuilder("my test" + Environment.NewLine +
                "{#IFNDEF TEST2}" + Environment.NewLine +
                "test2" + Environment.NewLine +
                "{#ENDIFN TEST2}" + Environment.NewLine);

            template.SetCodelet("TEST2", "test");

            Assert.AreEqual("my test" + Environment.NewLine,
                template.FinishWriting(true),
                "TEST2");

            template = new ProcessTemplate();
            template.FTemplateCode = new StringBuilder("my test" + Environment.NewLine +
                "{#IFNDEF TEST3}" + Environment.NewLine +
                "test3" + Environment.NewLine +
                "{#ENDIFN TEST3}" + Environment.NewLine +
                "hallo" + Environment.NewLine);

            Assert.AreEqual("my test" + Environment.NewLine +
                "test3" + Environment.NewLine +
                "hallo" + Environment.NewLine,
                template.FinishWriting(true),
                "TEST3");

            template = new ProcessTemplate();
            template.FTemplateCode = new StringBuilder("my test" + Environment.NewLine +
                "{#IFDEF TEST1}" + Environment.NewLine +
                "test1" + Environment.NewLine +
                "{#ENDIF TEST1}" + Environment.NewLine +
                "{#IFNDEF TEST2}" + Environment.NewLine +
                "test2" + Environment.NewLine +
                "{#ENDIFN TEST2}" + Environment.NewLine +
                "{#IFNDEF TEST3}" + Environment.NewLine +
                "test3" + Environment.NewLine +
                "{#ENDIFN TEST3}" + Environment.NewLine +
                "{#IFDEF TEST4}" + Environment.NewLine +
                "test4" + Environment.NewLine +
                "{#ENDIF TEST4}" + Environment.NewLine +
                "hallo" + Environment.NewLine);

            template.SetCodelet("TEST1", "test");
            template.SetCodelet("TEST3", "test");

            Assert.AreEqual("my test" + Environment.NewLine +
                "test1" + Environment.NewLine +
                "test2" + Environment.NewLine +
                "hallo" + Environment.NewLine,
                template.FinishWriting(true),
                "TEST4");

            template = new ProcessTemplate();
            template.FTemplateCode = new StringBuilder("my test" + Environment.NewLine +
                "{#IFDEF TEST5 OR TEST1}" + Environment.NewLine +
                "test5" + Environment.NewLine +
                "{#ENDIF TEST5 OR TEST1}" + Environment.NewLine);

            template.SetCodelet("TEST5", "test");

            Assert.AreEqual("my test" + Environment.NewLine + "test5" + Environment.NewLine,
                template.FinishWriting(true),
                "TEST5");

            template = new ProcessTemplate();
            template.FTemplateCode = new StringBuilder("my test" + Environment.NewLine +
                "{#IFDEF TEST5 AND TEST6}" + Environment.NewLine +
                "test6" + Environment.NewLine +
                "{#ENDIF TEST5 AND TEST6}" + Environment.NewLine);

            template.SetCodelet("TEST6", "test");

            Assert.AreEqual("my test" + Environment.NewLine,
                template.FinishWriting(true),
                "TEST6");

            template = new ProcessTemplate();
            template.FTemplateCode = new StringBuilder("my test" + Environment.NewLine +
                "{#IFDEF TEST6 AND TEST7}" + Environment.NewLine +
                "test7" + Environment.NewLine +
                "{#ENDIF TEST6 AND TEST7}" + Environment.NewLine);

            template.SetCodelet("TEST6", "test");
            template.SetCodelet("TEST7", "test");

            Assert.AreEqual("my test" + Environment.NewLine + "test7" + Environment.NewLine,
                template.FinishWriting(true),
                "TEST7");

            template = new ProcessTemplate();
            template.FTemplateCode = new StringBuilder("{#IFDEF TEST8}" + Environment.NewLine +
                "test8" + Environment.NewLine +
                "{#ENDIF TEST8}" + Environment.NewLine +
                "test8" + Environment.NewLine +
                "{#IFDEF TEST8}" + Environment.NewLine +
                "test8" + Environment.NewLine +
                "{#ENDIF TEST8}" + Environment.NewLine);


            template.SetCodelet("TEST8", "test");

            Assert.AreEqual("test8" + Environment.NewLine + "test8" + Environment.NewLine + "test8" + Environment.NewLine,
                template.FinishWriting(true),
                "TEST8");

            template = new ProcessTemplate();
            template.FTemplateCode = new StringBuilder("{#IFNDEF TEST9}" + Environment.NewLine +
                "test8" + Environment.NewLine +
                "{#ENDIFN TEST9}" + Environment.NewLine +
                "test9" + Environment.NewLine +
                "{#IFNDEF TEST9}" + Environment.NewLine +
                "test8" + Environment.NewLine +
                "{#ENDIFN TEST9}" + Environment.NewLine);


            template.SetCodelet("TEST9", "test");

            Assert.AreEqual("test9" + Environment.NewLine,
                template.FinishWriting(true),
                "TEST9");

            template = new ProcessTemplate();
            template.FTemplateCode = new StringBuilder("{#IFNDEF TEST10}" + Environment.NewLine +
                "test8" + Environment.NewLine +
                "{#ENDIFN TEST10}" + Environment.NewLine +
                "test9" + Environment.NewLine +
                "{#IFDEF TEST10}" + Environment.NewLine +
                "test10" + Environment.NewLine +
                "{#ENDIF TEST10}" + Environment.NewLine);


            template.SetCodelet("TEST10", "test");

            Assert.AreEqual("test9" + Environment.NewLine + "test10" + Environment.NewLine,
                template.FinishWriting(true),
                "TEST10");

            template = new ProcessTemplate();
            template.FTemplateCode = new StringBuilder("{#IFDEF TEST10}" + Environment.NewLine +
                "{#IFDEF TEST11}" + Environment.NewLine +
                "{#IFDEF TEST11}" + Environment.NewLine +
                "test11" + Environment.NewLine +
                "{#ENDIF TEST11}" + Environment.NewLine +
                "{#ENDIF TEST11}" + Environment.NewLine +
                "{#IFNDEF TEST11}" + Environment.NewLine +
                "test10" + Environment.NewLine +
                "{#ENDIFN TEST11}" + Environment.NewLine +
                "{#ENDIF TEST10}" + Environment.NewLine +
                "{#IFNDEF TEST10}" + Environment.NewLine +
                "{#IFNDEF TEST11}" + Environment.NewLine +
                "{#IFDEF TEST11}" + Environment.NewLine +
                "test13" + Environment.NewLine +
                "{#ENDIF TEST11}" + Environment.NewLine +
                "{#ENDIFN TEST11}" + Environment.NewLine +
                "{#ENDIFN TEST10}" + Environment.NewLine +
                "test1" + Environment.NewLine);

            template.SetCodelet("TEST11", "test_11");
            template.SetCodelet("TEST10", "test_10");

            Assert.AreEqual("test11" + Environment.NewLine + "test1" + Environment.NewLine,
                template.FinishWriting(true),
                "TEST11");
        }
        /// <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);
        }
Exemplo n.º 11
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);
        }
Exemplo n.º 12
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);
        }
Exemplo n.º 13
0
        static private void InsertSubNamespaces(ProcessTemplate ATemplate,
            SortedList <string, TypeDeclaration>connectors,
            string AParentNamespaceName,
            string AFullNamespace,
            TNamespace AParentNamespace)
        {
            ATemplate.SetCodelet("SUBNAMESPACECLASSES", string.Empty);
            ATemplate.SetCodelet("SUBNAMESPACEPROPERTIES", string.Empty);
            ATemplate.SetCodelet("CONNECTORMETHODS", string.Empty);

            foreach (TNamespace sn in AParentNamespace.Children.Values)
            {
                ProcessTemplate templateProperty = ATemplate.GetSnippet("SUBNAMESPACEPROPERTY");
                templateProperty.SetCodelet("NAMESPACENAME", AParentNamespaceName + sn.Name);
                templateProperty.SetCodelet("SUBNAMESPACENAME", sn.Name);
                templateProperty.SetCodelet("OBJECTNAME", sn.Name);

                ProcessTemplate templateClass = ATemplate.GetSnippet("NAMESPACECLASS");
                templateClass.SetCodelet("NAMESPACENAME", AParentNamespaceName + sn.Name);
                InsertSubNamespaces(templateClass, connectors,
                    AParentNamespaceName + sn.Name,
                    AFullNamespace + "." + sn.Name,
                    sn);

                ATemplate.InsertSnippet("SUBNAMESPACECLASSES", templateClass);

                ATemplate.InsertSnippet("SUBNAMESPACEPROPERTIES", templateProperty);
            }

            if (AParentNamespaceName.EndsWith("WebConnectors"))
            {
                ImplementWebConnector(connectors, ATemplate, AFullNamespace);
            }
            else
            {
                ImplementUIConnector(connectors, ATemplate, AFullNamespace);
            }
        }
Exemplo n.º 14
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;
        }
Exemplo n.º 15
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");
                                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");
                            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);
        }
Exemplo n.º 16
0
        /// <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;
        }
Exemplo n.º 17
0
    //other interfaces, e.g. IPartnerUIConnectorsPartnerEdit
    // we don't know the interfaces that are implemented, so need to look for the base classes
    // we need to know all the source files that are part of the UIConnector dll
    private void WriteNamespaces(ProcessTemplate AMainTemplate,
        TNamespace tn, SortedList AInterfaceNames, List <CSParser>ACSFiles)
    {
        AMainTemplate.SetCodelet("MODULE", tn.Name);

        foreach (TNamespace sn in tn.Children.Values)
        {
            ProcessTemplate snippet = AMainTemplate.GetSnippet("SUBNAMESPACE");
            snippet.SetCodelet("SUBNAMESPACENAME", sn.Name);
            snippet.SetCodelet("SUBNAMESPACEOBJECT", sn.Name);
            AMainTemplate.InsertSnippet("SUBNAMESPACES", snippet);
        }

        // parse Instantiator source code
        foreach (TNamespace sn in tn.Children.Values)
        {
            WriteNamespace(AMainTemplate,
                "Ict.Petra.Shared.Interfaces.M" + tn.Name + "." + sn.Name,
                sn.Name, tn, sn, sn.Children, AInterfaceNames, ACSFiles);
        }
    }
        private Boolean CreateConnectors(String AOutputPath, String AModulePath, String ATemplateDir)
        {
            // Work out the module name from the module path
            string[] items = AModulePath.Split(new char[] { Path.DirectorySeparatorChar });

            if (items.Length == 0)
            {
                // the -inputclient command line parameter must be wrong
                return false;
            }

            // Module name is e.g. MCommon, MPartner etc
            string moduleName = items[items.Length - 1];

            // Work out the actual folder/file for the output file
            String OutputFolder = AOutputPath + Path.DirectorySeparatorChar + "lib" +
                                  Path.DirectorySeparatorChar + moduleName +
                                  Path.DirectorySeparatorChar + "web";

            String OutputFile = OutputFolder + Path.DirectorySeparatorChar + "ReferenceCount-generated.cs";
            Console.WriteLine("working on " + OutputFile);

            // Where is the template?
            String templateFilename = ATemplateDir +
                                      Path.DirectorySeparatorChar + "ORM" +
                                      Path.DirectorySeparatorChar + "ReferenceCountWebConnector.cs";

            if (!File.Exists(templateFilename))
            {
                // The -templatedir command line parameter must have been wrong
                return false;
            }

            // Open the template
            ProcessTemplate Template = new ProcessTemplate(templateFilename);

            // now we need to remove the leading 'M' from the module name
            moduleName = moduleName.Substring(1);
            string className = "T" + moduleName + "ReferenceCountWebConnector";

            Console.WriteLine("Starting connector for " + className + Environment.NewLine);

            int cacheableCount = 0;
            int nonCacheableCount = 0;

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

            Template.SetCodelet("CLASSNAME", className);
            Template.SetCodelet("CACHEABLETABLECASES", string.Empty);
            Template.SetCodelet("CACHEABLETABLENAME", string.Empty);
            Template.SetCodelet("CACHEABLETABLECASE", string.Empty);
            Template.SetCodelet("CACHEABLETABLELISTNAME", string.Empty);
            Template.SetCodelet("CACHEABLETRANSACTION", string.Empty);
            Template.SetCodelet("CACHEABLEFINALLY", string.Empty);
            Template.SetCodelet("TABLESIF", string.Empty);
            Template.SetCodelet("TABLESELSEIF", string.Empty);
            Template.SetCodelet("TABLESELSE", string.Empty);
            Template.SetCodelet("TABLENAME", string.Empty);
            Template.SetCodelet("NONCACHEABLETRANSACTION", string.Empty);
            Template.SetCodelet("NONCACHEABLEFINALLY", string.Empty);

            // Find all the YAML files in the client module folder
            string[] clientFiles = Directory.GetFiles(AModulePath, "*.yaml", SearchOption.AllDirectories);

            foreach (String fn in clientFiles)
            {
                // only look for main files, not language specific files (*.xy-XY.yaml or *.xy.yaml)
                if (TProcessYAMLForms.IgnoreLanguageSpecificYamlFile(fn))
                {
                    continue;
                }

                XmlDocument doc = TYml2Xml.CreateXmlDocument();
                SortedList sortedNodes = null;
                TCodeStorage codeStorage = new TCodeStorage(doc, sortedNodes);
                TParseYAMLFormsDefinition yamlParser = new TParseYAMLFormsDefinition(ref codeStorage);
                yamlParser.LoadRecursively(fn, null);

                string attDetailTableName = codeStorage.GetAttribute("DetailTable");
                string attCacheableListName = codeStorage.GetAttribute("CacheableTable");

                // Note - this IF clause needs to be the same as the one in FormWriter.cs which is generating the client side code
                // Do Ctrl+F to find: this IF clause needs to be the same
                // in that file
                if ((attDetailTableName != String.Empty)
                    && (codeStorage.FControlList.ContainsKey("btnDelete")
                        || codeStorage.FControlList.ContainsKey("btnDeleteType")
                        || codeStorage.FControlList.ContainsKey("btnDeleteExtract")
                        || codeStorage.FControlList.ContainsKey("btnDeleteDetail")
                        || (codeStorage.FControlList.ContainsKey("btnRemoveDetail") && (codeStorage.GetAttribute("FormType") != "report"))))
                {
                    if (attCacheableListName != String.Empty)
                    {
                        ProcessTemplate snippet = Template.GetSnippet("CACHEABLETABLECASE");
                        snippet.SetCodelet("CACHEABLETABLENAME", attDetailTableName);
                        snippet.SetCodelet("CACHEABLETABLELISTNAME", attCacheableListName);
                        Template.InsertSnippet("CACHEABLETABLECASES", snippet);

                        if (cacheableCount == 0)
                        {
                            // Add these on the first time through
                            snippet = Template.GetSnippet("CACHEABLETRANSACTIONSNIP");
                            Template.InsertSnippet("CACHEABLETRANSACTION", snippet);
                            snippet = Template.GetSnippet("CACHEABLEFINALLYSNIP");
                            Template.InsertSnippet("CACHEABLEFINALLY", snippet);
                        }

                        Console.WriteLine("Creating cacheable reference count connector for " + attCacheableListName);
                        cacheableCount++;
                    }
                    else
                    {
                        ProcessTemplate snippet = null;

                        if (nonCacheableCount == 0)
                        {
                            snippet = Template.GetSnippet("TABLEIF");
                            snippet.SetCodelet("TABLENAME", attDetailTableName);
                            Template.InsertSnippet("TABLESIF", snippet);

                            snippet = Template.GetSnippet("NONCACHEABLETRANSACTIONSNIP");
                            Template.InsertSnippet("NONCACHEABLETRANSACTION", snippet);
                            snippet = Template.GetSnippet("NONCACHEABLEFINALLYSNIP");
                            Template.InsertSnippet("NONCACHEABLEFINALLY", snippet);
                        }
                        else
                        {
                            snippet = Template.GetSnippet("TABLEELSEIF");
                            snippet.SetCodelet("TABLENAME", attDetailTableName);
                            Template.InsertSnippet("TABLESELSEIF", snippet);
                        }

                        Console.WriteLine("Creating non-cacheable reference count connector for " + attDetailTableName);
                        nonCacheableCount++;
                    }
                }
            }

            // Now we finish off the template content depending on how many entries we made
            if ((nonCacheableCount == 0) && (cacheableCount > 0))
            {
                ProcessTemplate snippet = Template.GetSnippet("TABLENONE");
                Template.InsertSnippet("TABLESELSE", snippet);
            }

            if (nonCacheableCount > 0)
            {
                ProcessTemplate snippet = Template.GetSnippet("TABLEELSE");
                Template.InsertSnippet("TABLESELSE", snippet);
            }

            if ((cacheableCount > 0) || (nonCacheableCount > 0))
            {
                if (!Directory.Exists(OutputFolder))
                {
                    // The -outputserver command line parameter must be wrong, or the directory does not exist yet
                    // Directories must be manually created and added to source code control
                    Console.WriteLine("Error: directory does not exist: " + OutputFolder);
                    return false;
                }

                Console.WriteLine("Finishing connector for " + className + Environment.NewLine + Environment.NewLine);
                Template.FinishWriting(OutputFile, ".cs", true);

                FTotalCacheable += cacheableCount;
                FTotalNonCacheable += nonCacheableCount;
                FTotalConnectors++;
            }

            return true;
        }
Exemplo n.º 19
0
    void ImplementWebConnector(
        SortedList <string, TypeDeclaration>connectors,
        ProcessTemplate ATemplate, string AFullNamespace)
    {
        string ConnectorNamespace = AFullNamespace.
                                    Replace("Instantiator.", string.Empty);

        List <TypeDeclaration>ConnectorClasses = TCollectConnectorInterfaces.FindTypesInNamespace(connectors, ConnectorNamespace);

        ConnectorNamespace = ConnectorNamespace.
                             Replace("Ict.Petra.Shared.", "Ict.Petra.Server.");

        ATemplate.SetCodelet("CLIENTOBJECTFOREACHUICONNECTOR", string.Empty);

        foreach (TypeDeclaration connectorClass in ConnectorClasses)
        {
            foreach (MethodDeclaration m in CSParser.GetMethods(connectorClass))
            {
                if (TCollectConnectorInterfaces.IgnoreMethod(m.Attributes, m.Modifier))
                {
                    continue;
                }

                ProcessTemplate snippet = ATemplate.GetSnippet("WEBCONNECTORMETHOD");

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

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

                snippet.InsertSnippet("CHECKUSERMODULEPERMISSIONS",
                    CreateModuleAccessPermissionCheck(
                        ATemplate,
                        connectorClass.Name,
                        m));

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

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

                snippet.SetCodelet("METHODNAME", m.Name);
                snippet.SetCodelet("ACTUALPARAMETERS", ActualParameters);
                snippet.SetCodelet("PARAMETERDEFINITION", ParameterDefinition);
                snippet.SetCodelet("RETURNTYPE", returntype);
                snippet.SetCodelet("WEBCONNECTORCLASS", connectorClass.Name);

                if (!UsingConnectorNamespaces.Contains(ConnectorNamespace))
                {
                    UsingConnectorNamespaces.Add(ConnectorNamespace);
                }

                ATemplate.InsertSnippet("REMOTEDMETHODS", snippet);
            }
        }
    }
Exemplo n.º 20
0
        /// <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);

            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);
                }
            }

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

            return true;
        }
Exemplo n.º 21
0
    void ImplementUIConnector(
        SortedList <string, TypeDeclaration>connectors,
        ProcessTemplate ATemplate, string AFullNamespace)
    {
        string ConnectorNamespace = AFullNamespace.
                                    Replace("Instantiator.", string.Empty);

        List <TypeDeclaration>ConnectorClasses = TCollectConnectorInterfaces.FindTypesInNamespace(connectors, ConnectorNamespace);

        ConnectorNamespace = ConnectorNamespace.
                             Replace("Ict.Petra.Shared.", "Ict.Petra.Server.");

        ATemplate.SetCodelet("CLIENTOBJECTFOREACHUICONNECTOR", string.Empty);

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

                ProcessTemplate snippet = ATemplate.GetSnippet("UICONNECTORMETHOD");

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

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

                string methodname = m.Name.Substring(1);

                if (methodname.EndsWith("UIConnector"))
                {
                    methodname = methodname.Substring(0, methodname.LastIndexOf("UIConnector"));
                }

                snippet.SetCodelet("METHODNAME", methodname);
                snippet.SetCodelet("PARAMETERDEFINITION", ParameterDefinition);
                snippet.SetCodelet("ACTUALPARAMETERS", ActualParameters);
                snippet.SetCodelet("UICONNECTORINTERFACE", CSParser.GetImplementedInterface(connectorClass));
                snippet.SetCodelet("UICONNECTORCLIENTREMOTINGCLASS", connectorClass.Name + "Remote");
                snippet.SetCodelet("UICONNECTORCLASS", connectorClass.Name);

                if (!UsingConnectorNamespaces.Contains(ConnectorNamespace))
                {
                    UsingConnectorNamespaces.Add(ConnectorNamespace);
                }

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

            List <TypeDeclaration>tempList = new List <TypeDeclaration>();
            tempList.Add(connectorClass);

            ATemplate.InsertSnippet("CLIENTOBJECTFOREACHUICONNECTOR",
                TCreateClientRemotingClass.AddClientRemotingClass(
                    FTemplateDir,
                    connectorClass.Name + "Remote",
                    CSParser.GetImplementedInterface(connectorClass),
                    tempList
                    ));
        }
    }
Exemplo n.º 22
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);
        }
Exemplo n.º 23
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);
    }
Exemplo n.º 24
0
        /// based on the code model, create the code;
        /// using the code generators that have been loaded
        public override void CreateCode(TCodeStorage ACodeStorage, string AXAMLFilename, string ATemplateFile)
        {
            FCodeStorage = ACodeStorage;
            TControlGenerator.FCodeStorage = ACodeStorage;
            FTemplate = new ProcessTemplate(ATemplateFile);
            FFormName = Path.GetFileNameWithoutExtension(AXAMLFilename).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(AXAMLFilename);

            string languagefilepath = Path.GetDirectoryName(AXAMLFilename) + Path.DirectorySeparatorChar +
                                      Path.GetFileNameWithoutExtension(AXAMLFilename) + "-lang-template.js";
            File.WriteAllText(languagefilepath, FLanguageFileTemplate.FinishWriting(true));
        }
Exemplo n.º 25
0
        //other interfaces, e.g. IPartnerUIConnectorsPartnerEdit
        // we don't know the interfaces that are implemented, so need to look for the base classes
        // we need to know all the source files that are part of the UIConnector dll
        private void WriteNamespaces(ProcessTemplate AMainTemplate,
            TNamespace tn, SortedList AInterfaceNames, List <CSParser>ACSFiles)
        {
            AMainTemplate.SetCodelet("MODULE", tn.Name);

            // parse Instantiator source code
            foreach (TNamespace sn in tn.Children.Values)
            {
                WriteNamespace(AMainTemplate,
                    "Ict.Petra.Shared.Interfaces.M" + tn.Name + "." + sn.Name,
                    sn.Name, tn, sn, sn.Children, AInterfaceNames, ACSFiles);
            }
        }
Exemplo n.º 26
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 returnCodeFatClient = 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 EnumParameter = parametertype.EndsWith("Enum");
                bool BinaryParameter =
                    !((parametertype.StartsWith("System.Int64")) || (parametertype.StartsWith("System.Int32"))
                      || (parametertype.StartsWith("System.Int16"))
                      || (parametertype.StartsWith("System.String")) || (parametertype.StartsWith("System.Boolean"))
                      || EnumParameter);

                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))
                    {
                        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);
                }

                // 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 ((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 (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 (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))
                {
                    returnCodeFatClient +=
                        (returnCodeFatClient.Length > 0 ? "+\",\"+" : string.Empty) +
                        "THttpBinarySerializer.SerializeObjectWithType(" +
                        (((ParameterModifiers.Ref & p.ParamModifier) > 0 && BinaryParameter) ? "Local" : string.Empty) +
                        p.ParameterName + ")";

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

                    if (returnCounter > 0)
                    {
                        returnCodeJSClient += " + \", \\\"" + returnCounter.ToString() + "\\\": \" + ";
                    }

                    returnCodeJSClient +=
                        "THttpBinarySerializer.SerializeObjectWithType(" +
                        (((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")
                    {
                        returnCodeFatClient +=
                            (returnCodeFatClient.Length > 0 ? "+\",\"+" : string.Empty) + "THttpBinarySerializer.SerializeObjectWithType(Result)";

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

                        returnCodeJSClient += "+\", \\\"" + returnCounter.ToString() + "\\\": \"+" +
                                              "THttpBinarySerializer.SerializeObjectWithType(Result)";

                        returnCounter++;
                    }

                    returntype = "string";
                }
                else if (returntype == "System.String")
                {
                    returntype = "string";
                    returnCodeFatClient = "THttpBinarySerializer.SerializeObjectWithType(Result)";
                    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";
                    returnCodeFatClient = returnCodeJSClient = "THttpBinarySerializer.SerializeObject(Result)";
                }

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

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

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

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

                if ((returnCodeFatClient.Length > 0) || (returnCodeJSClient.Length > 0))
                {
                    snippet.SetCodelet("RETURN",
                        returntype != "void" ? "return isJSClient()?" + returnCodeJSClient + ":" + returnCodeFatClient + ";" : 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);
        }
Exemplo n.º 27
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);
        }
Exemplo n.º 28
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.Contains(":"))
                {
                    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);
        }
        /// <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;
        }