Esempio n. 1
0
        /// <summary>
        /// Determines whether automatic Data Validation code should be created for a certain Control in a YAML file.
        /// </summary>
        /// <param name="AControl">Control in YAML file.</param>
        /// <param name="AHasDataField"></param>
        /// <param name="AMasterOrDetailTable">Pass in 'true' if the YAML file has got a 'MasterTable' or 'DetailTable' Element. </param>
        /// <param name="AIncludeMasterOrDetailTableControl"></param>
        /// <param name="AScope">Scope of the Data Validation that should be checked for. Specify <see cref="TAutomDataValidationScope.advsAll"/>
        /// to find out if any of the scopes should be checked against, or use any other value of that enum to specifiy a specific scope.</param>
        /// <param name="AReasonForAutomValidation">Contains the reason why automatic data validation code needs to be generated.</param>
        /// <returns>True if automatic Data Validation code should be created for the Control in a YAML that was passed in in <paramref name="AControl" /> for
        /// the scope that was specified with <paramref name="AScope" />, otherwise false. This Method also returns false if the Control specified in
        /// <paramref name="AControl" /> isn't linked to a DB Table Field.</returns>
        public static bool GenerateAutoValidationCodeForControl(TControlDef AControl, bool AHasDataField, bool AMasterOrDetailTable,
                                                                bool AIncludeMasterOrDetailTableControl, TAutomDataValidationScope AScope, out string AReasonForAutomValidation)
        {
            TTableField DBField = null;
            bool        IsDetailNotMaster;

            AReasonForAutomValidation = String.Empty;

            if (AHasDataField)
            {
                DBField = TDataBinding.GetTableField(AControl, AControl.GetAttribute("DataField"), out IsDetailNotMaster, true);
            }
            else if (AMasterOrDetailTable && AIncludeMasterOrDetailTableControl)
            {
                DBField = TDataBinding.GetTableField(AControl, AControl.controlName.Substring(
                                                         AControl.controlTypePrefix.Length), out IsDetailNotMaster, false);
            }

            if (DBField != null)
            {
                return(GenerateAutoValidationCodeForDBTableField(DBField, AScope, null, out AReasonForAutomValidation));
            }
            else
            {
                return(false);
            }
        }
Esempio n. 2
0
        private static void PrepareCodeletsPrimaryKey(
            TTable ACurrentTable,
            out string csvListPrimaryKeyFields,
            out string formalParametersPrimaryKey,
            out string actualParametersPrimaryKey,
            out Tuple <string, string, string>[] formalParametersPrimaryKeySeparate)
        {
            csvListPrimaryKeyFields    = "";
            formalParametersPrimaryKey = "";
            actualParametersPrimaryKey = "";
            int           counterPrimaryKeyField = 0;
            string        PrimaryKeyLabel;
            List <string> PrimaryKeyLabels = new List <string>();

            if (!ACurrentTable.HasPrimaryKey())
            {
                formalParametersPrimaryKeySeparate = new Tuple <string, string, string> [0];
                return;
            }

            formalParametersPrimaryKeySeparate = new Tuple <string, string, string> [ACurrentTable.GetPrimaryKey().strThisFields.Count];

            foreach (string field in ACurrentTable.GetPrimaryKey().strThisFields)
            {
                if (counterPrimaryKeyField > 0)
                {
                    csvListPrimaryKeyFields    += ",";
                    formalParametersPrimaryKey += ", ";
                    actualParametersPrimaryKey += ", ";
                }

                TTableField typedField = ACurrentTable.GetField(field);

                PrimaryKeyLabel = typedField.strLabel;

                // Ensure that a table definition doesn't contain Primary Key columns with identical Labels as this would lead
                // to generated cascading count code that would fail at runtime as it would want to add items with the same
                // name to the 'PKInfo' dictionary! (Those labels would be wrong anyhow!)
                if (!PrimaryKeyLabels.Contains(PrimaryKeyLabel))
                {
                    PrimaryKeyLabels.Add(PrimaryKeyLabel);
                }
                else
                {
                    throw new Exception(
                              String.Format(
                                  "The DB table definition of Table '{0}' in petra.xml contains two Columns with the same Label, '{1}'. That is not allowed!",
                                  ACurrentTable.strName, PrimaryKeyLabel));
                }

                csvListPrimaryKeyFields    += field;
                formalParametersPrimaryKey += typedField.GetDotNetType() + " A" + TTable.NiceFieldName(field);
                actualParametersPrimaryKey += "A" + TTable.NiceFieldName(field);

                formalParametersPrimaryKeySeparate[counterPrimaryKeyField] = new Tuple <string, string, string>(
                    typedField.GetDotNetType(), " A" + TTable.NiceFieldName(field), PrimaryKeyLabel);

                counterPrimaryKeyField++;
            }
        }
Esempio n. 3
0
        /// convert the type from the xml file to an ODBC type
        public static string ToOdbcTypeString(TTableField tableField)
        {
//          Console.WriteLine("ToOdbcTypeString[" + tableField.strTableName + "]." + tableField.strName + ": "+ tableField.strType + "/" + tableField.strTypeDotNet);

            if ((tableField.strType == "number") && (tableField.iLength == 24 || tableField.iDecimals > 0))
            {
                return("OdbcType.Decimal");
            }
            else if (tableField.strTypeDotNet.ToLower().Contains("int64"))
            {
                return("OdbcType.BigInt");
            }
            else if ((tableField.strType == "number") && (tableField.iLength <= 10))
            {
                return("OdbcType.BigInt");
            }
            else if (tableField.strType == "number")
            {
                return("OdbcType.Decimal");
            }
            else if (tableField.strTypeDotNet.ToLower().Contains("decimal"))
            {
                return("OdbcType.Decimal");
            }
            else if ((tableField.strType == "varchar") || ((tableField.strTypeDotNet != null) && tableField.strTypeDotNet.ToLower().Contains("string")))
            {
                return("OdbcType.VarChar");
            }
            else if (tableField.strType == "text" || tableField.strType == "longtext")
            {
                return("OdbcType.Text");
            }
            else if (tableField.strType == "longtext")
            {
                return("OdbcType.Text");
            }
            else if ((tableField.strType == "bit") || ((tableField.strTypeDotNet != null) && tableField.strTypeDotNet.ToLower().Contains("bool")))
            {
                return("OdbcType.Bit");
            }
            else if ((tableField.strType == "date") || ((tableField.strTypeDotNet != null) && tableField.strTypeDotNet.ToLower().Contains("datetime")))
            {
                return("OdbcType.Date");
            }
            else if (tableField.strType == "timestamp" || tableField.strType == "datetime")
            {
                return("OdbcType.DateTime");
            }
            else if ((tableField.strType == "integer") || ((tableField.strTypeDotNet != null) && tableField.strTypeDotNet.ToLower().Contains("int32")))
            {
                return("OdbcType.Int");
            }
            else
            {
                throw (new Exception("ERROR: Bad Field Type in [" + tableField.strTableName + "]." + tableField.strName + ": " + tableField.strType +
                                     "/" + tableField.strTypeDotNet));
            }
        }
Esempio n. 4
0
        static private void ProcessLine(SqliteCommand cmd, string line, TTable table, StringCollection AColumnNames)
        {
            int    count     = 0;
            string Separator = "\t";

            line = line.Replace("\\N", "?");

            if (!line.Contains(Separator))
            {
                Separator = ",";
            }

            foreach (string columnname in AColumnNames)
            {
                TTableField field = table.GetField(columnname);

                Object val = StringHelper.GetNextCSV(ref line, Separator);

                if (val.ToString() == "?")
                {
                    val = null;
                }
                else if ((field.strType == "date") && (val.ToString().Length != 0))
                {
                    if (val.ToString().Contains("-"))
                    {
                        StringCollection dateString = StringHelper.StrSplit(val.ToString(), "-");
                        val = new DateTime(Convert.ToInt16(dateString[0]),
                                           Convert.ToInt16(dateString[1]),
                                           Convert.ToInt16(dateString[2]));
                    }
                    else
                    {
                        try
                        {
                            val = new DateTime(Convert.ToInt16(val.ToString().Substring(0, 3)),
                                               Convert.ToInt16(val.ToString().Substring(4, 2)),
                                               Convert.ToInt16(val.ToString().Substring(6, 2)));
                        }
                        catch (Exception e)
                        {
                            TLogging.Log(e.ToString());
                            throw new Exception("error parsing date time " + val);
                        }
                    }
                }
                else if (field.strType == "bit")
                {
                    val = (val.ToString() == "true") || (val.ToString() == "t");
                }

                cmd.Parameters[count].Value = val;
                count++;
            }
        }
Esempio n. 5
0
        /// convert the type from the xml file to an ODBC type
        public static string ToOdbcTypeString(TTableField tableField)
        {
//          Console.WriteLine("ToOdbcTypeString[" + tableField.strTableName + "]." + tableField.strName + ": "+ tableField.strType + "/" + tableField.strTypeDotNet);

            if ((tableField.strType == "number") && (tableField.iLength == 24))
            {
                // currency value. This length="24" attribute is not consistently applied - check XML files
                // by un-commenting the Writelns here before assuming that all the field definitions are correct.

//              Console.WriteLine("tableField.iLength == 24 in [" + tableField.strTableName + "]." + tableField.strName);
                return("OdbcType.Decimal");
            }
            else if ((tableField.strType == "number") || ((tableField.strTypeDotNet != null) && tableField.strTypeDotNet.ToLower().Contains("int64")))
            {
                return("OdbcType.Decimal");
            }
            else if (tableField.strTypeDotNet.ToLower().Contains("decimal"))
            {
                return("OdbcType.Decimal");
            }
            else if ((tableField.strType == "varchar") || ((tableField.strTypeDotNet != null) && tableField.strTypeDotNet.ToLower().Contains("string")))
            {
                return("OdbcType.VarChar");
            }
            else if (tableField.strType == "text")
            {
                return("OdbcType.Text");
            }
            else if ((tableField.strType == "bit") || ((tableField.strTypeDotNet != null) && tableField.strTypeDotNet.ToLower().Contains("bool")))
            {
                return("OdbcType.Bit");
            }
            else if ((tableField.strType == "date") || ((tableField.strTypeDotNet != null) && tableField.strTypeDotNet.ToLower().Contains("datetime")))
            {
                return("OdbcType.Date");
            }
            else if (tableField.strType == "timestamp" || tableField.strType == "datetime")
            {
                return("OdbcType.DateTime");
            }
            else if ((tableField.strType == "integer") || ((tableField.strTypeDotNet != null) && tableField.strTypeDotNet.ToLower().Contains("int32")))
            {
                return("OdbcType.Int");
            }
            else
            {
                //
                // This is new (March 2014) - previously every bad type was given as int.

                throw (new Exception("ERROR: Bad Field Type in [" + tableField.strTableName + "]." + tableField.strName + ": " + tableField.strType +
                                     "/" + tableField.strTypeDotNet));
            }
        }
Esempio n. 6
0
        /// convert the type from the xml file to an ODBC type
        public static string ToOdbcTypeString(TTableField tableField)
        {
//          Console.WriteLine("ToOdbcTypeString[" + tableField.strTableName + "]." + tableField.strName + ": "+ tableField.strType + "/" + tableField.strTypeDotNet);

            if ((tableField.strType == "number") && (tableField.iLength == 24))
            {
                // currency value. This length="24" attribute is not consistently applied - check XML files
                // by un-commenting the Writelns here before assuming that all the field definitions are correct.

//              Console.WriteLine("tableField.iLength == 24 in [" + tableField.strTableName + "]." + tableField.strName);
                return "OdbcType.Decimal";
            }
            else if ((tableField.strType == "number") || ((tableField.strTypeDotNet != null) && tableField.strTypeDotNet.ToLower().Contains("int64")))
            {
                return "OdbcType.Decimal";
            }
            else if (tableField.strTypeDotNet.ToLower().Contains("decimal"))
            {
                return "OdbcType.Decimal";
            }
            else if ((tableField.strType == "varchar") || ((tableField.strTypeDotNet != null) && tableField.strTypeDotNet.ToLower().Contains("string")))
            {
                return "OdbcType.VarChar";
            }
            else if (tableField.strType == "text")
            {
                return "OdbcType.Text";
            }
            else if ((tableField.strType == "bit") || ((tableField.strTypeDotNet != null) && tableField.strTypeDotNet.ToLower().Contains("bool")))
            {
                return "OdbcType.Bit";
            }
            else if ((tableField.strType == "date") || ((tableField.strTypeDotNet != null) && tableField.strTypeDotNet.ToLower().Contains("datetime")))
            {
                return "OdbcType.Date";
            }
            else if (tableField.strType == "timestamp")
            {
                return "OdbcType.DateTime";
            }
            else if ((tableField.strType == "integer") || ((tableField.strTypeDotNet != null) && tableField.strTypeDotNet.ToLower().Contains("int32")))
            {
                return "OdbcType.Int";
            }
            else
            {
                //
                // This is new (March 2014) - previously every bad type was given as int.

                throw (new Exception("ERROR: Bad Field Type in [" + tableField.strTableName + "]." + tableField.strName + ": " + tableField.strType +
                           "/" + tableField.strTypeDotNet));
            }
        }
Esempio n. 7
0
        /// <summary>
        /// special version to get the original sql name of the names
        /// </summary>
        /// <param name="ATables"></param>
        /// <param name="ATableName"></param>
        /// <param name="ANames"></param>
        /// <returns></returns>
        private static string StringCollectionToValuesFormattedForArray(
            SortedList <string, TDataSetTable> ATables,
            string ATableName,
            StringCollection ANames)
        {
            TDataSetTable currentTable = null;

            foreach (TDataSetTable table in ATables.Values)
            {
                if ((table.tablealias == ATableName) ||
                    (table.tablename == ATableName) ||
                    (table.tableorig == ATableName) ||
                    (TTable.NiceTableName(table.strName) == ATableName))
                {
                    currentTable = table;
                }
            }

            if (currentTable == null)
            {
                throw new Exception("StringCollectionToValuesFormattedForArray: cannot find table " + ATableName);
            }

            bool   first  = true;
            string Result = String.Empty;

            foreach (string fieldname in ANames)
            {
                if (!first)
                {
                    Result += ", ";
                }

                first = false;

                TTableField field = currentTable.GetField(fieldname);

                if (field == null)
                {
                    // might be a custom field
                    Result += '"' + fieldname + '"';
                }
                else
                {
                    // get the original sql name
                    Result += '"' + field.strName + '"';
                }
            }

            return(Result);
        }
        private static void PrepareCodeletsForeignKey(
            TTable AOtherTable,
            TConstraint AConstraint,
            out string whereClauseForeignKey,
            out string whereClauseViaOtherTable,
            out string odbcParametersForeignKey,
            out int numberFields,
            out string namesOfThisTableFields)
        {
            whereClauseForeignKey    = "";
            whereClauseViaOtherTable = "";
            numberFields             = AConstraint.strThisFields.Count;
            namesOfThisTableFields   = "";
            odbcParametersForeignKey =
                "OdbcParameter[] ParametersArray = new OdbcParameter[" +
                AConstraint.strThisFields.Count.ToString() + "];" +
                Environment.NewLine;

            int counterKeyField = 0;

            foreach (string field in AConstraint.strThisFields)
            {
                if (counterKeyField > 0)
                {
                    whereClauseForeignKey    += " AND ";
                    whereClauseViaOtherTable += " AND ";
                    namesOfThisTableFields   += ", ";
                }

                namesOfThisTableFields += '"' + AConstraint.strThisFields[counterKeyField] + '"';

                string      otherfield      = AConstraint.strOtherFields[counterKeyField];
                TTableField otherTypedField = AOtherTable.GetField(otherfield);

                whereClauseForeignKey    += field + " = ?";
                whereClauseViaOtherTable += "PUB_" + AConstraint.strThisTable + "." + field +
                                            " = PUB_" + AConstraint.strOtherTable + "." + otherfield;

                odbcParametersForeignKey += "ParametersArray[" + counterKeyField.ToString() + "] = " +
                                            "new OdbcParameter(\"\", " + otherTypedField.ToOdbcTypeString() +
                                            (otherTypedField.iLength != -1 ? ", " +
                                             otherTypedField.iLength.ToString() : "") + ");" + Environment.NewLine;
                odbcParametersForeignKey += "ParametersArray[" + counterKeyField.ToString() + "].Value = " +
                                            "((object)(A" + TTable.NiceFieldName(otherfield) + "));" + Environment.NewLine;

                counterKeyField++;
            }
        }
        /// <summary>
        /// get formal and actual parameters for a unique or primary key
        /// </summary>
        /// <param name="ACurrentTable"></param>
        /// <param name="AConstraint"></param>
        /// <param name="formalParametersKey"></param>
        /// <param name="actualParametersKey"></param>
        /// <param name="numberKeyColumns"></param>
        /// <param name="actualParametersToString"></param>
        private static void PrepareCodeletsKey(
            TTable ACurrentTable,
            TConstraint AConstraint,
            out string formalParametersKey,
            out string actualParametersKey,
            out string actualParametersToString,
            out int numberKeyColumns)
        {
            formalParametersKey      = "";
            actualParametersKey      = "";
            actualParametersToString = "";

            numberKeyColumns = AConstraint.strThisFields.Count;

            int counterKeyField = 0;

            foreach (string field in AConstraint.strThisFields)
            {
                if (counterKeyField > 0)
                {
                    formalParametersKey      += ", ";
                    actualParametersKey      += ", ";
                    actualParametersToString += " + \" \" + ";
                }

                TTableField typedField = ACurrentTable.GetField(field);

                formalParametersKey      += typedField.GetDotNetType() + " A" + TTable.NiceFieldName(field);
                actualParametersKey      += "A" + TTable.NiceFieldName(field);
                actualParametersToString += "A" + TTable.NiceFieldName(field) + ".ToString()";

                counterKeyField++;
            }

            // for partners, show their names as well. This is used in function AddOrModifyRecord to show the users which values are different
            foreach (TTableField column in ACurrentTable.grpTableField)
            {
                if (column.strName.Contains("_name_"))
                {
                    actualParametersToString += " + ExistingRecord[0]." + TTable.NiceFieldName(column) + ".ToString()";
                }
            }
        }
Esempio n. 10
0
        /// <summary>
        /// code for generating typed datasets
        /// </summary>
        /// <param name="AInputXmlfile"></param>
        /// <param name="AOutputPath"></param>
        /// <param name="ANameSpace"></param>
        /// <param name="store"></param>
        /// <param name="groups"></param>
        /// <param name="AFilename"></param>
        public static void CreateTypedDataSets(String AInputXmlfile,
                                               String AOutputPath,
                                               String ANameSpace,
                                               TDataDefinitionStore store,
                                               string[] groups,
                                               string AFilename)
        {
            Console.WriteLine("processing dataset " + ANameSpace);

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

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

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

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

            Template.SetCodelet("NAMESPACE", ANameSpace);

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

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

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

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

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

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

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

                    XmlNode curChild = cur.FirstChild;

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

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

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

                                    OverloadTable = true;
                                }

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

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

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

                                    table.grpTableField.Add(field);

                                    OverloadTable = true;
                                }

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

                                    OverloadTable = true;
                                }

                                tableNodes = tableNodes.NextSibling;
                            }

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

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

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

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

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

                            tables.Add(variablename, table);

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

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

                            AddTableToDataset(tabletype, variablename,
                                              snippetDataset);
                        }

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

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

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

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

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

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

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

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

                                    customTable.grpTableField.Add(field);
                                }

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

                                customTableNodes = customTableNodes.NextSibling;
                            }

                            tables.Add(tabletype, customTable);

                            AddTableToDataset(tabletype, variablename, snippetDataset);

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

                        curChild = curChild.NextSibling;
                    }

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

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

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

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

                    Template.InsertSnippet("CONTENTDATASETSANDTABLESANDROWS", snippetDataset);

                    cur = TXMLParser.GetNextEntity(cur);
                }
            }

            Template.FinishWriting(AOutputPath + Path.DirectorySeparatorChar + AFilename + "-generated.cs", ".cs", true);
        }
Esempio n. 11
0
        /// <summary>
        /// write the part of the sql creation script for a specific column
        /// </summary>
        /// <param name="ATargetDatabase"></param>
        /// <param name="ATable"></param>
        /// <param name="field"></param>
        /// <param name="first"></param>
        /// <param name="AWithComments"></param>
        /// <returns></returns>
        public static string WriteField(eDatabaseType ATargetDatabase, TTable ATable, TTableField field, bool first, bool AWithComments)
        {
            string result = "";

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

            if (AWithComments)
            {
                result += Environment.NewLine;

                if (field.strDescription.Length != 0)
                {
                    result += String.Format("    -- {0}", field.strDescription.Replace("\r", " ").Replace("\n", " ")) + Environment.NewLine;
                }
            }

            if ((field.strType == "datetime") && (ATargetDatabase == eDatabaseType.PostgreSQL))
            {
                // PostgreSQL does not have type datetime
                field.strType = "timestamp";
            }

            if ((field.strType == "varchar") && (field.iLength >= 10000))
            {
                field.strType = "text";
            }

            if (field.strType == "bit")
            {
                result += String.Format("  {0} boolean", field.strName);
            }
            else if ((field.strType == "number") && (field.iLength == 10) && (field.iDecimals == -1))
            {
                result += String.Format("  {0} bigint", field.strName);
            }
            else if (field.strType == "number")
            {
                result += String.Format("  {0} numeric", field.strName);
            }
            else if (field.bAutoIncrement)
            {
                if (ATargetDatabase == eDatabaseType.PostgreSQL)
                {
                    result += String.Format("  {0} SERIAL", field.strName);
                }
                else if (ATargetDatabase == eDatabaseType.Sqlite)
                {
                    result += String.Format("  {0} INTEGER PRIMARY KEY AUTOINCREMENT ", field.strName);
                }
                else if (ATargetDatabase == eDatabaseType.MySQL)
                {
                    result += String.Format("  {0} INTEGER AUTO_INCREMENT UNIQUE ", field.strName);
                }
            }
            else
            {
                result += String.Format("  {0} {1}", field.strName, field.strType);
            }

            // According to the type we will add parameters
            if ((field.strType == "number") && (field.iLength == 10) && (field.iDecimals == -1))
            {
                // no parameter for bigints
            }
            else if ((field.strType == "varchar") || (field.strType == "number"))
            {
                if (field.iLength >= 0)
                {
                    result += String.Format("({0}", field.iLength.ToString());
                }

                if (field.strType == "number")
                {
                    result += String.Format(", {0}", (field.iDecimals > 0 ? field.iDecimals.ToString() : "0"));
                }

                result += String.Format(")");
            }

            if (field.strDefault.Length > 0)
            {
                if (field.strDefault == "NULL")
                {
                    result += String.Format(" DEFAULT {0}", field.strDefault);
                }
                else if ((field.strType == "varchar") || (field.strType == "text"))
                {
                    result += String.Format(" DEFAULT '{0}'", field.strDefault);
                }
                else if (field.strType == "bit")
                {
                    if (ATargetDatabase == eDatabaseType.MySQL)
                    {
                        result += String.Format(" DEFAULT {0}", field.strDefault);
                    }
                    else
                    {
                        result += String.Format(" DEFAULT '{0}'", field.strDefault);
                    }
                }
                else if (field.strDefault == "SYSDATE")
                {
                    // MySql cannot have a function for the default value
                    // see http://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html
                    if (ATargetDatabase != eDatabaseType.MySQL)
                    {
                        result += String.Format(" DEFAULT CURRENT_DATE");
                    }
                }
                else
                {
                    result += String.Format(" DEFAULT {0}", field.strDefault);
                }
            }

#if (!IMPORTFROMLEGACYDB)
            if (field.bNotNull)
            {
                result += String.Format(" NOT NULL");
            }

            if ((field.strCheck != null) && (field.strCheck.Length != 0))
            {
                result += String.Format(" CHECK {0}", field.strCheck);
            }
#endif

            return(result);
        }
Esempio n. 12
0
        /// <summary>
        /// convert values from Progress notation to Postgresql notation
        /// </summary>
        public static string FixValue(string AValue, TTableField ANewField)
        {
            if (ANewField.strName == "s_modification_id_t")
            {
                AValue = "\\N";
            }
            else if ((ANewField.strName == "s_created_by_c")
                     || (ANewField.strName == "s_merged_by_c")
                     || (ANewField.strName == "s_modified_by_c")
                     || (ANewField.strName == "m_manual_mod_by_c")
                     || (ANewField.strName == "p_country_of_issue_c")
                     || (ANewField.strName == "a_transaction_currency_c")
                     || (ANewField.strName == "pm_st_leadership_rating_c")
                     || (ANewField.strName == "pm_passport_details_type_c")
                     || (ANewField.strName == "p_marital_status_c")
                     || (ANewField.strName == "p_owner_c")
                     || (ANewField.strName == "s_user_id_c")
                     || (ANewField.strName == "p_relation_name_c")
                     || ANewField.strName.EndsWith("_code_c"))
            {
                AValue = AValue.Trim().ToUpper();

                if (!ANewField.bNotNull)
                {
                    if (AValue.Length == 0)
                    {
                        AValue = "\\N";
                    }
                }
            }
            else if (!ANewField.bNotNull
                     && ((ANewField.strName == "p_field_key_n")
                         || (ANewField.strName == "p_bank_key_n")
                         || (ANewField.strName == "p_partner_key_n")
                         || (ANewField.strName == "p_contact_partner_key_n")
                         || (ANewField.strName == "p_recipient_key_n")
                         || (ANewField.strName == "a_recipient_ledger_number_n")
                         || (ANewField.strName == "pm_gen_app_poss_srv_unit_key_n")
                         || (ANewField.strName == "a_ilt_processing_centre_n")
                         || (ANewField.strName == "pm_st_field_charged_n")
                         || (ANewField.strName == "pm_st_current_field_n")
                         || (ANewField.strName == "pm_st_option2_n")
                         || (ANewField.strName == "pm_st_option1_n")
                         || (ANewField.strName == "pm_st_confirmed_option_n")
                         || (ANewField.strName == "pm_office_recruited_by_n")
                         || (ANewField.strName == "pm_home_office_n")
                         || (ANewField.strName == "p_primary_office_n")
                         || (ANewField.strName == "p_value_partner_key_n")
                         || (ANewField.strName == "pm_receiving_field_office_n")
                         || (ANewField.strName == "a_key_ministry_key_n")
                         || (ANewField.strName == "pm_placement_partner_key_n")
                         || (ANewField.strName == "pm_contact_partner_key_n")
                         ))
            {
                if (AValue == "0")
                {
                    AValue = "\\N";
                }
            }
            else if (!ANewField.bNotNull
                     && ((ANewField.strName == "pt_qualification_area_name_c")
                         || (ANewField.strName == "pm_passport_details_type_c")
                         ))
            {
                if (AValue == "")
                {
                    AValue = "\\N";
                }
            }
            else if ((AValue.Length == 0) && ANewField.strType.Equals("VARCHAR", StringComparison.OrdinalIgnoreCase) && !ANewField.bNotNull)
            {
                AValue = "\\N";
            }
            else if (ANewField.strType.Equals("BIT", StringComparison.OrdinalIgnoreCase))
            {
                AValue = (AValue == "yes") ? "1" : "0";
            }
            else if (ANewField.strType.Equals("DATE", StringComparison.OrdinalIgnoreCase))
            {
                if ((AValue.Length > 0) && (AValue != "\\N"))
                {
                    if (AValue.Length != 10)
                    {
                        TLogging.Log("WARNING: Invalid date: " + ANewField.strName + " " + AValue);
                        AValue = "\\N";
                    }
                    else
                    {
                        // fulldump23.p does write all dates in format dmy
                        // 15/04/2010 => 2010-04-15
                        AValue = string.Format("{0}-{1}-{2}", AValue.Substring(6, 4), AValue.Substring(3, 2), AValue.Substring(0, 2));
                    }
                }
            }

            return AValue;
        }
Esempio n. 13
0
        /// <summary>
        /// load the dataset tables
        /// </summary>
        public static SortedList <string, TTable>LoadDatasetTables(string AICTPath, string ADataSetTypeWithNamespace, TCodeStorage ACodeStorage,
            string APluginPath)
        {
            if (FDatasetTables == null)
            {
                FDatasetTables = new SortedList <string, SortedList <string, TTable>>();
            }

            FCodeStorage = ACodeStorage;

            if (!ADataSetTypeWithNamespace.StartsWith("Ict.Petra.Shared") && !ADataSetTypeWithNamespace.StartsWith("Ict.Petra.Plugins"))
            {
                throw new Exception("the DatasetType must contain the full namespace, starting with Ict.Petra.Shared or Ict.Petra.Plugins");
            }

            if (FDatasetTables.ContainsKey(ADataSetTypeWithNamespace))
            {
                FCurrentDataset = FDatasetTables[ADataSetTypeWithNamespace];

                return FCurrentDataset;
            }

            string[] datasetTypeSplit = ADataSetTypeWithNamespace.Split(new char[] { '.' });
            string module = datasetTypeSplit[3];
            string datasetName = datasetTypeSplit[datasetTypeSplit.Length - 1];

            // find the correct xml file for the dataset.
            // look in Ict/Petra/Shared/lib/MODULE/data
            string dataPath = AICTPath + "/Petra/Shared/lib/" + module + "/data/";

            if (ADataSetTypeWithNamespace.StartsWith("Ict.Petra.Plugins"))
            {
                int start = "Ict.Petra.Plugins.".Length;
                int end = ADataSetTypeWithNamespace.IndexOf(".", start);
                string PluginName = ADataSetTypeWithNamespace.Substring(start, end - start);
                dataPath = AICTPath + "/Petra/Plugins/" + PluginName + "/data/";
            }

            DirectoryInfo directory = new DirectoryInfo(dataPath);
            FileInfo[] xmlFiles = directory.GetFiles("*.xml");
            XmlNode datasetNode = null;

            foreach (FileInfo fileinfo in xmlFiles)
            {
                if (datasetNode == null)
                {
                    TXMLParser parser = new TXMLParser(dataPath + "/" + fileinfo.Name, false);
                    datasetNode = parser.GetDocument().SelectSingleNode(String.Format("//DataSet[@name='{0}']", datasetName));
                }
            }

            if ((datasetNode == null) && File.Exists(APluginPath))
            {
                // also check the plugin directory of the yaml file, for plugins can have a file TypedDataSets.xml
                TXMLParser parser = new TXMLParser(APluginPath, false);
                datasetNode = parser.GetDocument().SelectSingleNode(String.Format("//DataSet[@name='{0}']", datasetName));
            }

            if (datasetNode == null)
            {
                throw new Exception("cannot find the xml file for dataset " + ADataSetTypeWithNamespace);
            }

            SortedList <string, TTable>result = new SortedList <string, TTable>();
            XmlNodeList tables = datasetNode.SelectNodes("Table|CustomTable");

            foreach (XmlNode tableNode in tables)
            {
                TTable table = new TTable();
                string tablename;

                if ((tableNode.Name == "Table") && TXMLParser.HasAttribute(tableNode, "sqltable"))
                {
                    tablename = TTable.NiceTableName(tableNode.Attributes["sqltable"].Value);
                    table.Assign(FPetraXMLStore.GetTable(tablename));

                    table.strVariableNameInDataset = TXMLParser.HasAttribute(tableNode, "name") ? tableNode.Attributes["name"].Value : tablename;

                    if ((tableNode.SelectNodes("CustomField").Count > 0) || (tableNode.SelectNodes("Field").Count > 0))
                    {
                        table.strDotNetName = datasetName + tablename;
                    }
                }
                else if ((tableNode.Name == "Table") && TXMLParser.HasAttribute(tableNode, "customtable"))
                {
                    table = new TTable();
                    tablename = tableNode.Attributes["customtable"].Value;
                    table.strName = tablename;
                    table.strDotNetName = tablename;
                    table.strVariableNameInDataset = TXMLParser.HasAttribute(tableNode, "name") ? tableNode.Attributes["name"].Value : tablename;
                }
                else
                {
                    table = new TTable();
                    tablename = tableNode.Attributes["name"].Value;
                    table.strName = tablename;
                    table.strDotNetName = datasetName + tablename;
                    table.strVariableNameInDataset = tablename;
                }

                // add the custom fields if there are any
                XmlNodeList customFields = tableNode.SelectNodes("CustomField");

                foreach (XmlNode customField in customFields)
                {
                    TTableField newField = new TTableField();
                    newField.strName = customField.Attributes["name"].Value;
                    newField.strNameDotNet = newField.strName;
                    newField.strType = customField.Attributes["type"].Value;
                    newField.strTypeDotNet = customField.Attributes["type"].Value;
                    newField.strTableName = tablename;
                    newField.strDescription = "";
                    newField.bNotNull =
                        TXMLParser.HasAttribute(customField, "notnull") && TXMLParser.GetAttribute(customField, "notnull").ToLower() == "true";
                    table.grpTableField.Add(newField);
                }

                // add other fields from other tables that are defined in petra.xml
                XmlNodeList otherFields = tableNode.SelectNodes("Field");

                foreach (XmlNode otherField in otherFields)
                {
                    TTable otherTable = FPetraXMLStore.GetTable(otherField.Attributes["sqltable"].Value);
                    TTableField newField = new TTableField(otherTable.GetField(otherField.Attributes["sqlfield"].Value));

                    if (TXMLParser.HasAttribute(otherField, "name"))
                    {
                        newField.strNameDotNet = otherField.Attributes["name"].Value;
                    }

                    newField.strTableName = tablename;
                    table.grpTableField.Add(newField);
                }

                result.Add(table.strVariableNameInDataset, table);
            }

            FDatasetTables.Add(ADataSetTypeWithNamespace, result);
            FCurrentDataset = result;
            return result;
        }
Esempio n. 14
0
 /// <summary>
 /// convert an sql type from our xml file into a dotnet type.
 /// should also work for Convert.To&lt;DotNetType&gt;
 /// </summary>
 /// <param name="tableField"></param>
 /// <returns></returns>
 public static string ToDotNetType(TTableField tableField)
 {
     return(tableField.GetDotNetType());
 }
Esempio n. 15
0
        /// <summary>
        /// Generates code for the SHOWDATA Snippet.
        /// </summary>
        /// <param name="fieldname">Name of field</param>
        /// <param name="RowName">Name of row</param>
        /// <param name="TestForNullTable"></param>
        /// <param name="writer">FormWriter instance.</param>
        /// <param name="ctrl">TControlDef instance.</param>
        /// <param name="AField">TTableField instance.</param>
        /// <returns>A <see cref="ProcessTemplate"></see>.</returns>
        ProcessTemplate GenerateShowDataSnippetCode(ref string fieldname,
            ref string RowName,
            ref string TestForNullTable,
            TFormWriter writer,
            TControlDef ctrl,
            TTableField AField)
        {
            ProcessTemplate snippetShowData = writer.Template.GetSnippet("SHOWDATAFORCOLUMN");

            if (AField.GetDotNetType().ToLower().Contains("string"))
            {
                snippetShowData.SetCodelet("SETVALUEORNULL", "{#SETCONTROLVALUE}");
                snippetShowData.SetCodelet("SETROWVALUEORNULL", "{#SETROWVALUE}");
            }
            else
            {
                snippetShowData.InsertSnippet("SETVALUEORNULL", writer.Template.GetSnippet("SETVALUEORNULL"));
                snippetShowData.InsertSnippet("SETROWVALUEORNULL", writer.Template.GetSnippet("SETROWVALUEORNULL"));
            }

            snippetShowData.SetCodelet("CANBENULL", !AField.bNotNull ? "yes" : "");
            snippetShowData.SetCodelet("DETERMINECONTROLISNULL", this.GetControlValue(ctrl, null));
            snippetShowData.SetCodelet("NOTDEFAULTTABLE", TestForNullTable);
            snippetShowData.SetCodelet("ROW", RowName);
            snippetShowData.SetCodelet("COLUMNNAME", fieldname);
            snippetShowData.SetCodelet("SETNULLVALUE", this.AssignValue(ctrl, null, null));
            snippetShowData.SetCodelet("SETCONTROLVALUE", this.AssignValue(ctrl, RowName + "." + fieldname, AField.GetDotNetType()));
            snippetShowData.InsertSnippet("SETROWVALUE", writer.Template.GetSnippet("SETROWVALUE"));

            return snippetShowData;
        }
Esempio n. 16
0
        private void DataFieldUndoCapability(TFormWriter writer, TControlDef ctrl, TTableField AField, bool AIsDetailNotMaster)
        {
            if (AField == null)
            {
                return;
            }

            string tablename = TTable.NiceTableName(AField.strTableName);
            string fieldname = TTable.NiceFieldName(AField);
            string TestForNullTable = "FMainDS." + tablename;

            if ((tablename == writer.CodeStorage.GetAttribute("DetailTable")) || (tablename == writer.CodeStorage.GetAttribute("MasterTable")))
            {
                TestForNullTable = "";
            }

            string targetCodelet = "UNDODATA";

            ProcessTemplate snippetShowData = GenerateUndoDataSnippetCode(ref tablename, ref fieldname, ref TestForNullTable, writer, ctrl, AField);

            writer.Template.InsertSnippet(targetCodelet, snippetShowData);
        }
Esempio n. 17
0
 /// <summary>
 /// convert an sql type from our xml file into a dotnet type.
 /// should also work for Convert.To&lt;DotNetType&gt;
 /// </summary>
 /// <param name="tableField"></param>
 /// <returns></returns>
 public static string ToDotNetType(TTableField tableField)
 {
     return tableField.GetDotNetType();
 }
Esempio n. 18
0
        /// <summary>write the code for the designer file where the properties of the control are written</summary>
        public override ProcessTemplate SetControlProperties(TFormWriter writer, TControlDef ctrl)
        {
            if (!ctrl.HasAttribute("Width"))
            {
                ctrl.SetAttribute("Width", FDefaultWidth.ToString());
            }

            base.SetControlProperties(writer, ctrl);

            writer.Template.AddToCodelet("INITMANUALCODE", ctrl.controlName + ".CancelEditingWithEscapeKey = false;" + Environment.NewLine);

            if (TYml2Xml.HasAttribute(ctrl.xmlNode, "SelectedRowActivates"))
            {
                // TODO: this function needs to be called by the manual code at the moment when eg a search finishes
                // TODO: call "Activate" + TYml2Xml.GetAttribute(ctrl.xmlNode, "SelectedRowActivates")
            }

            StringCollection Columns = TYml2Xml.GetElements(ctrl.xmlNode, "Columns");

            if (Columns.Count > 0)
            {
                writer.Template.AddToCodelet("INITMANUALCODE", ctrl.controlName + ".Columns.Clear();" + Environment.NewLine);

                //This needs to come immediately after the Columns.Clear() and before the creation of the columns
                if (ctrl.HasAttribute("SortableHeaders"))
                {
                    string trueOrFalse = ctrl.GetAttribute("SortableHeaders");
                    writer.Template.AddToCodelet("INITMANUALCODE", ctrl.controlName + ".SortableHeaders = " + trueOrFalse + ";" + Environment.NewLine);
                }

                foreach (string ColumnFieldName in Columns)
                {
                    bool        IsDetailNotMaster;
                    TTableField field = null;
                    string      TableFieldTable;
                    string      ColumnFieldNameResolved;

                    // customfield, eg. UC_GLTransactions, ATransaction.DateEntered and ATransaction.AnalysisAttributes
                    // there needs to be a list of CustomColumns
                    XmlNode CustomColumnsNode = TYml2Xml.GetChild(ctrl.xmlNode, "CustomColumns");
                    XmlNode CustomColumnNode  = null;

                    if (CustomColumnsNode != null)
                    {
                        CustomColumnNode = TYml2Xml.GetChild(CustomColumnsNode, ColumnFieldName);
                    }

                    if ((ctrl.controlName == "grdDetails") && FCodeStorage.HasAttribute("DetailTable"))
                    {
                        TableFieldTable = FCodeStorage.GetAttribute("DetailTable");

                        if (ColumnFieldName.StartsWith("Detail") && !IsLegitimateDetailFieldName(TableFieldTable, ColumnFieldName))
                        {
                            ColumnFieldNameResolved = ColumnFieldName.Substring(6);     // Drop 'Details' out of 'Details...'
                        }
                        else
                        {
                            ColumnFieldNameResolved = ColumnFieldName;
                        }
                    }
                    else
                    {
                        TableFieldTable         = ctrl.GetAttribute("TableName");
                        ColumnFieldNameResolved = ColumnFieldName;
                    }

                    if (CustomColumnNode != null)
                    {
                        // if grd has no TableName property
                        if ((TableFieldTable == "") && ColumnFieldNameResolved.Contains("."))
                        {
                            int    Period     = ColumnFieldNameResolved.IndexOf(".");
                            string TableName  = ColumnFieldNameResolved.Remove(Period);
                            string ColumnName = ColumnFieldNameResolved.Remove(0, TableName.Length + 1);

                            AddColumnToGrid(writer, ctrl.controlName,
                                            TYml2Xml.GetAttribute(CustomColumnNode, "Type"),
                                            TYml2Xml.GetAttribute(CustomColumnNode, "Label"),
                                            TYml2Xml.GetAttribute(CustomColumnNode, "Tooltip"),
                                            TableName,
                                            ColumnName);
                        }
                        else
                        {
                            AddColumnToGrid(writer, ctrl.controlName,
                                            TYml2Xml.GetAttribute(CustomColumnNode, "Type"),
                                            TYml2Xml.GetAttribute(CustomColumnNode, "Label"),
                                            TYml2Xml.GetAttribute(CustomColumnNode, "Tooltip"),
                                            TableFieldTable,
                                            ColumnFieldNameResolved);
                        }
                    }
                    else if (ctrl.HasAttribute("TableName"))
                    {
                        field =
                            TDataBinding.GetTableField(null, ctrl.GetAttribute("TableName") + "." + ColumnFieldName, out IsDetailNotMaster,
                                                       true);
                    }
                    else
                    {
                        field = TDataBinding.GetTableField(null, ColumnFieldName, out IsDetailNotMaster, true);
                    }

                    if (field != null)
                    {
                        AddColumnToGrid(writer, ctrl.controlName,
                                        field.iDecimals == 10 && field.iLength == 24 ? "Decimal" : field.GetDotNetType(),
                                        field.strLabel.Length > 0 ? field.strLabel : field.strName,
                                        String.Empty,
                                        TTable.NiceTableName(field.strTableName),
                                        TTable.NiceFieldName(field.strName));
                    }
                }
            }
            else
            {
                //If no columns, but the user is able to add columns dynamically during the running of the form, then need this here.
                if (ctrl.HasAttribute("SortableHeaders"))
                {
                    string trueOrFalse = ctrl.GetAttribute("SortableHeaders");
                    writer.Template.AddToCodelet("INITMANUALCODE", ctrl.controlName + ".SortableHeaders = " + trueOrFalse + ";" + Environment.NewLine);
                }
            }

            if (ctrl.controlName != "grdDetails")
            {
                if (ctrl.HasAttribute("ActionLeavingRow"))
                {
                    AssignEventHandlerToControl(writer, ctrl, "Selection.FocusRowLeaving", "SourceGrid.RowCancelEventHandler",
                                                ctrl.GetAttribute("ActionLeavingRow"));
                }

                if (ctrl.HasAttribute("ActionFocusRow"))
                {
                    AssignEventHandlerToControl(writer, ctrl, "Selection.FocusRowEntered", "SourceGrid.RowEventHandler",
                                                ctrl.GetAttribute("ActionFocusRow"));
                }
            }

            if (ctrl.HasAttribute("ActionEnterKeyPressed"))
            {
                AssignEventHandlerToControl(writer, ctrl, "EnterKeyPressed", "TKeyPressedEventHandler",
                                            ctrl.GetAttribute("ActionEnterKeyPressed"));
            }

            if ((ctrl.controlName == "grdDetails") && FCodeStorage.HasAttribute("DetailTable"))
            {
                writer.Template.AddToCodelet("SHOWDATA", "");

                if (ctrl.HasAttribute("SortOrder"))
                {
                    // SortOrder is comma separated and has DESC or ASC after the column name
                    string SortOrder = ctrl.GetAttribute("SortOrder");

                    foreach (string SortOrderPart in SortOrder.Split(','))
                    {
                        bool        temp;
                        TTableField field = null;

                        if ((SortOrderPart.Split(' ')[0].IndexOf(".") == -1) && ctrl.HasAttribute("TableName"))
                        {
                            field = TDataBinding.GetTableField(null, ctrl.GetAttribute("TableName") + "." + SortOrderPart.Split(
                                                                   ' ')[0], out temp, true);
                        }
                        else
                        {
                            field =
                                TDataBinding.GetTableField(
                                    null,
                                    SortOrderPart.Split(' ')[0],
                                    out temp, true);
                        }

                        if (field != null)
                        {
                            SortOrder = SortOrder.Replace(SortOrderPart.Split(' ')[0], field.strName);
                        }
                    }

                    writer.Template.AddToCodelet("GRIDSORT", SortOrder);
                }

                if (ctrl.HasAttribute("RowFilter"))
                {
                    // this references a field in the table, and assumes there exists a local variable with the same name
                    // eg. FBatchNumber in GL Journals
                    string RowFilter = ctrl.GetAttribute("RowFilter");

                    String FilterString = "\"";

                    foreach (string RowFilterPart in RowFilter.Split(','))
                    {
                        bool   temp;
                        string columnName =
                            TDataBinding.GetTableField(
                                null,
                                RowFilterPart,
                                out temp, true).strName;

                        if (FilterString.Length > 1)
                        {
                            FilterString += " + \" and ";
                        }

                        FilterString += columnName + " = \" + F" + TTable.NiceFieldName(columnName) + ".ToString()";
                    }

                    writer.Template.AddToCodelet("GRIDFILTER", FilterString);
                }
            }

            if (ctrl.controlName == "grdDetails")
            {
                if (ctrl.HasAttribute("EnableMultiSelection"))
                {
                    writer.Template.SetCodelet("GRIDMULTISELECTION",
                                               String.Format("grdDetails.Selection.EnableMultiSelection = {0};{1}", ctrl.GetAttribute("EnableMultiSelection"),
                                                             Environment.NewLine));
                }
                else if (FCodeStorage.FControlList.ContainsKey("btnDelete"))
                {
                    writer.Template.SetCodelet("GRIDMULTISELECTION",
                                               "grdDetails.Selection.EnableMultiSelection = true;" + Environment.NewLine);
                }
            }

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

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

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

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

            Template.SetCodelet("NAMESPACE", ANameSpace);

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

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

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

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

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

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

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

                    XmlNode curChild = cur.FirstChild;

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

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

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

                                    OverloadTable = true;
                                }

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

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

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

                                    table.grpTableField.Add(field);

                                    OverloadTable = true;
                                }

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

                                    OverloadTable = true;
                                }

                                tableNodes = tableNodes.NextSibling;
                            }

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

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

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

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

                                // TODO: can we derive from the base table, and just overload a few functions?
                                CodeGenerationTable.InsertTableDefinition(snippetDataset, table, store.GetTable(table.tableorig), "TABLELOOP");
                                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);
        }
Esempio n. 20
0
        /// <summary>
        /// Determines whether automatic Data Validation code should be created for a certain DB Table Field.
        /// </summary>
        /// <param name="ADBField">DB Field.</param>
        /// <param name="AScope">Scope of the Data Validation that should be checked for. Specify <see cref="TAutomDataValidationScope.advsAll"/>
        /// to find out if any of the scopes should be checked against, or use any other value of that enum to specifiy a specific scope.</param>
        /// <param name="AConstraintsGroup">The constraints for the table associated with this column. Can be null unless this is doing table
        /// validation rather than control validation</param>
        /// <param name="AReasonForAutomValidation">Contains the reason why automatic data validation code needs to be generated.</param>
        /// <returns>True if automatic Data Validation code should be created for the DB Table Field passed in in <paramref name="ADBField" /> for
        /// the scope that was specified with <paramref name="AScope" />, otherwise false.</returns>
        public static bool GenerateAutoValidationCodeForDBTableField(TTableField ADBField,
                                                                     TAutomDataValidationScope AScope,
                                                                     List <TConstraint> AConstraintsGroup,
                                                                     out string AReasonForAutomValidation)
        {
            AReasonForAutomValidation = String.Empty;

            // NOT NULL checks
            if ((AScope == TAutomDataValidationScope.advsNotNullChecks) ||
                (AScope == TAutomDataValidationScope.advsAll))
            {
                if (ADBField.bPartOfPrimKey)
                {
                    AReasonForAutomValidation = "must have a value (it is part of the Primary Key)";

                    if ((ADBField.strType == "varchar") || (ADBField.strType == "text"))
                    {
                        AReasonForAutomValidation += " and must not be an empty string";
                    }

                    return(true);
                }
                else if (ADBField.bNotNull)
                {
                    AReasonForAutomValidation = "must have a value (NOT NULL constraint)";

                    // If it is a string and is a foreign key then the string cannot be empty
                    if (((ADBField.strType == "varchar") || (ADBField.strType == "text")) && (AConstraintsGroup != null))
                    {
                        foreach (TConstraint c in AConstraintsGroup)
                        {
                            if ((c.strType == "foreignkey") && (c.strThisFields.Contains(ADBField.strName)))
                            {
                                // Empty String is not allowed because it isn't allowed in the foreign table
                                AReasonForAutomValidation += " and must not be an empty string (Foreign Key constraint)";
                                break;
                            }
                        }
                    }

                    return(true);
                }
            }

            // Date checks
            if ((AScope == TAutomDataValidationScope.advsDateChecks) ||
                (AScope == TAutomDataValidationScope.advsAll))
            {
                if (ADBField.strType == "date")
                {
                    AReasonForAutomValidation = "must represent a valid date";

                    return(true);
                }
            }

            // String Length checks
            if ((AScope == TAutomDataValidationScope.advsStringLengthChecks) ||
                (AScope == TAutomDataValidationScope.advsAll))
            {
                if (((ADBField.strType == "varchar") || (ADBField.strType == "text")) &&
                    ((ADBField.strName != "s_created_by_c") &&
                     (ADBField.strName != "s_modified_by_c")))
                {
                    AReasonForAutomValidation = "must not contain more than " + (ADBField.iCharLength * 2).ToString() + " characters";

                    return(true);
                }
            }

            // Number Range checks
            if ((AScope == TAutomDataValidationScope.advsNumberRangeChecks) ||
                (AScope == TAutomDataValidationScope.advsAll))
            {
                if (ADBField.strType == "number")
                {
                    if (ADBField.iDecimals > 0)
                    {
                        AReasonForAutomValidation = "must not have more than " +
                                                    (ADBField.iLength -
                                                     ADBField.iDecimals).ToString() + " digits before the decimal point and not more than " +
                                                    ADBField.iDecimals.ToString() +
                                                    " after the decimal point";
                    }
                    else
                    {
                        AReasonForAutomValidation = "must not have more than " + ADBField.iLength.ToString() + " digits and no decimals";
                    }

                    return(true);
                }
            }

            return(false);
        }
Esempio n. 21
0
        /// <summary>write the code for the designer file where the properties of the control are written</summary>
        public override ProcessTemplate SetControlProperties(TFormWriter writer, TControlDef ctrl)
        {
            if (!ctrl.HasAttribute("Width"))
            {
                ctrl.SetAttribute("Width", FDefaultWidth.ToString());
            }

            base.SetControlProperties(writer, ctrl);

            writer.Template.AddToCodelet("INITMANUALCODE", ctrl.controlName + ".CancelEditingWithEscapeKey = false;" + Environment.NewLine);

            if (TYml2Xml.HasAttribute(ctrl.xmlNode, "SelectedRowActivates"))
            {
                // TODO: this function needs to be called by the manual code at the moment when eg a search finishes
                // TODO: call "Activate" + TYml2Xml.GetAttribute(ctrl.xmlNode, "SelectedRowActivates")
            }

            StringCollection Columns = TYml2Xml.GetElements(ctrl.xmlNode, "Columns");

            if (Columns.Count > 0)
            {
                writer.Template.AddToCodelet("INITMANUALCODE", ctrl.controlName + ".Columns.Clear();" + Environment.NewLine);

                //This needs to come immediately after the Columns.Clear() and before the creation of the columns
                if (ctrl.HasAttribute("SortableHeaders"))
                {
                    string trueOrFalse = ctrl.GetAttribute("SortableHeaders");
                    writer.Template.AddToCodelet("INITMANUALCODE", ctrl.controlName + ".SortableHeaders = " + trueOrFalse + ";" + Environment.NewLine);
                }

                bool isFirstColumnVarchar = false;
                bool doneFirstColumn      = false;

                foreach (string ColumnFieldName in Columns)
                {
                    bool        IsDetailNotMaster;
                    TTableField field = null;
                    string      TableFieldTable;
                    string      ColumnFieldNameResolved;

                    // customfield, eg. UC_GLTransactions, ATransaction.DateEntered and ATransaction.AnalysisAttributes
                    // there needs to be a list of CustomColumns
                    XmlNode CustomColumnsNode = TYml2Xml.GetChild(ctrl.xmlNode, "CustomColumns");
                    XmlNode CustomColumnNode  = null;

                    if (CustomColumnsNode != null)
                    {
                        CustomColumnNode = TYml2Xml.GetChild(CustomColumnsNode, ColumnFieldName);
                    }

                    if ((ctrl.controlName == "grdDetails") && FCodeStorage.HasAttribute("DetailTable"))
                    {
                        TableFieldTable = FCodeStorage.GetAttribute("DetailTable");

                        if (ColumnFieldName.StartsWith("Detail") && !IsLegitimateDetailFieldName(TableFieldTable, ColumnFieldName))
                        {
                            ColumnFieldNameResolved = ColumnFieldName.Substring(6);     // Drop 'Details' out of 'Details...'
                        }
                        else
                        {
                            ColumnFieldNameResolved = ColumnFieldName;
                        }
                    }
                    else
                    {
                        TableFieldTable         = ctrl.GetAttribute("TableName");
                        ColumnFieldNameResolved = ColumnFieldName;
                    }

                    if (CustomColumnNode != null)
                    {
                        TTableField tf = null;

                        // if grd has no TableName property
                        if ((TableFieldTable == "") && ColumnFieldNameResolved.Contains("."))
                        {
                            int    Period     = ColumnFieldNameResolved.IndexOf(".");
                            string TableName  = ColumnFieldNameResolved.Remove(Period);
                            string ColumnName = ColumnFieldNameResolved.Remove(0, TableName.Length + 1);

                            AddColumnToGrid(writer, ctrl.controlName,
                                            TYml2Xml.GetAttribute(CustomColumnNode, "Type"),
                                            TYml2Xml.GetAttribute(CustomColumnNode, "Label"),
                                            TYml2Xml.GetAttribute(CustomColumnNode, "Tooltip"),
                                            TableName,
                                            ColumnName);
                            tf = TDataBinding.GetTableField(null, TableName + "." + ColumnName, out IsDetailNotMaster, true);
                        }
                        else
                        {
                            AddColumnToGrid(writer, ctrl.controlName,
                                            TYml2Xml.GetAttribute(CustomColumnNode, "Type"),
                                            TYml2Xml.GetAttribute(CustomColumnNode, "Label"),
                                            TYml2Xml.GetAttribute(CustomColumnNode, "Tooltip"),
                                            TableFieldTable,
                                            ColumnFieldNameResolved);
                            tf = TDataBinding.GetTableField(null, TableFieldTable + "." + ColumnFieldNameResolved, out IsDetailNotMaster, true);
                        }

                        if (!doneFirstColumn)
                        {
                            isFirstColumnVarchar = tf.strName.EndsWith("_c");
                            doneFirstColumn      = true;
                        }
                    }
                    else if (ctrl.HasAttribute("TableName"))
                    {
                        field = TDataBinding.GetTableField(null, ctrl.GetAttribute("TableName") + "." + ColumnFieldName,
                                                           out IsDetailNotMaster, true);
                    }
                    else
                    {
                        field = TDataBinding.GetTableField(null, ColumnFieldName, out IsDetailNotMaster, true);
                    }

                    if (field != null)
                    {
                        AddColumnToGrid(writer, ctrl.controlName,
                                        field.iDecimals == 10 && field.iLength == 24 ? "Decimal" : field.GetDotNetType(),
                                        field.strLabel.Length > 0 ? field.strLabel : field.strName,
                                        String.Empty,
                                        TTable.NiceTableName(field.strTableName),
                                        TTable.NiceFieldName(field.strName));

                        if (!doneFirstColumn)
                        {
                            isFirstColumnVarchar = field.strName.EndsWith("_c");
                            doneFirstColumn      = true;
                        }
                    }
                }

                if (FControlType == TYPE_DATA_GRID_NON_PAGED)
                {
                    // Grid AutoFind definition (not allowed in paged grids)
                    string autoFindStr = ctrl.controlName + ".AutoFindMode = TAutoFindModeEnum.";
                    string mode        = "NoAutoFind";

                    if (ctrl.HasAttribute("AutoFindMode"))
                    {
                        // Use the specified value in YAML
                        mode = ctrl.GetAttribute("AutoFindMode");
                        TLogging.Log("Info: AutoFindMode (with columns) was set to " + mode + " from explicit YAML attribute: " + ctrl.controlName);
                    }
                    else if (isFirstColumnVarchar)
                    {
                        // We can use auto-find because we have a first column based on a varchar
                        mode = "FirstCharacter";
                        TLogging.Log("Info: AutoFindMode (with columns) was set implicitly for: " + ctrl.controlName);
                    }
                    else
                    {
                        TLogging.Log("Info: AutoFindMode (with columns) was set to NoAutoFind for: " + ctrl.controlName);
                    }

                    writer.Template.AddToCodelet("INITMANUALCODE", autoFindStr + mode + ";" + Environment.NewLine);

                    if (ctrl.HasAttribute("AutoFindColumn"))
                    {
                        string colNum = ctrl.GetAttribute("AutoFindColumn");
                        writer.Template.AddToCodelet("INITMANUALCODE",
                                                     ctrl.controlName + ".AutoFindColumn = " + colNum + ";" + Environment.NewLine);
                        TLogging.Log("Info: AutoFindColumn was set to " + colNum + " for: " + ctrl.controlName);
                    }

                    if ((mode == "FirstCharacter") && !ctrl.HasAttribute("SortOrder"))
                    {
                        TLogging.Log("Info: AutoFind has been turned on for a grid with no YAML-defined sort order: (" + ctrl.controlName +
                                     "). You can remove this message by explicitly setting a SortOrder in the YAML file.");
                    }
                }
            }
            else
            {
                //If no columns, but the user is able to add columns dynamically during the running of the form, then need this here.
                if (ctrl.HasAttribute("SortableHeaders"))
                {
                    string trueOrFalse = ctrl.GetAttribute("SortableHeaders");
                    writer.Template.AddToCodelet("INITMANUALCODE", ctrl.controlName + ".SortableHeaders = " + trueOrFalse + ";" + Environment.NewLine);
                }

                if (FControlType == TYPE_DATA_GRID_NON_PAGED)
                {
                    // Grid AutoFind definition (not allowed in paged grids)
                    string autoFindStr = ctrl.controlName + ".AutoFindMode = TAutoFindModeEnum.";
                    string mode        = "FirstCharacter";

                    if (ctrl.HasAttribute("AutoFindMode"))
                    {
                        // Use the specified value in YAML
                        mode = ctrl.GetAttribute("AutoFindMode");
                        TLogging.Log("Info: AutoFindMode (without columns) was set to " + mode + " from explicit YAML attribute: " + ctrl.controlName);
                    }
                    else if (writer.FCodeStorage.ManualFileExistsAndContains(ctrl.controlName + ".AddTextColumn("))
                    {
                        // We presume can use auto-find because we have a column (maybe the first) based on a varchar
                        TLogging.Log("Info: AutoFindMode (without columns) was set implicitly for: " + ctrl.controlName);
                    }
                    else
                    {
                        mode = "NoAutoFind";
                        TLogging.Log("Info: AutoFindMode (without columns) was set to NoAutoFind for: " + ctrl.controlName);
                    }

                    writer.Template.AddToCodelet("INITMANUALCODE", autoFindStr + mode + ";" + Environment.NewLine);

                    if (ctrl.HasAttribute("AutoFindColumn"))
                    {
                        string colNum = ctrl.GetAttribute("AutoFindColumn");
                        writer.Template.AddToCodelet("INITMANUALCODE",
                                                     ctrl.controlName + ".AutoFindColumn = " + colNum + ";" + Environment.NewLine);
                        TLogging.Log("Info: AutoFindColumn was set to " + colNum + " for: " + ctrl.controlName);
                    }
                }
            }

            if (ctrl.controlName != "grdDetails")
            {
                if (ctrl.HasAttribute("ActionLeavingRow"))
                {
                    AssignEventHandlerToControl(writer, ctrl, "Selection.FocusRowLeaving", "SourceGrid.RowCancelEventHandler",
                                                ctrl.GetAttribute("ActionLeavingRow"));
                }

                if (ctrl.HasAttribute("ActionFocusRow"))
                {
                    AssignEventHandlerToControl(writer, ctrl, "Selection.FocusRowEntered", "SourceGrid.RowEventHandler",
                                                ctrl.GetAttribute("ActionFocusRow"));
                }
            }

            if (ctrl.HasAttribute("ActionEnterKeyPressed"))
            {
                AssignEventHandlerToControl(writer, ctrl, "EnterKeyPressed", "TKeyPressedEventHandler",
                                            ctrl.GetAttribute("ActionEnterKeyPressed"));
            }

            if ((ctrl.controlName == "grdDetails") && FCodeStorage.HasAttribute("DetailTable"))
            {
                writer.Template.AddToCodelet("SHOWDATA", "");

                if (ctrl.HasAttribute("SortOrder"))
                {
                    // SortOrder is comma separated and has DESC or ASC after the column name
                    string SortOrder = ctrl.GetAttribute("SortOrder");

                    foreach (string SortOrderPart in SortOrder.Split(','))
                    {
                        bool        temp;
                        TTableField field          = null;
                        string      columnNamePart = SortOrderPart.Split(' ')[0];

                        if ((columnNamePart.IndexOf(".") == -1) && ctrl.HasAttribute("TableName"))
                        {
                            field = TDataBinding.GetTableField(null, ctrl.GetAttribute("TableName") + "." + columnNamePart, out temp, true);
                        }
                        else
                        {
                            field = TDataBinding.GetTableField(null, columnNamePart, out temp, true);
                        }

                        if (field != null)
                        {
                            SortOrder = SortOrder.Replace(columnNamePart, field.strName);
                        }
                    }

                    writer.Template.AddToCodelet("GRIDSORT", SortOrder);
                }

                if (ctrl.HasAttribute("RowFilter"))
                {
                    // this references a field in the table, and assumes there exists a local variable with the same name
                    // eg. FBatchNumber in GL Journals
                    string RowFilter = ctrl.GetAttribute("RowFilter");

                    String FilterString = "\"";

                    foreach (string RowFilterPart in RowFilter.Split(','))
                    {
                        bool   temp;
                        string columnName =
                            TDataBinding.GetTableField(
                                null,
                                RowFilterPart,
                                out temp, true).strName;

                        if (FilterString.Length > 1)
                        {
                            FilterString += " + \" and ";
                        }

                        FilterString += columnName + " = \" + F" + TTable.NiceFieldName(columnName) + ".ToString()";
                    }

                    writer.Template.AddToCodelet("GRIDFILTER", FilterString);
                }
            }

            if (ctrl.controlName == "grdDetails")
            {
                if (ctrl.HasAttribute("EnableMultiSelection"))
                {
                    writer.Template.SetCodelet("GRIDMULTISELECTION",
                                               String.Format("grdDetails.Selection.EnableMultiSelection = {0};{1}", ctrl.GetAttribute("EnableMultiSelection"),
                                                             Environment.NewLine));
                }
                else if (FCodeStorage.FControlList.ContainsKey("btnDelete"))
                {
                    writer.Template.SetCodelet("GRIDMULTISELECTION",
                                               "grdDetails.Selection.EnableMultiSelection = true;" + Environment.NewLine);
                }
            }

            return(writer.FTemplate);
        }
Esempio n. 22
0
        /// <summary>
        /// parse the definition of one table column
        /// </summary>
        /// <param name="cur2">the current node</param>
        /// <returns></returns>
        protected TTableField ParseTableField(XmlNode cur2)
        {
            TTableField element;

            element = new TTableField();
            element.strName = GetAttribute(cur2, "name");

            if (element.strName.Length > 32)
            {
                throw new Exception("Fieldname is too long (max 32 characters): " + element.strName);
            }

            element.strType = GetAttribute(cur2, "type").ToLower();
            element.strTypeDotNet = GetAttribute(cur2, "typedotnet");
            element.strNameDotNet = GetAttribute(cur2, "namedotnet");
            element.ExistsStrHelp = HasAttribute(cur2, "help");
            element.strHelp = GetAttribute(cur2, "help");
            element.ExistsStrLabel = HasAttribute(cur2, "label");
            element.strLabel = GetAttribute(cur2, "label");

            if (!element.ExistsStrLabel)
            {
                element.strLabel = element.strName;
            }

            element.strFormat = GetAttribute(cur2, "format");
            element.iCharLength = GetIntAttribute(cur2, "charlength");
            element.iLength = GetIntAttribute(cur2, "length");
            element.iDecimals = GetIntAttribute(cur2, "decimals");
            element.bNotNull = (GetAttribute(cur2, "notnull") == "yes");
            element.bAutoIncrement = (GetAttribute(cur2, "autoincrement") == "yes");

            if (GetAttribute(cur2, "mandatory") == "yes")
            {
                element.bNotNull = true;
            }
            else
            {
                element.bNotNull = (GetAttribute(cur2, "notnull") == "yes");
            }

            element.ExistsStrInitialValue = HasAttribute(cur2, "initial");
            element.strInitialValue = GetAttribute(cur2, "initial");

            if (element.ExistsStrInitialValue == true)
            {
                if (element.strType == "bit")
                {
                    if (element.strFormat.ToLower().IndexOf(element.strInitialValue.ToLower()) > 0)
                    {
                        element.strDefault = "0";
                    }
                    else
                    {
                        element.strDefault = "1";
                    }
                }
                else if (element.strInitialValue.ToLower() == "today")
                {
                    element.strDefault = "SYSDATE";
                }
                else if (element.strInitialValue.ToLower() == "?")
                {
                    element.strDefault = "NULL";
                }
                else
                {
                    element.strDefault = element.strInitialValue;
                }
            }

            element.strSequence = GetAttribute(cur2, "sequence");
            element.strDescription = GetAttribute(cur2, "descr");
            element.ExistsStrColLabel = HasAttribute(cur2, "columnlabel");
            element.strColLabel = GetAttribute(cur2, "columnlabel");
            element.ExistsStrCheck = HasAttribute(cur2, "check");
            element.strCheck = GetAttribute(cur2, "check");
            element.strValExp = GetAttribute(cur2, "valueexpression");
            element.strValMsg = GetAttribute(cur2, "valuemessage");
            element.strTableName = "";

            if (element.strType == "varchar")
            {
                element.iLength = 0;

                if ((element.strFormat.Length > 0) && (element.strFormat.IndexOf("(") == -1))
                {
                    // number of x, e.g. xxxxx or xx99999
                    element.iLength = element.strFormat.Length;
                }
                else if (element.strFormat.Length > 1)
                {
                    element.iLength = Convert.ToInt32(element.strFormat.Substring(2, element.strFormat.Length - 3));
                }

                if (element.iCharLength > 0)
                {
                    element.iLength = element.iCharLength;
                }

                if (element.iCharLength <= 0)
                {
                    element.iCharLength = element.iLength;
                }

                element.iLength = element.iLength * 2;
            }

            return element;
        }
        /// <summary>
        /// Populate the empty table PPartnerGiftDestination using PmStaffData
        /// </summary>
        public static int PopulatePPartnerGiftDestination(StringCollection AColumnNames,
            ref string[] ANewRow,
            StreamWriter AWriter,
            StreamWriter AWriterTest)
        {
            List <string[]>ActiveCommitments = new List <string[]>();
            List <string[]>Persons = new List <string[]>();
            int RowCounter = 0;

            // default for all new records
            SetValue(AColumnNames, ref ANewRow, "p_active_l", "\\N");
            SetValue(AColumnNames, ref ANewRow, "p_default_gift_destination_l", "\\N");
            SetValue(AColumnNames, ref ANewRow, "p_partner_class_c", "\\N");
            SetValue(AColumnNames, ref ANewRow, "p_commitment_site_key_n", "\\N");
            SetValue(AColumnNames, ref ANewRow, "p_commitment_key_n", "\\N");
            SetValue(AColumnNames, ref ANewRow, "p_comment_c", "\\N");
            SetValue(AColumnNames, ref ANewRow, "s_date_created_d", "\\N");
            SetValue(AColumnNames, ref ANewRow, "s_created_by_c", "\\N");
            SetValue(AColumnNames, ref ANewRow, "s_date_modified_d", "\\N");
            SetValue(AColumnNames, ref ANewRow, "s_modified_by_c", "\\N");
            SetValue(AColumnNames, ref ANewRow, "s_modification_id_t", "\\N");

            // load the file pm_staff_data.d.gz
            TTable StaffDataTable = TDumpProgressToPostgresql.GetStoreOld().GetTable("pm_staff_data");

            TParseProgressCSV StaffDataParser = new TParseProgressCSV(
                TAppSettingsManager.GetValue("fulldumpPath", "fulldump") + Path.DirectorySeparatorChar + "pm_staff_data.d.gz",
                StaffDataTable.grpTableField.Count);

            StringCollection StaffDataColumnNames = GetColumnNames(StaffDataTable);

            // find which records are currently active
            while (true)
            {
                string[] StaffDataRow = StaffDataParser.ReadNextRow();

                if (StaffDataRow == null)
                {
                    break;
                }

                string strStartOfCommitment = GetValue(StaffDataColumnNames, StaffDataRow, "pm_start_of_commitment_d");
                string strEndOfCommitment = GetValue(StaffDataColumnNames, StaffDataRow, "pm_end_of_commitment_d");

                try
                {
                    // if commitment is currently active
                    if ((DateTime.ParseExact(strStartOfCommitment, "dd/mm/yyyy", CultureInfo.InvariantCulture) <= DateTime.Today)
                        && ((strEndOfCommitment == "\\N")
                            || (DateTime.ParseExact(strEndOfCommitment, "dd/mm/yyyy", CultureInfo.InvariantCulture) >= DateTime.Today))
                        && (strStartOfCommitment != strEndOfCommitment))
                    {
                        ActiveCommitments.Add(StaffDataRow);
                    }
                }
                catch
                {
                    TLogging.Log("WARNING: Invalid date in commitment: " +
                        strStartOfCommitment + " or " + strEndOfCommitment);
                }
            }

            // load the file p_person.d.gz
            TTable PersonTable = TDumpProgressToPostgresql.GetStoreOld().GetTable("p_person");

            TParseProgressCSV PersonParser = new TParseProgressCSV(
                TAppSettingsManager.GetValue("fulldumpPath", "fulldump") + Path.DirectorySeparatorChar + "p_person.d.gz",
                PersonTable.grpTableField.Count);

            StringCollection PersonColumnNames = GetColumnNames(PersonTable);
            SortedList <string, List <PersonKeyAndRow>>FamilyKeysWithPersons =
                new SortedList <string, List <PersonKeyAndRow>>();

            // add all Persons to a list
            while (true)
            {
                string[] PersonRow = PersonParser.ReadNextRow();

                if (PersonRow == null)
                {
                    break;
                }

                string familyKey = GetValue(PersonColumnNames, PersonRow, "p_family_key_n");

                if (!FamilyKeysWithPersons.ContainsKey(familyKey))
                {
                    FamilyKeysWithPersons.Add(familyKey, new List <PersonKeyAndRow>());
                }

                FamilyKeysWithPersons[familyKey].Add(
                    new PersonKeyAndRow(
                        GetValue(PersonColumnNames, PersonRow, "p_partner_key_n"), PersonRow));

                Persons.Add(PersonRow);
            }

            // load the file p_family.d.gz
            TTable FamilyTable = TDumpProgressToPostgresql.GetStoreOld().GetTable("p_family");

            TParseProgressCSV FamilyParser = new TParseProgressCSV(
                TAppSettingsManager.GetValue("fulldumpPath", "fulldump") + Path.DirectorySeparatorChar + "p_family.d.gz",
                FamilyTable.grpTableField.Count);

            StringCollection FamilyColumnNames = GetColumnNames(FamilyTable);

            // read through each family
            while (true)
            {
                string[] FamilyRow = FamilyParser.ReadNextRow();

                if (FamilyRow == null)
                {
                    break;
                }

                string familykey = GetValue(FamilyColumnNames, FamilyRow, "p_partner_key_n");

                // find Person partners belonging to the family
                bool CommitmentFound = false;
                int MinimumFamilyId = int.MaxValue;

                // if family contains Persons
                if (FamilyKeysWithPersons.ContainsKey(familykey))
                {
                    // read through each of the Family's Persons
                    foreach (PersonKeyAndRow PersonRecord in FamilyKeysWithPersons[familykey])
                    {
                        // find if the Person has a currently active commitment
                        string[] Commitment = ActiveCommitments.Find(e => GetValue(StaffDataColumnNames, e, "p_partner_key_n") ==
                            PersonRecord.PersonKey);

                        // if currently active commitment exists create a new Gift Destination record
                        if (Commitment != null)
                        {
                            int CurrentFamilyId = Convert.ToInt32(GetValue(PersonColumnNames, PersonRecord.PersonRow, "p_old_omss_family_id_i"));

                            if (CurrentFamilyId < MinimumFamilyId)
                            {
                                SetValue(AColumnNames, ref ANewRow, "p_key_i", RowCounter.ToString());
                                SetValue(AColumnNames, ref ANewRow, "p_partner_key_n", GetValue(FamilyColumnNames, FamilyRow, "p_partner_key_n"));
                                SetValue(AColumnNames, ref ANewRow, "p_field_key_n", GetValue(StaffDataColumnNames, Commitment, "pm_target_field_n"));
                                SetValue(AColumnNames, ref ANewRow, "p_comment_c", "\\N");

                                TTableField tf = new TTableField();
                                tf.strName = "pm_start_of_commitment_d";
                                tf.strType = "DATE";

                                SetValue(AColumnNames, ref ANewRow, "p_date_effective_d",
                                    TFixData.FixValue(GetValue(StaffDataColumnNames, Commitment, "pm_start_of_commitment_d"), tf));
                                tf.strName = "pm_end_of_commitment_d";
                                SetValue(AColumnNames, ref ANewRow, "p_date_expires_d",
                                    TFixData.FixValue(GetValue(StaffDataColumnNames, Commitment, "pm_end_of_commitment_d"), tf));

                                CommitmentFound = true;

                                MinimumFamilyId = CurrentFamilyId;

                                // there can only be one active gift destination per family
                                break;
                            }
                        }
                    }
                }

                // if no active commitment is found then search for a "p_om_field_key_n" and use that to create a gift destination
                if (!CommitmentFound)
                {
                    string OMFieldKey = GetValue(FamilyColumnNames, FamilyRow, "p_om_field_key_n");

                    if ((OMFieldKey != "\\N") && (OMFieldKey != "0"))
                    {
                        SetValue(AColumnNames, ref ANewRow, "p_key_i", RowCounter.ToString());
                        SetValue(AColumnNames, ref ANewRow, "p_partner_key_n", GetValue(FamilyColumnNames, FamilyRow, "p_partner_key_n"));
                        SetValue(AColumnNames, ref ANewRow, "p_field_key_n", GetValue(FamilyColumnNames, FamilyRow, "p_om_field_key_n"));
                        DateTime LastYear = DateTime.Today.AddYears(-1);
                        SetValue(AColumnNames, ref ANewRow, "p_date_effective_d",
                            string.Format("{0}-{1}-{2}", LastYear.Year, LastYear.Month, LastYear.Day));
                        SetValue(AColumnNames, ref ANewRow, "p_date_expires_d", "\\N");
                        SetValue(AColumnNames, ref ANewRow, "p_comment_c", Catalog.GetString("Copied from Petra's OM Field Key."));

                        CommitmentFound = true;
                    }
                }

                // write gift destination to file
                if (CommitmentFound)
                {
                    AWriter.WriteLine(StringHelper.StrMerge(ANewRow, '\t').Replace("\\\\N", "\\N").ToString());

                    if (AWriterTest != null)
                    {
                        AWriterTest.WriteLine("BEGIN; " + "COPY p_partner_gift_destination FROM stdin;");
                        AWriterTest.WriteLine(StringHelper.StrMerge(ANewRow, '\t').Replace("\\\\N", "\\N").ToString());
                        AWriterTest.WriteLine("\\.");
                        AWriterTest.WriteLine("ROLLBACK;");
                    }

                    RowCounter++;
                }
            }

            return RowCounter;
        }
Esempio n. 24
0
    /// <summary>
    /// write the part of the sql creation script for a specific column
    /// </summary>
    /// <param name="ATargetDatabase"></param>
    /// <param name="ATable"></param>
    /// <param name="field"></param>
    /// <param name="first"></param>
    /// <param name="AWithComments"></param>
    /// <returns></returns>
    public static string WriteField(eDatabaseType ATargetDatabase, TTable ATable, TTableField field, bool first, bool AWithComments)
    {
        string result = "";

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

        if (AWithComments)
        {
            result += Environment.NewLine;

            if (field.strDescription.Length != 0)
            {
                result += String.Format("    -- {0}", field.strDescription.Replace("\r", " ").Replace("\n", " ")) + Environment.NewLine;
            }
        }

#if IMPORTFROMLEGACYDB
        // this is useful when converting from legacy database, with columns that contain too long strings
        if ((field.strType == "varchar") && (field.iLength >= 20) && (!field.strName.Contains("_code_")))
        {
            field.strType = "text";
        }
#endif

        if (field.strType == "bit")
        {
            result += String.Format("  {0} boolean", field.strName);
        }
        else if ((field.strType == "number") && (field.iLength == 10) && (field.iDecimals == -1))
        {
            result += String.Format("  {0} bigint", field.strName);
        }
        else if (field.strType == "number")
        {
            result += String.Format("  {0} numeric", field.strName);
        }
        else if (field.bAutoIncrement)
        {
            if (ATargetDatabase == eDatabaseType.PostgreSQL)
            {
                result += String.Format("  {0} SERIAL", field.strName);
            }
            else if (ATargetDatabase == eDatabaseType.Sqlite)
            {
                result += String.Format("  {0} INTEGER PRIMARY KEY AUTOINCREMENT ", field.strName);
            }
            else if (ATargetDatabase == eDatabaseType.MySQL)
            {
                result += String.Format("  {0} INTEGER AUTO_INCREMENT UNIQUE ", field.strName);
            }
        }
        else
        {
            result += String.Format("  {0} {1}", field.strName, field.strType);
        }

        // According to the type we will add parameters
        if ((field.strType == "number") && (field.iLength == 10) && (field.iDecimals == -1))
        {
            // no parameter for bigints
        }
        else if ((field.strType == "varchar") || (field.strType == "number"))
        {
            if (field.iLength >= 0)
            {
                result += String.Format("({0}", field.iLength.ToString());
            }

            if (field.strType == "number")
            {
                result += String.Format(", {0}", (field.iDecimals > 0 ? field.iDecimals.ToString() : "0"));
            }

            result += String.Format(")");
        }

        if (field.strDefault.Length > 0)
        {
            if (field.strDefault == "NULL")
            {
                result += String.Format(" DEFAULT {0}", field.strDefault);
            }
            else if ((field.strType == "varchar") || (field.strType == "text"))
            {
                result += String.Format(" DEFAULT '{0}'", field.strDefault);
            }
            else if (field.strType == "bit")
            {
                if (ATargetDatabase == eDatabaseType.MySQL)
                {
                    result += String.Format(" DEFAULT {0}", field.strDefault);
                }
                else
                {
                    result += String.Format(" DEFAULT '{0}'", field.strDefault);
                }
            }
            else if (field.strDefault == "SYSDATE")
            {
                // MySql cannot have a function for the default value
                // see http://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html
                if (ATargetDatabase != eDatabaseType.MySQL)
                {
                    result += String.Format(" DEFAULT CURRENT_DATE");
                }
            }
            else
            {
                result += String.Format(" DEFAULT {0}", field.strDefault);
            }
        }

#if (!IMPORTFROMLEGACYDB)
        if (field.bNotNull)
        {
            result += String.Format(" NOT NULL");
        }

        if ((field.strCheck != null) && (field.strCheck.Length != 0))
        {
            result += String.Format(" CHECK {0}", field.strCheck);
        }
#endif

        return result;
    }
Esempio n. 25
0
        /// <summary>
        /// Determines whether automatic Data Validation code should be created for a certain DB Table Field.
        /// </summary>
        /// <param name="ADBField">DB Field.</param>
        /// <param name="AScope">Scope of the Data Validation that should be checked for. Specify <see cref="TAutomDataValidationScope.advsAll"/>
        /// to find out if any of the scopes should be checked against, or use any other value of that enum to specifiy a specific scope.</param>
        /// <param name="AConstraintsGroup">The constraints for the table associated with this column. Can be null unless this is doing table
        /// validation rather than control validation</param>
        /// <param name="AReasonForAutomValidation">Contains the reason why automatic data validation code needs to be generated.</param>
        /// <returns>True if automatic Data Validation code should be created for the DB Table Field passed in in <paramref name="ADBField" /> for
        /// the scope that was specified with <paramref name="AScope" />, otherwise false.</returns>
        public static bool GenerateAutoValidationCodeForDBTableField(TTableField ADBField,
            TAutomDataValidationScope AScope,
            List <TConstraint>AConstraintsGroup,
            out string AReasonForAutomValidation)
        {
            AReasonForAutomValidation = String.Empty;

            // NOT NULL checks
            if ((AScope == TAutomDataValidationScope.advsNotNullChecks)
                || (AScope == TAutomDataValidationScope.advsAll))
            {
                if (ADBField.bPartOfPrimKey)
                {
                    AReasonForAutomValidation = "must have a value (it is part of the Primary Key)";

                    if ((ADBField.strType == "varchar") || (ADBField.strType == "text"))
                    {
                        AReasonForAutomValidation += " and must not be an empty string";
                    }

                    return true;
                }
                else if (ADBField.bNotNull)
                {
                    AReasonForAutomValidation = "must have a value (NOT NULL constraint)";

                    // If it is a string and is a foreign key then the string cannot be empty
                    if (((ADBField.strType == "varchar") || (ADBField.strType == "text")) && (AConstraintsGroup != null))
                    {
                        foreach (TConstraint c in AConstraintsGroup)
                        {
                            if ((c.strType == "foreignkey") && (c.strThisFields.Contains(ADBField.strName)))
                            {
                                // Empty String is not allowed because it isn't allowed in the foreign table
                                AReasonForAutomValidation += " and must not be an empty string (Foreign Key constraint)";
                                break;
                            }
                        }
                    }

                    return true;
                }
            }

            // Date checks
            if ((AScope == TAutomDataValidationScope.advsDateChecks)
                || (AScope == TAutomDataValidationScope.advsAll))
            {
                if (ADBField.strType == "date")
                {
                    AReasonForAutomValidation = "must represent a valid date";

                    return true;
                }
            }

            // String Length checks
            if ((AScope == TAutomDataValidationScope.advsStringLengthChecks)
                || (AScope == TAutomDataValidationScope.advsAll))
            {
                if (((ADBField.strType == "varchar") || (ADBField.strType == "text"))
                    && ((ADBField.strName != "s_created_by_c")
                        && (ADBField.strName != "s_modified_by_c")))
                {
                    AReasonForAutomValidation = "must not contain more than " + (ADBField.iCharLength * 2).ToString() + " characters";

                    return true;
                }
            }

            // Number Range checks
            if ((AScope == TAutomDataValidationScope.advsNumberRangeChecks)
                || (AScope == TAutomDataValidationScope.advsAll))
            {
                if (ADBField.strType == "number")
                {
                    if (ADBField.iDecimals > 0)
                    {
                        AReasonForAutomValidation = "must not have more than " +
                                                    (ADBField.iLength -
                                                     ADBField.iDecimals).ToString() + " digits before the decimal point and not more than " +
                                                    ADBField.iDecimals.ToString() +
                                                    " after the decimal point";
                    }
                    else
                    {
                        AReasonForAutomValidation = "must not have more than " + ADBField.iLength.ToString() + " digits and no decimals";
                    }

                    return true;
                }
            }

            return false;
        }
Esempio n. 26
0
        private void LinkControlDataField(TFormWriter writer, TControlDef ctrl, TTableField AField, bool AIsDetailNotMaster)
        {
            ProcessTemplate snippetValidationControlsDictAdd;
            bool AutomDataValidation;
            string ReasonForAutomValidation;
            string ColumnIDStr;
            bool OKToGenerateDVCode = true;

            if (AField == null)
            {
                return;
            }

            string tablename = TTable.NiceTableName(AField.strTableName);
            string fieldname = TTable.NiceFieldName(AField);
            string RowName = "FMainDS." + tablename + "[0]";
            string TestForNullTable = "FMainDS." + tablename;

            if ((tablename == writer.CodeStorage.GetAttribute("DetailTable")) || (tablename == writer.CodeStorage.GetAttribute("MasterTable")))
            {
                RowName = "ARow";
                TestForNullTable = "";
            }

            string targetCodelet = "SHOWDATA";

            if (tablename == writer.CodeStorage.GetAttribute("DetailTable"))
            {
                targetCodelet = "SHOWDETAILS";
            }

            ProcessTemplate snippetShowData = GenerateShowDataSnippetCode(ref fieldname, ref RowName, ref TestForNullTable, writer, ctrl, AField);

            writer.Template.InsertSnippet(targetCodelet, snippetShowData);

            if (AField.bPartOfPrimKey)
            {
                // check if the current row is new; then allow changing the primary key; otherwise make the control readonly
                writer.Template.AddToCodelet(targetCodelet, ctrl.controlName + "." + (FHasReadOnlyProperty ? "ReadOnly" : "Enabled") + " = " +
                    "(" + RowName + ".RowState " + (FHasReadOnlyProperty ? "!=" : "==") + " DataRowState.Added);" + Environment.NewLine);
                writer.Template.AddToCodelet("PRIMARYKEYCONTROLSREADONLY",
                    ctrl.controlName + "." + (FHasReadOnlyProperty ? "ReadOnly = " : "Enabled = !") + "AReadOnly;" + Environment.NewLine);
            }

            if (ctrl.GetAttribute("ReadOnly").ToLower() != "true")
            {
                targetCodelet = targetCodelet.Replace("SHOW", "SAVE");

                ProcessTemplate snippetGetData = writer.Template.GetSnippet("GETDATAFORCOLUMNTHATCANBENULL");

                if (AField.GetDotNetType().ToLower().Contains("string"))
                {
                    snippetGetData.SetCodelet("GETVALUEORNULL", "{#ROW}.{#COLUMNNAME} = {#CONTROLVALUE};");
                    snippetGetData.InsertSnippet("GETROWVALUEORNULL", writer.Template.GetSnippet("GETROWVALUEORNULLSTRING"));
                }
                else
                {
                    snippetGetData.InsertSnippet("GETVALUEORNULL", writer.Template.GetSnippet("GETVALUEORNULL"));
                    snippetGetData.InsertSnippet("GETROWVALUEORNULL", writer.Template.GetSnippet("GETROWVALUEORNULL"));
                }

                snippetGetData.SetCodelet("CANBENULL", !AField.bNotNull && (this.GetControlValue(ctrl, null) != null) ? "yes" : "");
                snippetGetData.SetCodelet("NOTDEFAULTTABLE", TestForNullTable);
                snippetGetData.SetCodelet("DETERMINECONTROLISNULL", this.GetControlValue(ctrl, null));
                snippetGetData.SetCodelet("ROW", RowName);
                snippetGetData.SetCodelet("COLUMNNAME", fieldname);
                snippetGetData.SetCodelet("CONTROLVALUE", this.GetControlValue(ctrl, AField.GetDotNetType()));
                snippetGetData.SetCodelet("CONTROLNAME", ctrl.controlName);

                writer.Template.InsertSnippet(targetCodelet, snippetGetData);
            }

            // setstatusbar tooltips for datafields, with getstring plus value from petra.xml
            string helpText = AField.strHelp;

            if (helpText.Length == 0)
            {
                helpText = AField.strDescription;
            }

            if ((helpText.Length > 0) && (ctrl.GetAttribute("Tooltip").Length == 0))
            {
                writer.Template.AddToCodelet("INITUSERCONTROLS", "FPetraUtilsObject.SetStatusBarText(" + ctrl.controlName +
                    ", Catalog.GetString(\"" +
                    helpText.Replace("\"", "\\\"") +                           // properly escape double quotation marks
                    "\"));" + Environment.NewLine);
            }

            // Data Validation
            if (GenerateDataValidationCode(writer, ctrl, out AutomDataValidation, out ReasonForAutomValidation))
            {
                string targetCodeletValidation = "ADDCONTROLTOVALIDATIONCONTROLSDICT";

                ColumnIDStr = "FMainDS." + tablename + ".Columns[(short)FMainDS." + tablename + ".GetType().GetField(\"Column" + fieldname +
                              "Id\", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy).GetValue(FMainDS." + tablename +
                              ".GetType())]";

                if (writer.Template.FCodelets.Keys.Contains(targetCodeletValidation))
                {
                    // Check if code for the addition of a certain DataColumn is is already contained in Template;
                    // if so, skip a further addition to prevent an Exception at runtime
                    if (writer.Template.FCodelets[targetCodeletValidation].ToString().Contains(ColumnIDStr))
                    {
                        OKToGenerateDVCode = false;
                    }
                }

                if (OKToGenerateDVCode)
                {
                    if (!ctrl.GetAttribute("Validation").ToLower().StartsWith("pair("))
                    {
                        snippetValidationControlsDictAdd = writer.Template.GetSnippet("VALIDATIONCONTROLSDICTADD");
                    }
                    else
                    {
                        snippetValidationControlsDictAdd = writer.Template.GetSnippet("VALIDATIONCONTROLSDICTADDMULTI");

                        string PairControlName = ctrl.GetAttribute("Validation").Substring(5, ctrl.GetAttribute("Validation").Length - 6);
                        TControlDef SecondValidationControl = writer.CodeStorage.GetControl(PairControlName);

                        if (SecondValidationControl != null)
                        {
                            snippetValidationControlsDictAdd.SetCodelet("VALIDATIONCONTROL2", SecondValidationControl.controlName);

                            if (TFormWriter.ProperI18NCatalogGetString(StringHelper.TrimQuotes(SecondValidationControl.Label)))
                            {
                                snippetValidationControlsDictAdd.SetCodelet("LABELTEXT2",
                                    "Catalog.GetString(" + "\"" + SecondValidationControl.Label + "\")");
                            }
                            else
                            {
                                snippetValidationControlsDictAdd.SetCodelet("LABELTEXT2", "\"" + SecondValidationControl.Label + "\"");
                            }
                        }
                        else
                        {
                            throw new ApplicationException(
                                "Pair Control for Validation '" + PairControlName + "' does not exist. Please specify a valid control!");
                        }
                    }

                    snippetValidationControlsDictAdd.SetCodelet("TABLENAME", tablename);
                    snippetValidationControlsDictAdd.SetCodelet("COLUMNID", ColumnIDStr);
                    snippetValidationControlsDictAdd.SetCodelet("VALIDATIONCONTROLSDICTVAR",
                        writer.Template.FTemplateCode.Contains(
                            "FValidationControlsDict") ? "FValidationControlsDict" : "FPetraUtilsObject.ValidationControlsDict");

                    if (AutomDataValidation)
                    {
                        snippetValidationControlsDictAdd.SetCodelet("AUTOMATICVALIDATIONCOMMENT",
                            " // Automatic Data Validation based on DB specification: " + ReasonForAutomValidation);
                    }
                    else
                    {
                        snippetValidationControlsDictAdd.SetCodelet("AUTOMATICVALIDATIONCOMMENT", "");
                    }

                    snippetValidationControlsDictAdd.SetCodelet("VALIDATIONCONTROL", ctrl.controlName);

                    if (TFormWriter.ProperI18NCatalogGetString(StringHelper.TrimQuotes(ctrl.Label)))
                    {
                        snippetValidationControlsDictAdd.SetCodelet("LABELTEXT", "Catalog.GetString(" + "\"" + ctrl.Label + "\")");
                    }
                    else
                    {
                        snippetValidationControlsDictAdd.SetCodelet("LABELTEXT", "\"" + ctrl.Label + "\"");
                    }

                    writer.Template.InsertSnippet(targetCodeletValidation, snippetValidationControlsDictAdd);
                }
            }
        }
Esempio n. 27
0
        /// <summary>
        /// parse the definition of one table column
        /// </summary>
        /// <param name="cur2">the current node</param>
        /// <returns></returns>
        protected TTableField ParseTableField(XmlNode cur2)
        {
            TTableField element;

            element         = new TTableField();
            element.strName = GetAttribute(cur2, "name");

            if (element.strName.Length > 32)
            {
                throw new Exception("Fieldname is too long (max 32 characters): " + element.strName);
            }

            element.strType        = GetAttribute(cur2, "type").ToLower();
            element.strTypeDotNet  = GetAttribute(cur2, "typedotnet");
            element.strNameDotNet  = GetAttribute(cur2, "namedotnet");
            element.ExistsStrHelp  = HasAttribute(cur2, "help");
            element.strHelp        = GetAttribute(cur2, "help");
            element.ExistsStrLabel = HasAttribute(cur2, "label");
            element.strLabel       = GetAttribute(cur2, "label");

            if (!element.ExistsStrLabel)
            {
                element.strLabel = element.strName;
            }

            element.strFormat      = GetAttribute(cur2, "format");
            element.iCharLength    = GetIntAttribute(cur2, "charlength");
            element.iLength        = GetIntAttribute(cur2, "length");
            element.iDecimals      = GetIntAttribute(cur2, "decimals");
            element.bNotNull       = (GetAttribute(cur2, "notnull") == "yes");
            element.bAutoIncrement = (GetAttribute(cur2, "autoincrement") == "yes");

            if (GetAttribute(cur2, "mandatory") == "yes")
            {
                element.bNotNull = true;
            }
            else
            {
                element.bNotNull = (GetAttribute(cur2, "notnull") == "yes");
            }

            element.ExistsStrInitialValue = HasAttribute(cur2, "initial");
            element.strInitialValue       = GetAttribute(cur2, "initial");

            if (element.ExistsStrInitialValue == true)
            {
                if (element.strType == "bit")
                {
                    if (element.strFormat.ToLower().IndexOf(element.strInitialValue.ToLower()) > 0)
                    {
                        element.strDefault = "0";
                    }
                    else
                    {
                        element.strDefault = "1";
                    }
                }
                else if (element.strInitialValue.ToLower() == "today")
                {
                    element.strDefault = "SYSDATE";
                }
                else if (element.strInitialValue.ToLower() == "?")
                {
                    element.strDefault = "NULL";
                }
                else
                {
                    element.strDefault = element.strInitialValue;
                }
            }

            element.strSequence       = GetAttribute(cur2, "sequence");
            element.strDescription    = GetAttribute(cur2, "descr");
            element.ExistsStrColLabel = HasAttribute(cur2, "columnlabel");
            element.strColLabel       = GetAttribute(cur2, "columnlabel");
            element.ExistsStrCheck    = HasAttribute(cur2, "check");
            element.strCheck          = GetAttribute(cur2, "check");
            element.strValExp         = GetAttribute(cur2, "valueexpression");
            element.strValMsg         = GetAttribute(cur2, "valuemessage");
            element.strTableName      = "";

            if (element.strType == "varchar")
            {
                element.iLength = 0;

                if ((element.strFormat.Length > 0) && (element.strFormat.IndexOf("(") == -1))
                {
                    // number of x, e.g. xxxxx or xx99999
                    element.iLength = element.strFormat.Length;
                }
                else if (element.strFormat.Length > 1)
                {
                    element.iLength = Convert.ToInt32(element.strFormat.Substring(2, element.strFormat.Length - 3));
                }

                if (element.iCharLength > 0)
                {
                    element.iLength = element.iCharLength;
                }

                if (element.iCharLength <= 0)
                {
                    element.iCharLength = element.iLength;
                }

                element.iLength = element.iLength * 2;
            }

            return(element);
        }
Esempio n. 28
0
        /// <summary>
        /// Generates code for the UNDODATA Snippet.
        /// </summary>
        /// <param name="tablename">Name of table</param>
        /// <param name="fieldname">Name of field</param>
        /// <param name="TestForNullTable"></param>
        /// <param name="writer">FormWriter instance.</param>
        /// <param name="ctrl">TControlDef instance.</param>
        /// <param name="AField">TTableField instance.</param>
        /// <returns>A <see cref="ProcessTemplate"></see>.</returns>
        ProcessTemplate GenerateUndoDataSnippetCode(ref string tablename,
            ref string fieldname,
            ref string TestForNullTable,
            TFormWriter writer,
            TControlDef ctrl,
            TTableField AField)
        {
            ProcessTemplate snippetShowData = writer.Template.GetSnippet("UNDODATAFORCOLUMN");

            snippetShowData.SetCodelet("NOTDEFAULTTABLE", TestForNullTable);

            snippetShowData.SetCodelet("UNDOCONTROLVALUE",
                this.UndoValue(ctrl, "ARow[FMainDS." + tablename + ".Columns[(short)FMainDS." + tablename + ".GetType().GetField(\"Column" +
                    fieldname +
                    "Id\", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy).GetValue(FMainDS." + tablename +
                    ".GetType())], DataRowVersion.Original]",
                    AField.GetDotNetType()));
            snippetShowData.InsertSnippet("UNDOROWVALUE", writer.Template.GetSnippet("UNDOROWVALUE"));

            snippetShowData.SetCodelet("CONTROLNAME", ctrl.controlName);

            return snippetShowData;
        }
Esempio n. 29
0
        /// <summary>
        /// load the dataset tables
        /// </summary>
        public static SortedList <string, TTable> LoadDatasetTables(string AICTPath, string ADataSetTypeWithNamespace, TCodeStorage ACodeStorage,
                                                                    string APluginPath)
        {
            if (FDatasetTables == null)
            {
                FDatasetTables = new SortedList <string, SortedList <string, TTable> >();
            }

            FCodeStorage = ACodeStorage;

            if (!ADataSetTypeWithNamespace.StartsWith("Ict.Petra.Shared") && !ADataSetTypeWithNamespace.StartsWith("Ict.Petra.Plugins"))
            {
                throw new Exception("the DatasetType must contain the full namespace, starting with Ict.Petra.Shared or Ict.Petra.Plugins");
            }

            if (FDatasetTables.ContainsKey(ADataSetTypeWithNamespace))
            {
                FCurrentDataset = FDatasetTables[ADataSetTypeWithNamespace];

                return(FCurrentDataset);
            }

            string[] datasetTypeSplit = ADataSetTypeWithNamespace.Split(new char[] { '.' });
            string   module           = datasetTypeSplit[3];
            string   datasetName      = datasetTypeSplit[datasetTypeSplit.Length - 1];

            // find the correct xml file for the dataset.
            // look in Ict/Petra/Shared/lib/MODULE/data
            string dataPath = AICTPath + "/Petra/Shared/lib/" + module + "/data/";

            if (ADataSetTypeWithNamespace.StartsWith("Ict.Petra.Plugins"))
            {
                int    start      = "Ict.Petra.Plugins.".Length;
                int    end        = ADataSetTypeWithNamespace.IndexOf(".", start);
                string PluginName = ADataSetTypeWithNamespace.Substring(start, end - start);
                dataPath = AICTPath + "/Petra/Plugins/" + PluginName + "/data/";
            }

            DirectoryInfo directory = new DirectoryInfo(dataPath);

            FileInfo[] xmlFiles    = directory.GetFiles("*.xml");
            XmlNode    datasetNode = null;

            foreach (FileInfo fileinfo in xmlFiles)
            {
                if (datasetNode == null)
                {
                    TXMLParser parser = new TXMLParser(dataPath + "/" + fileinfo.Name, false);
                    datasetNode = parser.GetDocument().SelectSingleNode(String.Format("//DataSet[@name='{0}']", datasetName));
                }
            }

            if ((datasetNode == null) && File.Exists(APluginPath))
            {
                // also check the plugin directory of the yaml file, for plugins can have a file TypedDataSets.xml
                TXMLParser parser = new TXMLParser(APluginPath, false);
                datasetNode = parser.GetDocument().SelectSingleNode(String.Format("//DataSet[@name='{0}']", datasetName));
            }

            if (datasetNode == null)
            {
                throw new Exception("cannot find the xml file for dataset " + ADataSetTypeWithNamespace);
            }

            SortedList <string, TTable> result = new SortedList <string, TTable>();
            XmlNodeList tables = datasetNode.SelectNodes("Table|CustomTable");

            foreach (XmlNode tableNode in tables)
            {
                TTable table = new TTable();
                string tablename;

                if ((tableNode.Name == "Table") && TXMLParser.HasAttribute(tableNode, "sqltable"))
                {
                    tablename = TTable.NiceTableName(tableNode.Attributes["sqltable"].Value);
                    table.Assign(FPetraXMLStore.GetTable(tablename));

                    table.strVariableNameInDataset = TXMLParser.HasAttribute(tableNode, "name") ? tableNode.Attributes["name"].Value : tablename;

                    if ((tableNode.SelectNodes("CustomField").Count > 0) || (tableNode.SelectNodes("Field").Count > 0))
                    {
                        table.strDotNetName = datasetName + tablename;
                    }
                }
                else if ((tableNode.Name == "Table") && TXMLParser.HasAttribute(tableNode, "customtable"))
                {
                    table                          = new TTable();
                    tablename                      = tableNode.Attributes["customtable"].Value;
                    table.strName                  = tablename;
                    table.strDotNetName            = tablename;
                    table.strVariableNameInDataset = TXMLParser.HasAttribute(tableNode, "name") ? tableNode.Attributes["name"].Value : tablename;
                }
                else
                {
                    table                          = new TTable();
                    tablename                      = tableNode.Attributes["name"].Value;
                    table.strName                  = tablename;
                    table.strDotNetName            = datasetName + tablename;
                    table.strVariableNameInDataset = tablename;
                }

                // add the custom fields if there are any
                XmlNodeList customFields = tableNode.SelectNodes("CustomField");

                foreach (XmlNode customField in customFields)
                {
                    TTableField newField = new TTableField();
                    newField.strName        = customField.Attributes["name"].Value;
                    newField.strNameDotNet  = newField.strName;
                    newField.strType        = customField.Attributes["type"].Value;
                    newField.strTypeDotNet  = customField.Attributes["type"].Value;
                    newField.strTableName   = tablename;
                    newField.strDescription = "";
                    newField.bNotNull       =
                        TXMLParser.HasAttribute(customField, "notnull") && TXMLParser.GetAttribute(customField, "notnull").ToLower() == "true";
                    table.grpTableField.Add(newField);
                }

                // add other fields from other tables that are defined in petra.xml
                XmlNodeList otherFields = tableNode.SelectNodes("Field");

                foreach (XmlNode otherField in otherFields)
                {
                    TTable      otherTable = FPetraXMLStore.GetTable(otherField.Attributes["sqltable"].Value);
                    TTableField newField   = new TTableField(otherTable.GetField(otherField.Attributes["sqlfield"].Value));

                    if (TXMLParser.HasAttribute(otherField, "name"))
                    {
                        newField.strNameDotNet = otherField.Attributes["name"].Value;
                    }

                    newField.strTableName = tablename;
                    table.grpTableField.Add(newField);
                }

                result.Add(table.strVariableNameInDataset, table);
            }

            FDatasetTables.Add(ADataSetTypeWithNamespace, result);
            FCurrentDataset = result;
            return(result);
        }
Esempio n. 30
0
        /// <summary>write the code for the designer file where the properties of the control are written</summary>
        public override ProcessTemplate SetControlProperties(TFormWriter writer, TControlDef ctrl)
        {
            base.SetControlProperties(writer, ctrl);

            if (TYml2Xml.HasAttribute(ctrl.xmlNode, "SelectedRowActivates"))
            {
                // TODO: this function needs to be called by the manual code at the moment when eg a search finishes
                // TODO: call "Activate" + TYml2Xml.GetAttribute(ctrl.xmlNode, "SelectedRowActivates")
            }

            StringCollection Columns = TYml2Xml.GetElements(ctrl.xmlNode, "Columns");

            if (Columns.Count > 0)
            {
                writer.Template.AddToCodelet("INITMANUALCODE", ctrl.controlName + ".Columns.Clear();" + Environment.NewLine);

                foreach (string ColumnFieldName in Columns)
                {
                    bool        IsDetailNotMaster;
                    TTableField field = null;

                    // customfield, eg. UC_GLTransactions, ATransaction.DateEntered and ATransaction.AnalysisAttributes
                    // there needs to be a list of CustomColumns
                    XmlNode CustomColumnsNode = TYml2Xml.GetChild(ctrl.xmlNode, "CustomColumns");
                    XmlNode CustomColumnNode  = null;

                    if (CustomColumnsNode != null)
                    {
                        CustomColumnNode = TYml2Xml.GetChild(CustomColumnsNode, ColumnFieldName);
                    }

                    if (CustomColumnNode != null)
                    {
                        //string ColumnType = "System.String";

                        /* TODO DateTime (tracker: #58)
                         * if (TYml2Xml.GetAttribute(CustomColumnNode, "Type") == "System.DateTime")
                         * {
                         *  ColumnType = "DateTime";
                         * }
                         */

                        // TODO: different behaviour for double???
                        if (TYml2Xml.GetAttribute(CustomColumnNode, "Type") == "Boolean")
                        {
                            //ColumnType = "CheckBox";
                        }

                        writer.Template.AddToCodelet("INITMANUALCODE", ctrl.controlName + ".Columns.Add(" +
                                                     "FMainDS." + ctrl.GetAttribute("TableName") + ".Get" + ColumnFieldName + "DBName(), \"" +
                                                     TYml2Xml.GetAttribute(CustomColumnNode, "Label") + "\");" + Environment.NewLine);
                    }
                    else if (ctrl.HasAttribute("TableName"))
                    {
                        field =
                            TDataBinding.GetTableField(null, ctrl.GetAttribute("TableName") + "." + ColumnFieldName,
                                                       out IsDetailNotMaster,
                                                       true);
                    }
                    else
                    {
                        field = TDataBinding.GetTableField(null, ColumnFieldName, out IsDetailNotMaster, true);
                    }

                    if (field != null)
                    {
                        //string ColumnType = "System.String";

                        /* TODO DateTime (tracker: #58)
                         * if (field.GetDotNetType() == "System.DateTime")
                         * {
                         *  ColumnType = "DateTime";
                         * }
                         */

                        // TODO: different behaviour for double???
                        if (field.GetDotNetType() == "Boolean")
                        {
                            //ColumnType = "CheckBox";
                        }

                        writer.Template.AddToCodelet("INITMANUALCODE", ctrl.controlName + ".Columns.Add(" +
                                                     TTable.NiceTableName(field.strTableName) + "Table.Get" +
                                                     TTable.NiceFieldName(field.strName) + "DBName(), \"" +
                                                     field.strLabel + "\");" + Environment.NewLine);
                    }
                }
            }

            if (ctrl.HasAttribute("ActionLeavingRow"))
            {
                AssignEventHandlerToControl(writer, ctrl, "Selection.FocusRowLeaving", "SourceGrid.RowCancelEventHandler",
                                            ctrl.GetAttribute("ActionLeavingRow"));
            }

            if (ctrl.HasAttribute("ActionFocusRow"))
            {
// TODO                AssignEventHandlerToControl(writer, ctrl, "Selection.FocusRowEntered", "SourceGrid.RowEventHandler",
//                    ctrl.GetAttribute("ActionFocusRow"));
            }

            if ((ctrl.controlName == "grdDetails") && FCodeStorage.HasAttribute("DetailTable"))
            {
                writer.Template.AddToCodelet("SHOWDATA", "");

                if (ctrl.HasAttribute("SortOrder"))
                {
                    // SortOrder is comma separated and has DESC or ASC after the column name
                    string SortOrder = ctrl.GetAttribute("SortOrder");

                    foreach (string SortOrderPart in SortOrder.Split(','))
                    {
                        bool        temp;
                        TTableField field = null;

                        if ((SortOrderPart.Split(' ')[0].IndexOf(".") == -1) && ctrl.HasAttribute("TableName"))
                        {
                            field =
                                TDataBinding.GetTableField(null, ctrl.GetAttribute("TableName") + "." + SortOrderPart.Split(
                                                               ' ')[0], out temp, true);
                        }
                        else
                        {
                            field =
                                TDataBinding.GetTableField(
                                    null,
                                    SortOrderPart.Split(' ')[0],
                                    out temp, true);
                        }

                        if (field != null)
                        {
                            SortOrder = SortOrder.Replace(SortOrderPart.Split(' ')[0], field.strName);
                        }
                    }

                    writer.Template.AddToCodelet("GRIDSORT", SortOrder);
                }

                if (ctrl.HasAttribute("RowFilter"))
                {
                    // this references a field in the table, and assumes there exists a local variable with the same name
                    // eg. FBatchNumber in GL Journals
                    string RowFilter = ctrl.GetAttribute("RowFilter");

                    String FilterString = "\"";

                    foreach (string RowFilterPart in RowFilter.Split(','))
                    {
                        bool   temp;
                        string columnName =
                            TDataBinding.GetTableField(
                                null,
                                RowFilterPart,
                                out temp, true).strName;

                        if (FilterString.Length > 1)
                        {
                            FilterString += " + \" and ";
                        }

                        FilterString += columnName + " = \" + F" + TTable.NiceFieldName(columnName) + ".ToString()";
                    }

                    writer.Template.AddToCodelet("GRIDFILTER", FilterString);
                }
            }

            return(writer.FTemplate);
        }
Esempio n. 31
0
        /// <summary>
        /// Populate the empty table PPartnerGiftDestination using PmStaffData
        /// </summary>
        public static int PopulatePPartnerGiftDestination(StringCollection AColumnNames,
                                                          ref string[] ANewRow,
                                                          StreamWriter AWriter,
                                                          StreamWriter AWriterTest)
        {
            List <string[]> ActiveCommitments = new List <string[]>();
            List <string[]> Persons           = new List <string[]>();
            int             RowCounter        = 0;

            // default for all new records
            SetValue(AColumnNames, ref ANewRow, "p_active_l", "\\N");
            SetValue(AColumnNames, ref ANewRow, "p_default_gift_destination_l", "\\N");
            SetValue(AColumnNames, ref ANewRow, "p_partner_class_c", "\\N");
            SetValue(AColumnNames, ref ANewRow, "p_commitment_site_key_n", "\\N");
            SetValue(AColumnNames, ref ANewRow, "p_commitment_key_n", "\\N");
            SetValue(AColumnNames, ref ANewRow, "p_comment_c", "\\N");
            SetValue(AColumnNames, ref ANewRow, "s_date_created_d", "\\N");
            SetValue(AColumnNames, ref ANewRow, "s_created_by_c", "\\N");
            SetValue(AColumnNames, ref ANewRow, "s_date_modified_d", "\\N");
            SetValue(AColumnNames, ref ANewRow, "s_modified_by_c", "\\N");
            SetValue(AColumnNames, ref ANewRow, "s_modification_id_t", "\\N");

            // load the file pm_staff_data.d.gz
            TTable StaffDataTable = TDumpProgressToPostgresql.GetStoreOld().GetTable("pm_staff_data");

            TParseProgressCSV StaffDataParser = new TParseProgressCSV(
                TAppSettingsManager.GetValue("fulldumpPath", "fulldump") + Path.DirectorySeparatorChar + "pm_staff_data.d.gz",
                StaffDataTable.grpTableField.Count);

            StringCollection StaffDataColumnNames = GetColumnNames(StaffDataTable);

            // find which records are currently active
            while (true)
            {
                string[] StaffDataRow = StaffDataParser.ReadNextRow();

                if (StaffDataRow == null)
                {
                    break;
                }

                string strStartOfCommitment = GetValue(StaffDataColumnNames, StaffDataRow, "pm_start_of_commitment_d");
                string strEndOfCommitment   = GetValue(StaffDataColumnNames, StaffDataRow, "pm_end_of_commitment_d");

                try
                {
                    // if commitment is currently active
                    if ((DateTime.ParseExact(strStartOfCommitment, "dd/mm/yyyy", CultureInfo.InvariantCulture) <= DateTime.Today) &&
                        ((strEndOfCommitment == "\\N") ||
                         (DateTime.ParseExact(strEndOfCommitment, "dd/mm/yyyy", CultureInfo.InvariantCulture) >= DateTime.Today)) &&
                        (strStartOfCommitment != strEndOfCommitment))
                    {
                        ActiveCommitments.Add(StaffDataRow);
                    }
                }
                catch
                {
                    TLogging.Log("WARNING: Invalid date in commitment: " +
                                 strStartOfCommitment + " or " + strEndOfCommitment);
                }
            }

            // load the file p_person.d.gz
            TTable PersonTable = TDumpProgressToPostgresql.GetStoreOld().GetTable("p_person");

            TParseProgressCSV PersonParser = new TParseProgressCSV(
                TAppSettingsManager.GetValue("fulldumpPath", "fulldump") + Path.DirectorySeparatorChar + "p_person.d.gz",
                PersonTable.grpTableField.Count);

            StringCollection PersonColumnNames = GetColumnNames(PersonTable);
            SortedList <string, List <PersonKeyAndRow> > FamilyKeysWithPersons =
                new SortedList <string, List <PersonKeyAndRow> >();

            // add all Persons to a list
            while (true)
            {
                string[] PersonRow = PersonParser.ReadNextRow();

                if (PersonRow == null)
                {
                    break;
                }

                string familyKey = GetValue(PersonColumnNames, PersonRow, "p_family_key_n");

                if (!FamilyKeysWithPersons.ContainsKey(familyKey))
                {
                    FamilyKeysWithPersons.Add(familyKey, new List <PersonKeyAndRow>());
                }

                FamilyKeysWithPersons[familyKey].Add(
                    new PersonKeyAndRow(
                        GetValue(PersonColumnNames, PersonRow, "p_partner_key_n"), PersonRow));

                Persons.Add(PersonRow);
            }

            // load the file p_family.d.gz
            TTable FamilyTable = TDumpProgressToPostgresql.GetStoreOld().GetTable("p_family");

            TParseProgressCSV FamilyParser = new TParseProgressCSV(
                TAppSettingsManager.GetValue("fulldumpPath", "fulldump") + Path.DirectorySeparatorChar + "p_family.d.gz",
                FamilyTable.grpTableField.Count);

            StringCollection FamilyColumnNames = GetColumnNames(FamilyTable);

            // read through each family
            while (true)
            {
                string[] FamilyRow = FamilyParser.ReadNextRow();

                if (FamilyRow == null)
                {
                    break;
                }

                string familykey = GetValue(FamilyColumnNames, FamilyRow, "p_partner_key_n");

                // find Person partners belonging to the family
                bool CommitmentFound = false;
                int  MinimumFamilyId = int.MaxValue;

                // if family contains Persons
                if (FamilyKeysWithPersons.ContainsKey(familykey))
                {
                    // read through each of the Family's Persons
                    foreach (PersonKeyAndRow PersonRecord in FamilyKeysWithPersons[familykey])
                    {
                        // find if the Person has a currently active commitment
                        string[] Commitment = ActiveCommitments.Find(e => GetValue(StaffDataColumnNames, e, "p_partner_key_n") ==
                                                                     PersonRecord.PersonKey);

                        // if currently active commitment exists create a new Gift Destination record
                        if (Commitment != null)
                        {
                            int CurrentFamilyId = Convert.ToInt32(GetValue(PersonColumnNames, PersonRecord.PersonRow, "p_old_omss_family_id_i"));

                            if (CurrentFamilyId < MinimumFamilyId)
                            {
                                SetValue(AColumnNames, ref ANewRow, "p_key_i", RowCounter.ToString());
                                SetValue(AColumnNames, ref ANewRow, "p_partner_key_n", GetValue(FamilyColumnNames, FamilyRow, "p_partner_key_n"));
                                SetValue(AColumnNames, ref ANewRow, "p_field_key_n", GetValue(StaffDataColumnNames, Commitment, "pm_target_field_n"));
                                SetValue(AColumnNames, ref ANewRow, "p_comment_c", "\\N");

                                TTableField tf = new TTableField();
                                tf.strName = "pm_start_of_commitment_d";
                                tf.strType = "DATE";

                                SetValue(AColumnNames, ref ANewRow, "p_date_effective_d",
                                         TFixData.FixValue(GetValue(StaffDataColumnNames, Commitment, "pm_start_of_commitment_d"), tf));
                                tf.strName = "pm_end_of_commitment_d";
                                SetValue(AColumnNames, ref ANewRow, "p_date_expires_d",
                                         TFixData.FixValue(GetValue(StaffDataColumnNames, Commitment, "pm_end_of_commitment_d"), tf));

                                CommitmentFound = true;

                                MinimumFamilyId = CurrentFamilyId;

                                // there can only be one active gift destination per family
                                break;
                            }
                        }
                    }
                }

                // if no active commitment is found then search for a "p_om_field_key_n" and use that to create a gift destination
                if (!CommitmentFound)
                {
                    string OMFieldKey = GetValue(FamilyColumnNames, FamilyRow, "p_om_field_key_n");

                    if ((OMFieldKey != "\\N") && (OMFieldKey != "0"))
                    {
                        SetValue(AColumnNames, ref ANewRow, "p_key_i", RowCounter.ToString());
                        SetValue(AColumnNames, ref ANewRow, "p_partner_key_n", GetValue(FamilyColumnNames, FamilyRow, "p_partner_key_n"));
                        SetValue(AColumnNames, ref ANewRow, "p_field_key_n", GetValue(FamilyColumnNames, FamilyRow, "p_om_field_key_n"));
                        DateTime LastYear = DateTime.Today.AddYears(-1);
                        SetValue(AColumnNames, ref ANewRow, "p_date_effective_d",
                                 string.Format("{0}-{1}-{2}", LastYear.Year, LastYear.Month, LastYear.Day));
                        SetValue(AColumnNames, ref ANewRow, "p_date_expires_d", "\\N");
                        SetValue(AColumnNames, ref ANewRow, "p_comment_c", Catalog.GetString("Copied from Petra's OM Field Key."));

                        CommitmentFound = true;
                    }
                }

                // write gift destination to file
                if (CommitmentFound)
                {
                    AWriter.WriteLine(StringHelper.StrMerge(ANewRow, '\t').Replace("\\\\N", "\\N").ToString());

                    if (AWriterTest != null)
                    {
                        AWriterTest.WriteLine("BEGIN; " + "COPY p_partner_gift_destination FROM stdin;");
                        AWriterTest.WriteLine(StringHelper.StrMerge(ANewRow, '\t').Replace("\\\\N", "\\N").ToString());
                        AWriterTest.WriteLine("\\.");
                        AWriterTest.WriteLine("ROLLBACK;");
                    }

                    RowCounter++;
                }
            }

            return(RowCounter);
        }