static private ProcessTemplate CreateModuleAccessPermissionCheck(ProcessTemplate ATemplate, string AConnectorClassWithNamespace, MethodDeclaration m) { if (m.Attributes != null) { foreach (AttributeSection attrSection in m.Attributes) { foreach (ICSharpCode.NRefactory.Ast.Attribute attr in attrSection.Attributes) { if (attr.Name == "RequireModulePermission") { ProcessTemplate snippet = ATemplate.GetSnippet("CHECKUSERMODULEPERMISSIONS"); snippet.SetCodelet("METHODNAME", m.Name); snippet.SetCodelet("CONNECTORWITHNAMESPACE", AConnectorClassWithNamespace); snippet.SetCodelet("LEDGERNUMBER", ""); string ParameterTypes = ";"; foreach (ParameterDeclarationExpression p in m.Parameters) { if (p.ParameterName == "ALedgerNumber") { snippet.SetCodelet("LEDGERNUMBER", ", ALedgerNumber"); } string ParameterType = p.TypeReference.Type.Replace("&", "").Replace("System.", String.Empty); if (ParameterType == "List") { ParameterType = ParameterType.Replace("List", "List[" + p.TypeReference.GenericTypes[0].ToString() + "]"); ParameterType = ParameterType.Replace("System.", String.Empty); } if (ParameterType == "Dictionary") { // this does not seem to work with Mono 5.12 api browser // ParameterType = ParameterType.Replace("Dictionary", "Dictionary[" + // p.TypeReference.GenericTypes[0].ToString() + "," + // p.TypeReference.GenericTypes[1].ToString() + "]"); // ParameterType = ParameterType.Replace("System.", String.Empty); ParameterType = "String"; } if (ParameterType.Contains(".")) { ParameterType = ParameterType.Substring(ParameterType.LastIndexOf(".") + 1); } if (p.TypeReference.Type == "System.Nullable") { ParameterType = ParameterType.Replace("Nullable", "Nullable[" + p.TypeReference.GenericTypes[0].ToString() + "]"); } if (p.TypeReference.IsArrayType) { ParameterType += ".ARRAY"; } // if (ParameterType == "SortedList") // { //Console.WriteLine(p.ParameterName + "'s ParameterType = SortedList"); // ParameterType = ParameterType.Replace("List", "List[" + // p.TypeReference.GenericTypes[0].ToString() + "," + // p.TypeReference.GenericTypes[1].ToString() + "]"); // ParameterType = ParameterType.Replace("System.", String.Empty); // } ParameterType = ParameterType.Replace("Boolean", "bool"); ParameterType = ParameterType.Replace("Int32", "int"); ParameterType = ParameterType.Replace("Int64", "long"); ParameterTypes += ParameterType + ";"; } ParameterTypes = ParameterTypes.ToUpper(); snippet.SetCodelet("PARAMETERTYPES", ParameterTypes); return(snippet); } else if (attr.Name == "CheckServerAdminToken") { ProcessTemplate snippet = ATemplate.GetSnippet("CHECKSERVERADMINPERMISSION"); string paramdefinition = "string AServerAdminSecurityToken"; if (ATemplate.FCodelets["PARAMETERDEFINITION"].Length != 0) { paramdefinition += ", "; } ATemplate.AddToCodeletPrepend("PARAMETERDEFINITION", paramdefinition); return(snippet); } } } } TLogging.Log("Warning !!! Missing module access permissions for " + AConnectorClassWithNamespace + "::" + m.Name); return(new ProcessTemplate()); }
static private void WriteUIConnector(string connectorname, TypeDeclaration connectorClass, ProcessTemplate Template) { List <string> MethodNames = new List <string>(); foreach (ConstructorDeclaration m in CSParser.GetConstructors(connectorClass)) { if (TCollectConnectorInterfaces.IgnoreMethod(m.Attributes, m.Modifier)) { continue; } string connectorNamespaceName = ((NamespaceDeclaration)connectorClass.Parent).Name; if (!FUsingNamespaces.ContainsKey(connectorNamespaceName)) { FUsingNamespaces.Add(connectorNamespaceName, connectorNamespaceName); } ProcessTemplate snippet = Template.GetSnippet("UICONNECTORCONSTRUCTOR"); snippet.SetCodelet("UICONNECTORCLASS", connectorClass.Name); snippet.SetCodelet("CHECKUSERMODULEPERMISSIONS", "// TODO CHECKUSERMODULEPERMISSIONS"); PrepareParametersForMethod(snippet, null, m.Parameters, m.Name, ref MethodNames); Template.InsertSnippet("UICONNECTORS", snippet); } // foreach public method create a method foreach (MethodDeclaration m in CSParser.GetMethods(connectorClass)) { if (TCollectConnectorInterfaces.IgnoreMethod(m.Attributes, m.Modifier)) { continue; } ProcessTemplate snippet = Template.GetSnippet("UICONNECTORMETHOD"); snippet.SetCodelet("METHODNAME", m.Name); snippet.SetCodelet("UICONNECTORCLASS", connectorClass.Name); snippet.SetCodelet("CHECKUSERMODULEPERMISSIONS", "// TODO CHECKUSERMODULEPERMISSIONS"); PrepareParametersForMethod(snippet, m.TypeReference, m.Parameters, m.Name, ref MethodNames); if (snippet.FCodelets["PARAMETERDEFINITION"].Length > 0) { snippet.AddToCodeletPrepend("PARAMETERDEFINITION", ", "); } Template.InsertSnippet("UICONNECTORS", snippet); } // foreach public property create a method foreach (PropertyDeclaration p in CSParser.GetProperties(connectorClass)) { if (TCollectConnectorInterfaces.IgnoreMethod(p.Attributes, p.Modifier)) { continue; } string propertytype = p.TypeReference.ToString(); // check if the parametertype is not a generic type, eg. dictionary or list if (!propertytype.Contains("<")) { propertytype = propertytype == "string" || propertytype == "String" ? "System.String" : propertytype; propertytype = propertytype == "bool" || propertytype == "Boolean" ? "System.Boolean" : propertytype; if (propertytype.Contains("UINT") || propertytype.Contains("unsigned")) { propertytype = propertytype.Contains("UInt32") || propertytype == "unsigned int" ? "System.UInt32" : propertytype; propertytype = propertytype.Contains("UInt16") || propertytype == "unsigned short" ? "System.UInt16" : propertytype; propertytype = propertytype.Contains("UInt64") || propertytype == "unsigned long" ? "System.UInt64" : propertytype; } else { propertytype = propertytype.Contains("Int32") || propertytype == "int" ? "System.Int32" : propertytype; propertytype = propertytype.Contains("Int16") || propertytype == "short" ? "System.Int16" : propertytype; propertytype = propertytype.Contains("Int64") || propertytype == "long" ? "System.Int64" : propertytype; } propertytype = propertytype.Contains("Decimal") || propertytype == "decimal" ? "System.Decimal" : propertytype; } bool BinaryReturn = !((propertytype == "System.Int64") || (propertytype == "System.Int32") || (propertytype == "System.Int16") || (propertytype == "System.String") || (propertytype == "System.Boolean")); string EncodedType = propertytype; string EncodeReturnType = string.Empty; string ActualValue = "AValue"; if (BinaryReturn) { EncodedType = "System.String"; EncodeReturnType = "THttpBinarySerializer.SerializeObject"; ActualValue = "(" + propertytype + ")THttpBinarySerializer.DeserializeObject(AValue)"; } ProcessTemplate propertySnippet = Template.GetSnippet("UICONNECTORPROPERTY"); propertySnippet.SetCodelet("UICONNECTORCLASS", connectorClass.Name); propertySnippet.SetCodelet("ENCODEDTYPE", EncodedType); propertySnippet.SetCodelet("PROPERTYNAME", p.Name); if (p.HasGetRegion) { if (p.TypeReference.ToString().StartsWith("I")) { if (p.TypeReference.ToString() == "IAsynchronousExecutionProgress") { FContainsAsynchronousExecutionProgress = true; } // return the ObjectID of the Sub-UIConnector propertySnippet.InsertSnippet("GETTER", Template.GetSnippet("GETSUBUICONNECTOR")); propertySnippet.SetCodelet("ENCODEDTYPE", "System.String"); } else { propertySnippet.SetCodelet("GETTER", "return {#ENCODERETURNTYPE}((({#UICONNECTORCLASS})FUIConnectors[ObjectID]).{#PROPERTYNAME});"); propertySnippet.SetCodelet("ENCODERETURNTYPE", EncodeReturnType); } } if (p.HasSetRegion) { propertySnippet.SetCodelet("SETTER", "true"); propertySnippet.SetCodelet("ACTUALPARAMETERS", ActualValue); } Template.InsertSnippet("UICONNECTORS", propertySnippet); } }
/// <summary> /// write the interfaces for the methods that need to be reflected /// check connector files /// </summary> /// <param name="ATemplate"></param> /// <param name="AMethodsAlreadyWritten">write methods only once</param> /// <param name="AConnectorClasses">the classes that are implementing the methods</param> /// <param name="AInterfaceName">the interface that is written at the moment</param> /// <param name="AInterfaceNamespace">only needed to shorten the type names to improve readability</param> /// <param name="AServerNamespace">for the comment in the autogenerated code</param> /// <returns></returns> private bool WriteConnectorMethods( ProcessTemplate ATemplate, ref StringCollection AMethodsAlreadyWritten, List <TypeDeclaration> AConnectorClasses, String AInterfaceName, String AInterfaceNamespace, String AServerNamespace) { foreach (TypeDeclaration t in AConnectorClasses) { string ConnectorClassName = t.Name; foreach (PropertyDeclaration p in CSParser.GetProperties(t)) { if (TCollectConnectorInterfaces.IgnoreMethod(p.Attributes, p.Modifier)) { continue; } // don't write namespace hierarchy here if (p.TypeReference.Type.IndexOf("Namespace") == -1) { String returnType = AutoGenerationTools.TypeToString(p.TypeReference, AInterfaceNamespace); // this interface got implemented somewhere on the server ProcessTemplate snippet = ATemplate.GetSnippet("CONNECTORPROPERTY"); snippet.SetCodelet("CONNECTORCLASSNAME", ConnectorClassName); snippet.SetCodelet("SERVERNAMESPACE", AServerNamespace); snippet.SetCodelet("TYPE", returnType); snippet.SetCodelet("NAME", p.Name); if (p.HasGetRegion) { snippet.SetCodelet("GETTER", "true"); } if (p.HasSetRegion) { snippet.SetCodelet("SETTER", "true"); } ATemplate.InsertSnippet("CONTENT", snippet); } } foreach (MethodDeclaration m in CSParser.GetMethods(t)) { string MethodName = m.Name; if (TCollectConnectorInterfaces.IgnoreMethod(m.Attributes, m.Modifier)) { continue; } String formattedMethod = ""; String returnType = AutoGenerationTools.TypeToString(m.TypeReference, AInterfaceNamespace); int align = (returnType + " " + m.Name).Length + 1; // this interface got implemented somewhere on the server formattedMethod = "/// <summary> auto generated from Connector method(" + AServerNamespace + "." + ConnectorClassName + ")</summary>" + Environment.NewLine; formattedMethod += returnType + " " + m.Name + "("; bool firstParameter = true; foreach (ParameterDeclarationExpression p in m.Parameters) { if (!firstParameter) { ATemplate.AddToCodelet("CONTENT", formattedMethod + "," + Environment.NewLine); formattedMethod = new String(' ', align); } firstParameter = false; String parameterType = AutoGenerationTools.TypeToString(p.TypeReference, ""); if ((p.ParamModifier & ParameterModifiers.Ref) != 0) { formattedMethod += "ref "; } else if ((p.ParamModifier & ParameterModifiers.Out) != 0) { formattedMethod += "out "; } formattedMethod += parameterType + " " + p.ParameterName; } formattedMethod += ");"; AMethodsAlreadyWritten.Add(MethodName); ATemplate.AddToCodelet("CONTENT", formattedMethod + Environment.NewLine); } } return(true); }
private Boolean CreateConnectors(String AOutputPath, String AModulePath, String ATemplateDir) { // Work out the module name from the module path string[] items = AModulePath.Split(new char[] { Path.DirectorySeparatorChar }); if (items.Length == 0) { // the -inputclient command line parameter must be wrong return(false); } // Module name is e.g. MCommon, MPartner etc string moduleName = items[items.Length - 1]; // Work out the actual folder/file for the output file String OutputFolder = AOutputPath + Path.DirectorySeparatorChar + "lib" + Path.DirectorySeparatorChar + moduleName + Path.DirectorySeparatorChar + "web"; String OutputFile = OutputFolder + Path.DirectorySeparatorChar + "ReferenceCount-generated.cs"; Console.WriteLine("working on " + OutputFile); // Where is the template? String templateFilename = ATemplateDir + Path.DirectorySeparatorChar + "ORM" + Path.DirectorySeparatorChar + "ReferenceCountWebConnector.cs"; if (!File.Exists(templateFilename)) { // The -templatedir command line parameter must have been wrong return(false); } // Open the template ProcessTemplate Template = new ProcessTemplate(templateFilename); // now we need to remove the leading 'M' from the module name moduleName = moduleName.Substring(1); string className = "T" + moduleName + "ReferenceCountWebConnector"; Console.WriteLine("Starting connector for " + className + Environment.NewLine); int cacheableCount = 0; int nonCacheableCount = 0; // load default header with license and copyright Template.SetCodelet("GPLFILEHEADER", ProcessTemplate.LoadEmptyFileComment(ATemplateDir)); Template.SetCodelet("TOPLEVELMODULE", moduleName); Template.SetCodelet("CLASSNAME", className); Template.SetCodelet("CACHEABLETABLECASES", string.Empty); Template.SetCodelet("CACHEABLETABLENAME", string.Empty); Template.SetCodelet("CACHEABLETABLECASE", string.Empty); Template.SetCodelet("CACHEABLETABLELISTNAME", string.Empty); Template.SetCodelet("CACHEABLETRANSACTION", string.Empty); Template.SetCodelet("CACHEABLEFINALLY", string.Empty); Template.SetCodelet("TABLESIF", string.Empty); Template.SetCodelet("TABLESELSEIF", string.Empty); Template.SetCodelet("TABLESELSE", string.Empty); Template.SetCodelet("TABLENAME", string.Empty); Template.SetCodelet("NONCACHEABLETRANSACTION", string.Empty); Template.SetCodelet("NONCACHEABLEFINALLY", string.Empty); // Find all the YAML files in the client module folder string[] clientFiles = Directory.GetFiles(AModulePath, "*.yaml", SearchOption.AllDirectories); foreach (String fn in clientFiles) { // only look for main files, not language specific files (*.xy-XY.yaml or *.xy.yaml) if (TProcessYAMLForms.IgnoreLanguageSpecificYamlFile(fn)) { continue; } XmlDocument doc = TYml2Xml.CreateXmlDocument(); SortedList sortedNodes = null; TCodeStorage codeStorage = new TCodeStorage(doc, sortedNodes); TParseYAMLFormsDefinition yamlParser = new TParseYAMLFormsDefinition(ref codeStorage); yamlParser.LoadRecursively(fn, null); string attDetailTableName = codeStorage.GetAttribute("DetailTable"); string attCacheableListName = codeStorage.GetAttribute("CacheableTable"); // Note - this IF clause needs to be the same as the one in FormWriter.cs which is generating the client side code // Do Ctrl+F to find: this IF clause needs to be the same // in that file if ((attDetailTableName != String.Empty) && (codeStorage.FControlList.ContainsKey("btnDelete") || codeStorage.FControlList.ContainsKey("btnDeleteType") || codeStorage.FControlList.ContainsKey("btnDeleteExtract") || codeStorage.FControlList.ContainsKey("btnDeleteDetail") || (codeStorage.FControlList.ContainsKey("btnRemoveDetail") && (codeStorage.GetAttribute("FormType") != "report")))) { if (attCacheableListName != String.Empty) { ProcessTemplate snippet = Template.GetSnippet("CACHEABLETABLECASE"); snippet.SetCodelet("CACHEABLETABLENAME", attDetailTableName); snippet.SetCodelet("CACHEABLETABLELISTNAME", attCacheableListName); Template.InsertSnippet("CACHEABLETABLECASES", snippet); if (cacheableCount == 0) { // Add these on the first time through snippet = Template.GetSnippet("CACHEABLETRANSACTIONSNIP"); Template.InsertSnippet("CACHEABLETRANSACTION", snippet); snippet = Template.GetSnippet("CACHEABLEFINALLYSNIP"); Template.InsertSnippet("CACHEABLEFINALLY", snippet); } Console.WriteLine("Creating cacheable reference count connector for " + attCacheableListName); cacheableCount++; } else { ProcessTemplate snippet = null; if (nonCacheableCount == 0) { snippet = Template.GetSnippet("TABLEIF"); snippet.SetCodelet("TABLENAME", attDetailTableName); Template.InsertSnippet("TABLESIF", snippet); snippet = Template.GetSnippet("NONCACHEABLETRANSACTIONSNIP"); Template.InsertSnippet("NONCACHEABLETRANSACTION", snippet); snippet = Template.GetSnippet("NONCACHEABLEFINALLYSNIP"); Template.InsertSnippet("NONCACHEABLEFINALLY", snippet); } else { snippet = Template.GetSnippet("TABLEELSEIF"); snippet.SetCodelet("TABLENAME", attDetailTableName); Template.InsertSnippet("TABLESELSEIF", snippet); } Console.WriteLine("Creating non-cacheable reference count connector for " + attDetailTableName); nonCacheableCount++; } } } // Now we finish off the template content depending on how many entries we made if ((nonCacheableCount == 0) && (cacheableCount > 0)) { ProcessTemplate snippet = Template.GetSnippet("TABLENONE"); Template.InsertSnippet("TABLESELSE", snippet); } if (nonCacheableCount > 0) { ProcessTemplate snippet = Template.GetSnippet("TABLEELSE"); Template.InsertSnippet("TABLESELSE", snippet); } if ((cacheableCount > 0) || (nonCacheableCount > 0)) { if (!Directory.Exists(OutputFolder)) { // The -outputserver command line parameter must be wrong, or the directory does not exist yet // Directories must be manually created and added to source code control Console.WriteLine("Error: directory does not exist: " + OutputFolder); return(false); } Console.WriteLine("Finishing connector for " + className + Environment.NewLine + Environment.NewLine); Template.FinishWriting(OutputFile, ".cs", true); FTotalCacheable += cacheableCount; FTotalNonCacheable += nonCacheableCount; FTotalConnectors++; } return(true); }
private static void ImplementUIConnector( SortedList <string, TypeDeclaration> connectors, ProcessTemplate ATemplate, string AFullNamespace) { string ConnectorNamespace = AFullNamespace. Replace("Instantiator.", string.Empty); List <TypeDeclaration> ConnectorClasses = TCollectConnectorInterfaces.FindTypesInNamespace(connectors, ConnectorNamespace); ConnectorNamespace = ConnectorNamespace. Replace(".Shared.", ".Server."); foreach (TypeDeclaration connectorClass in ConnectorClasses) { foreach (ConstructorDeclaration m in CSParser.GetConstructors(connectorClass)) { if (TCollectConnectorInterfaces.IgnoreMethod(m.Attributes, m.Modifier)) { continue; } ProcessTemplate snippet; FModuleHasUIConnector = true; if (FCompileForStandalone) { if (!FUsingNamespaces.ContainsKey(ConnectorNamespace)) { FUsingNamespaces.Add(ConnectorNamespace, ConnectorNamespace); } snippet = ATemplate.GetSnippet("UICONNECTORMETHODSTANDALONE"); } else { snippet = ATemplate.GetSnippet("UICONNECTORMETHODREMOTE"); } string ParameterDefinition = string.Empty; string ActualParameters = string.Empty; AutoGenerationTools.FormatParameters(m.Parameters, out ActualParameters, out ParameterDefinition); string methodname = m.Name.Substring(1); if (methodname.EndsWith("UIConnector")) { methodname = methodname.Substring(0, methodname.LastIndexOf("UIConnector")); } string interfacename = CSParser.GetImplementedInterface(connectorClass); snippet.SetCodelet("METHODNAME", methodname); snippet.SetCodelet("PARAMETERDEFINITION", ParameterDefinition); snippet.SetCodelet("ACTUALPARAMETERS", ActualParameters); snippet.SetCodelet("UICONNECTORINTERFACE", interfacename); snippet.SetCodelet("UICONNECTORCLASSNAME", connectorClass.Name); snippet.SetCodelet("UICONNECTORCLASS", string.Empty); if (!FCompileForStandalone) { if (!FUIConnectorsAdded.Contains(connectorClass.Name)) { FUIConnectorsAdded.Add(connectorClass.Name); snippet.InsertSnippet("UICONNECTORCLASS", GenerateUIConnector(ATemplate, connectorClass, interfacename)); } } ATemplate.InsertSnippet("CONNECTORMETHODS", snippet); } } }
private static void InsertMethodsAndProperties(ProcessTemplate template, TypeDeclaration t) { List <string> MethodNames = new List <string>(); // foreach public method create a method foreach (MethodDeclaration m in CSParser.GetMethods(t)) { if (TCollectConnectorInterfaces.IgnoreMethod(m.Attributes, m.Modifier)) { continue; } ProcessTemplate methodSnippet = template.GetSnippet("UICONNECTORMETHOD"); InsertMethodCall(methodSnippet, t, m, ref MethodNames); template.InsertSnippet("METHODSANDPROPERTIES", methodSnippet); } // foreach public property create a method foreach (PropertyDeclaration p in CSParser.GetProperties(t)) { if (TCollectConnectorInterfaces.IgnoreMethod(p.Attributes, p.Modifier)) { continue; } ProcessTemplate propertySnippet = template.GetSnippet("UICONNECTORPROPERTY"); string type = AutoGenerationTools.TypeToString(p.TypeReference, string.Empty); propertySnippet.SetCodelet("NAME", p.Name); propertySnippet.SetCodelet("TYPE", type); string expectedreturntype = GetExpectedReturnType(0, AutoGenerationTools.TypeToString(p.TypeReference, string.Empty)); propertySnippet.SetCodelet("EXPECTEDRETURNTYPE", expectedreturntype); if (p.HasGetRegion) { if (type.StartsWith("I")) { propertySnippet.SetCodelet( "GETTER", "return new T" + type.Substring( 1) + "(\"M{#TOPLEVELMODULE}\", THttpConnector.ReadUIConnectorProperty(FObjectID, \"M{#TOPLEVELMODULE}\", \"{#UICONNECTORCLASSNAME}\", \"{#NAME}\", \"System.String\").ToString());"); } else { propertySnippet.SetCodelet( "GETTER", "return ({#TYPE}) THttpConnector.ReadUIConnectorProperty(FObjectID, \"M{#TOPLEVELMODULE}\", \"{#UICONNECTORCLASSNAME}\", \"{#NAME}\", \"{#EXPECTEDRETURNTYPE}\");"); } } if (p.HasSetRegion) { propertySnippet.SetCodelet("SETTER", "yes"); } template.InsertSnippet("METHODSANDPROPERTIES", propertySnippet); } }
/// <summary> /// write the definition for the code of validation of a typed table /// </summary> /// <param name="Template"></param> /// <param name="currentTable"></param> /// <param name="origTable"></param> /// <param name="WhereToInsert"></param> public static void InsertTableValidation(ProcessTemplate Template, TTable currentTable, TTable origTable, string WhereToInsert) { ProcessTemplate snippet = Template.GetSnippet("TABLEVALIDATION"); ProcessTemplate deletableRowSnippet = Template.GetSnippet("SNIPDELETABLEROWVALIDATION"); string ReasonForAutomValidation; bool CheckForEmptyDateGenerated; bool FoundDeletableRowValidation = false; snippet.SetCodeletComment("TABLE_DESCRIPTION", currentTable.strDescription); snippet.SetCodelet("TABLENAME", currentTable.strDotNetName); foreach (TTableField col in currentTable.grpTableField) { ProcessTemplate columnTemplate; ProcessTemplate validateColumnTemplate; if ((col.strNameDotNet == "Deletable") || (col.strNameDotNet == "DeletableFlag") || (col.strNameDotNet == "TypeDeletable")) { deletableRowSnippet.SetCodelet("TABLENAME", currentTable.strDotNetName); deletableRowSnippet.SetCodelet("COLUMNNAME", col.strNameDotNet); FoundDeletableRowValidation = true; } CheckForEmptyDateGenerated = false; // NOT NULL checks if (TDataValidation.GenerateAutoValidationCodeForDBTableField(col, TDataValidation.TAutomDataValidationScope.advsNotNullChecks, currentTable.grpConstraint, out ReasonForAutomValidation)) { if (col.GetDotNetType().Contains("DateTime")) { // CHECKEMPTYDATE has NULL as invalid so we use this test with VALIDATECOLUMN2 (test not enclosed in 'if') validateColumnTemplate = Template.GetSnippet("CHECKEMPTYDATE"); validateColumnTemplate.SetCodelet("COLUMNNAME", col.strNameDotNet); columnTemplate = Template.GetSnippet("VALIDATECOLUMN2"); columnTemplate.InsertSnippet("COLUMNSPECIFICCHECK", validateColumnTemplate); columnTemplate.SetCodelet("COLUMNNAME", col.strNameDotNet); columnTemplate.SetCodelet("COLUMNSPECIFICCOMMENT", "'" + col.strNameDotNet + "' " + ReasonForAutomValidation); snippet.InsertSnippet("VALIDATECOLUMNS", columnTemplate); CheckForEmptyDateGenerated = true; } else { // Check all other types with a general NOT NULL check - again using VALIDATECOLUMN2 (test not enclosed in 'if') validateColumnTemplate = Template.GetSnippet("CHECKGENERALNOTNULL"); validateColumnTemplate.SetCodelet("COLUMNNAME", col.strNameDotNet); columnTemplate = Template.GetSnippet("VALIDATECOLUMN2"); columnTemplate.InsertSnippet("COLUMNSPECIFICCHECK", validateColumnTemplate); columnTemplate.SetCodelet("COLUMNNAME", col.strNameDotNet); columnTemplate.SetCodelet("COLUMNSPECIFICCOMMENT", "'" + col.strNameDotNet + "' " + ReasonForAutomValidation); snippet.InsertSnippet("VALIDATECOLUMNS", columnTemplate); } // Additionally we do not allow empty string in primary keys or columns that are foreign keys if (col.GetDotNetType().Contains("String") && ReasonForAutomValidation.Contains(" and ")) { validateColumnTemplate = Template.GetSnippet("CHECKEMPTYSTRING"); validateColumnTemplate.SetCodelet("COLUMNNAME", col.strNameDotNet); columnTemplate = Template.GetSnippet("VALIDATECOLUMN"); columnTemplate.InsertSnippet("COLUMNSPECIFICCHECK", validateColumnTemplate); columnTemplate.SetCodelet("COLUMNNAME", col.strNameDotNet); columnTemplate.SetCodelet("COLUMNSPECIFICCOMMENT", "'" + col.strNameDotNet + "' " + ReasonForAutomValidation); snippet.InsertSnippet("VALIDATECOLUMNS", columnTemplate); } } if (!CheckForEmptyDateGenerated) { // Date checks // If a NULL date is not allowed we will have already tested for that above if (TDataValidation.GenerateAutoValidationCodeForDBTableField(col, TDataValidation.TAutomDataValidationScope.advsDateChecks, null, out ReasonForAutomValidation)) { columnTemplate = Template.GetSnippet("VALIDATECOLUMN2"); columnTemplate.SetCodelet("COLUMNNAME", col.strNameDotNet); // CHECKVALIDDATE allows NULL to be valid but ensures that otherwise the date is correctly formed validateColumnTemplate = Template.GetSnippet("CHECKVALIDDATE"); validateColumnTemplate.SetCodelet("COLUMNNAME", col.strNameDotNet); validateColumnTemplate.SetCodelet("COLUMNLENGTH", (col.iCharLength * 2).ToString()); columnTemplate.InsertSnippet("COLUMNSPECIFICCHECK", validateColumnTemplate); columnTemplate.SetCodelet("COLUMNSPECIFICCOMMENT", "'" + col.strNameDotNet + "' " + ReasonForAutomValidation); snippet.InsertSnippet("VALIDATECOLUMNS", columnTemplate); } } // String Length checks if (TDataValidation.GenerateAutoValidationCodeForDBTableField(col, TDataValidation.TAutomDataValidationScope.advsStringLengthChecks, null, out ReasonForAutomValidation)) { columnTemplate = Template.GetSnippet("VALIDATECOLUMN"); columnTemplate.SetCodelet("COLUMNNAME", col.strNameDotNet); validateColumnTemplate = Template.GetSnippet("CHECKSTRINGLENGTH"); validateColumnTemplate.SetCodelet("COLUMNNAME", col.strNameDotNet); validateColumnTemplate.SetCodelet("COLUMNLENGTH", (col.iCharLength * 2).ToString()); columnTemplate.InsertSnippet("COLUMNSPECIFICCHECK", validateColumnTemplate); columnTemplate.SetCodelet("COLUMNSPECIFICCOMMENT", "'" + col.strNameDotNet + "' " + ReasonForAutomValidation); snippet.InsertSnippet("VALIDATECOLUMNS", columnTemplate); } // Number Range checks if (TDataValidation.GenerateAutoValidationCodeForDBTableField(col, TDataValidation.TAutomDataValidationScope.advsNumberRangeChecks, null, out ReasonForAutomValidation)) { columnTemplate = Template.GetSnippet("VALIDATECOLUMN"); columnTemplate.SetCodelet("COLUMNNAME", col.strNameDotNet); validateColumnTemplate = Template.GetSnippet("CHECKNUMBERRANGE"); validateColumnTemplate.SetCodelet("COLUMNNAME", col.strNameDotNet); validateColumnTemplate.SetCodelet("NUMBEROFDECIMALDIGITS", col.iLength.ToString()); validateColumnTemplate.SetCodelet("NUMBEROFFRACTIONALDIGITS", col.iDecimals > 0 ? col.iDecimals.ToString() : "0"); columnTemplate.InsertSnippet("COLUMNSPECIFICCHECK", validateColumnTemplate); columnTemplate.SetCodelet("COLUMNSPECIFICCOMMENT", "'" + col.strNameDotNet + "' " + ReasonForAutomValidation); snippet.InsertSnippet("VALIDATECOLUMNS", columnTemplate); } } if (FoundDeletableRowValidation) { snippet.InsertSnippet("DELETABLEROWVALIDATION", deletableRowSnippet); } else { snippet.SetCodelet("DELETABLEROWVALIDATION", String.Empty); } Template.InsertSnippet(WhereToInsert, snippet); }
/// <summary> /// create the code for the definition of a typed table /// </summary> /// <param name="Template"></param> /// <param name="currentTable"></param> /// <param name="origTable"></param> /// <param name="WhereToInsert"></param> public static void InsertTableDefinition(ProcessTemplate Template, TTable currentTable, TTable origTable, string WhereToInsert) { ProcessTemplate snippet = Template.GetSnippet("TYPEDTABLE"); string derivedTable = ""; if (origTable != null) { snippet.SetCodelet("BASECLASSTABLE", TTable.NiceTableName(currentTable.strName) + "Table"); derivedTable = "new "; snippet.SetCodelet("TABLEID", origTable.iOrder.ToString()); } else { snippet.SetCodelet("BASECLASSTABLE", "TTypedDataTable"); snippet.SetCodelet("TABLEID", currentTable.iOrder.ToString()); } snippet.SetCodelet("NEW", derivedTable); snippet.SetCodeletComment("TABLE_DESCRIPTION", currentTable.strDescription); snippet.SetCodelet("TABLENAME", currentTable.strDotNetName); if (currentTable.strVariableNameInDataset != null) { snippet.SetCodelet("TABLEVARIABLENAME", currentTable.strVariableNameInDataset); } else { snippet.SetCodelet("TABLEVARIABLENAME", currentTable.strDotNetName); } snippet.SetCodelet("DBTABLENAME", currentTable.strName); snippet.SetCodelet("DBTABLELABEL", currentTable.strLabel); if (currentTable.HasPrimaryKey()) { TConstraint primKey = currentTable.GetPrimaryKey(); bool first = true; string primaryKeyColumns = ""; int prevIndex = -1; // the fields in the primary key should be used in the same order as in the table. // otherwise this is causing confusion. eg. a_processed_fee foreach (TTableField column in currentTable.grpTableField) { int newIndex = -1; if (primKey.strThisFields.Contains(column.strName)) { newIndex = primKey.strThisFields.IndexOf(column.strName); } else if (primKey.strThisFields.Contains(TTable.NiceFieldName(column))) { newIndex = primKey.strThisFields.IndexOf(TTable.NiceFieldName(column)); } if (newIndex != -1) { if (newIndex < prevIndex) { throw new Exception("Please fix the order of the fields in the primary key of table " + currentTable.strName); } prevIndex = newIndex; } } // the fields in the primary key should be used in the same order as in the table. // otherwise this is causing confusion. eg. a_processed_fee foreach (TTableField column in currentTable.grpTableField) { if (primKey.strThisFields.Contains(column.strName) || primKey.strThisFields.Contains(TTable.NiceFieldName(column))) { string columnName = column.strName; string toAdd = currentTable.grpTableField.IndexOf(currentTable.GetField(columnName)).ToString(); if (!first) { toAdd = ", " + toAdd; primaryKeyColumns += ","; } first = false; snippet.AddToCodelet("COLUMNPRIMARYKEYORDER", toAdd); primaryKeyColumns += "Column" + TTable.NiceFieldName(currentTable.GetField(columnName)); } } if (primaryKeyColumns.Length > 0) { snippet.SetCodelet("PRIMARYKEYCOLUMNS", primaryKeyColumns); snippet.SetCodelet("PRIMARYKEYCOLUMNSCOUNT", primKey.strThisFields.Count.ToString()); } } else { snippet.AddToCodelet("COLUMNPRIMARYKEYORDER", ""); } if (currentTable.HasUniqueKey()) { TConstraint primKey = currentTable.GetFirstUniqueKey(); bool first = true; foreach (string columnName in primKey.strThisFields) { string toAdd = currentTable.grpTableField.IndexOf(currentTable.GetField(columnName)).ToString(); if (!first) { toAdd = ", " + toAdd; } first = false; snippet.AddToCodelet("COLUMNUNIQUEKEYORDER", toAdd); } } else { snippet.AddToCodelet("COLUMNUNIQUEKEYORDER", ""); } int colOrder = 0; foreach (TTableField col in currentTable.grpTableField) { col.strTableName = currentTable.strName; ProcessTemplate tempTemplate = null; string columnOverwrite = ""; bool writeColumnProperties = true; if ((origTable != null) && (origTable.GetField(col.strName, false) != null)) { columnOverwrite = "new "; if (origTable.GetField(col.strName).iOrder == colOrder) { // same order number, save some lines of code by not writing them writeColumnProperties = false; } } if (writeColumnProperties && (columnOverwrite.Length == 0)) { tempTemplate = Template.GetSnippet("DATACOLUMN"); tempTemplate.SetCodeletComment("COLUMN_DESCRIPTION", col.strDescription); tempTemplate.SetCodelet("COLUMNNAME", TTable.NiceFieldName(col)); snippet.InsertSnippet("DATACOLUMNS", tempTemplate); } if (writeColumnProperties) { tempTemplate = Template.GetSnippet("COLUMNIDS"); tempTemplate.SetCodelet("COLUMNNAME", TTable.NiceFieldName(col)); tempTemplate.SetCodelet("COLUMNORDERNUMBER", colOrder.ToString()); tempTemplate.SetCodelet("NEW", columnOverwrite); snippet.InsertSnippet("COLUMNIDS", tempTemplate); } if (origTable == null) { tempTemplate = Template.GetSnippet("COLUMNINFO"); tempTemplate.SetCodelet("COLUMNORDERNUMBER", colOrder.ToString()); tempTemplate.SetCodelet("COLUMNNAME", TTable.NiceFieldName(col)); tempTemplate.SetCodelet("COLUMNDBNAME", col.strName); tempTemplate.SetCodelet("COLUMNLABEL", col.strLabel); tempTemplate.SetCodelet("COLUMNODBCTYPE", CodeGenerationPetra.ToOdbcTypeString(col)); tempTemplate.SetCodelet("COLUMNLENGTH", col.iLength.ToString()); tempTemplate.SetCodelet("COLUMNNOTNULL", col.bNotNull.ToString().ToLower()); tempTemplate.SetCodelet("COLUMNCOMMA", colOrder + 1 < currentTable.grpTableField.Count ? "," : ""); snippet.InsertSnippet("COLUMNINFO", tempTemplate); } tempTemplate = Template.GetSnippet("INITCLASSADDCOLUMN"); tempTemplate.SetCodelet("COLUMNDBNAME", col.strName); tempTemplate.SetCodelet("COLUMNDOTNETTYPE", col.GetDotNetType()); tempTemplate.SetCodelet("COLUMNDOTNETTYPENOTNULLABLE", col.GetDotNetType().Replace("?", "")); snippet.InsertSnippet("INITCLASSADDCOLUMN", tempTemplate); tempTemplate = Template.GetSnippet("INITVARSCOLUMN"); tempTemplate.SetCodelet("COLUMNDBNAME", col.strName); tempTemplate.SetCodelet("COLUMNNAME", TTable.NiceFieldName(col)); snippet.InsertSnippet("INITVARSCOLUMN", tempTemplate); if (writeColumnProperties) { tempTemplate = Template.GetSnippet("STATICCOLUMNPROPERTIES"); tempTemplate.SetCodelet("COLUMNDBNAME", col.strName); tempTemplate.SetCodelet("COLUMNNAME", TTable.NiceFieldName(col)); tempTemplate.SetCodelet("COLUMNHELP", col.strHelp.Replace("\"", "\\\"")); tempTemplate.SetCodelet("COLUMNLENGTH", col.iLength.ToString()); tempTemplate.SetCodelet("NEW", columnOverwrite); snippet.InsertSnippet("STATICCOLUMNPROPERTIES", tempTemplate); } colOrder++; } Template.InsertSnippet(WhereToInsert, snippet); }
/// <summary> /// write the definition for the code of a typed row /// </summary> /// <param name="Template"></param> /// <param name="currentTable"></param> /// <param name="origTable"></param> /// <param name="WhereToInsert"></param> public static void InsertRowDefinition(ProcessTemplate Template, TTable currentTable, TTable origTable, string WhereToInsert) { ProcessTemplate snippet = Template.GetSnippet("TYPEDROW"); if (origTable != null) { snippet.SetCodelet("BASECLASSROW", TTable.NiceTableName(currentTable.strName) + "Row"); snippet.SetCodelet("OVERRIDE", "override "); } else { snippet.SetCodelet("BASECLASSROW", "System.Data.DataRow"); snippet.SetCodelet("OVERRIDE", "virtual "); } snippet.SetCodeletComment("TABLE_DESCRIPTION", currentTable.strDescription); snippet.SetCodelet("TABLENAME", currentTable.strDotNetName); foreach (TTableField col in currentTable.grpTableField) { ProcessTemplate tempTemplate = null; string columnOverwrite = ""; if ((origTable != null) && (origTable.GetField(col.strName, false) != null)) { columnOverwrite = "new "; } if (columnOverwrite.Length == 0) { tempTemplate = Template.GetSnippet("ROWCOLUMNPROPERTY"); tempTemplate.SetCodelet("COLUMNDBNAME", col.strName); tempTemplate.SetCodelet("COLUMNNAME", col.strNameDotNet); tempTemplate.SetCodelet("COLUMNHELP", col.strDescription.Replace(Environment.NewLine, " ")); tempTemplate.SetCodelet("COLUMNLABEL", col.strLabel); tempTemplate.SetCodelet("COLUMNLENGTH", col.iLength.ToString()); tempTemplate.SetCodelet("COLUMNDOTNETTYPE", col.GetDotNetType()); if (!col.bNotNull) { if (col.GetDotNetType().Contains("DateTime?")) { tempTemplate.SetCodelet("TESTFORNULL", "!value.HasValue"); } else if (col.GetDotNetType().Contains("String")) { tempTemplate.SetCodelet("TESTFORNULL", "(value == null) || (value.Length == 0)"); } } if (col.GetDotNetType().Contains("DateTime?")) { tempTemplate.SetCodelet("ACTIONGETNULLVALUE", "return null;"); } else if (col.GetDotNetType().Contains("DateTime")) { tempTemplate.SetCodelet("ACTIONGETNULLVALUE", "return DateTime.MinValue;"); } else if (col.GetDotNetType().ToLower().Contains("string")) { tempTemplate.SetCodelet("ACTIONGETNULLVALUE", "return String.Empty;"); } else { tempTemplate.SetCodelet("ACTIONGETNULLVALUE", "throw new System.Data.StrongTypingException(\"Error: DB null\", null);"); } tempTemplate.SetCodeletComment("COLUMN_DESCRIPTION", col.strDescription); snippet.InsertSnippet("ROWCOLUMNPROPERTIES", tempTemplate); tempTemplate = Template.GetSnippet("FUNCTIONSFORNULLVALUES"); tempTemplate.SetCodelet("COLUMNNAME", TTable.NiceFieldName(col)); snippet.InsertSnippet("FUNCTIONSFORNULLVALUES", tempTemplate); } if ((col.strDefault.Length > 0) && (col.strDefault != "NULL")) { string defaultValue = col.strDefault; if (defaultValue == "SYSDATE") { defaultValue = "DateTime.Today"; } else if ((col.strType == "bit") || ((col.strTypeDotNet != null) && col.strTypeDotNet.ToLower().Contains("bool"))) { defaultValue = (defaultValue == "1" || defaultValue.ToLower() == "true").ToString().ToLower(); } else if ((col.strType == "varchar") || ((col.strTypeDotNet != null) && col.strTypeDotNet.ToLower().Contains("string"))) { defaultValue = '"' + defaultValue + '"'; } snippet.AddToCodelet("ROWSETNULLORDEFAULT", "this[this.myTable.Column" + TTable.NiceFieldName( col) + ".Ordinal] = " + defaultValue + ";" + Environment.NewLine); } else { snippet.AddToCodelet("ROWSETNULLORDEFAULT", "this.SetNull(this.myTable.Column" + TTable.NiceFieldName( col) + ");" + Environment.NewLine); } } Template.InsertSnippet(WhereToInsert, snippet); }