protected static List<MorphAction> GenerateActionsViaDiffEngine() { if (_actionsViaDiffEngine != null) return _actionsViaDiffEngine; using (var agileTemplate = EmbeddedProcessTemplate.Agile6()) using (var scrumTemplate = EmbeddedProcessTemplate.Scrum2()) { var agileReader = new ProcessTemplateReader(agileTemplate.TemplatePath); var scrumReader = new ProcessTemplateReader(scrumTemplate.TemplatePath); var processTemplateMap = ProcessTemplateMap.ConvertScrum2ToAgile6(); var currentProcessTemplate = new ProcessTemplate {WorkItemTypeDefinitions = new ReadOnlyCollection<WorkItemTypeDefinition>(scrumReader.WorkItemTypeDefinitions.ToArray())}; var goalProcessTemplate = new ProcessTemplate {WorkItemTypeDefinitions = new ReadOnlyCollection<WorkItemTypeDefinition>(agileReader.WorkItemTypeDefinitions.ToArray())}; var diffEngine = new DiffEngine(processTemplateMap); var differences = diffEngine.CompareProcessTemplates(currentProcessTemplate, goalProcessTemplate); var morphEngine = new MorphEngine(); _actionsViaDiffEngine = morphEngine.GenerateActions(differences).ToList(); } return _actionsViaDiffEngine; }
/// <summary> /// insert the viaothertable functions for one specific constraint /// </summary> /// <param name="AStore"></param> /// <param name="AConstraint"></param> /// <param name="ACurrentTable"></param> /// <param name="AOtherTable"></param> /// <param name="ATemplate"></param> /// <param name="ASnippet"></param> private static void InsertViaOtherTableConstraint(TDataDefinitionStore AStore, TConstraint AConstraint, TTable ACurrentTable, TTable AOtherTable, ProcessTemplate ATemplate, ProcessTemplate ASnippet) { ATemplate.AddToCodelet("USINGNAMESPACES", GetNamespace(AOtherTable.strGroup), false); ProcessTemplate snippetViaTable = ATemplate.GetSnippet("VIAOTHERTABLE"); snippetViaTable.SetCodelet("OTHERTABLENAME", TTable.NiceTableName(AOtherTable.strName)); snippetViaTable.SetCodelet("SQLOTHERTABLENAME", AOtherTable.strName); string ProcedureName = "Via" + TTable.NiceTableName(AOtherTable.strName); // check if other foreign key exists that references the same table, e.g. // PBankAccess.CountViaPPartnerPartnerKey // PBankAccess.CountViaPPartnerContactPartnerKey string DifferentField = FindOtherConstraintSameOtherTable(ACurrentTable.grpConstraint, AConstraint); if (DifferentField.Length != 0) { ProcedureName += TTable.NiceFieldName(DifferentField); } int notUsedInt; string formalParametersOtherPrimaryKey; string actualParametersOtherPrimaryKey; string dummy; PrepareCodeletsPrimaryKey(AOtherTable, out formalParametersOtherPrimaryKey, out actualParametersOtherPrimaryKey, out dummy, out notUsedInt); int numberFields; string namesOfThisTableFields; string notUsed; PrepareCodeletsForeignKey( AOtherTable, AConstraint, out notUsed, out notUsed, out notUsed, out numberFields, out namesOfThisTableFields); snippetViaTable.SetCodelet("VIAPROCEDURENAME", ProcedureName); snippetViaTable.SetCodelet("FORMALPARAMETERSOTHERPRIMARYKEY", formalParametersOtherPrimaryKey); snippetViaTable.SetCodelet("ACTUALPARAMETERSOTHERPRIMARYKEY", actualParametersOtherPrimaryKey); snippetViaTable.SetCodelet("NUMBERFIELDS", numberFields.ToString()); snippetViaTable.SetCodelet("NUMBERFIELDSOTHER", (actualParametersOtherPrimaryKey.Split(',').Length).ToString()); snippetViaTable.SetCodelet("THISTABLEFIELDS", namesOfThisTableFields); AddDirectReference(AConstraint); ASnippet.InsertSnippet("VIAOTHERTABLE", snippetViaTable); }
public void TestTemplateEngine() { ProcessTemplate template = new ProcessTemplate(); template.FTemplateCode = new StringBuilder("my test" + Environment.NewLine + "{#IFDEF TEST1}" + Environment.NewLine + "test1" + Environment.NewLine + "{#ENDIF TEST1}" + Environment.NewLine); template.SetCodelet("TEST1", "test"); Assert.AreEqual("my test" + Environment.NewLine + "test1" + Environment.NewLine, template.FinishWriting(true), "TEST1"); template = new ProcessTemplate(); template.FTemplateCode = new StringBuilder("my test" + Environment.NewLine + "{#IFNDEF TEST2}" + Environment.NewLine + "test2" + Environment.NewLine + "{#ENDIFN TEST2}" + Environment.NewLine); template.SetCodelet("TEST2", "test"); Assert.AreEqual("my test" + Environment.NewLine, template.FinishWriting(true), "TEST2"); template = new ProcessTemplate(); template.FTemplateCode = new StringBuilder("my test" + Environment.NewLine + "{#IFNDEF TEST3}" + Environment.NewLine + "test3" + Environment.NewLine + "{#ENDIFN TEST3}" + Environment.NewLine + "hallo" + Environment.NewLine); Assert.AreEqual("my test" + Environment.NewLine + "test3" + Environment.NewLine + "hallo" + Environment.NewLine, template.FinishWriting(true), "TEST3"); template = new ProcessTemplate(); template.FTemplateCode = new StringBuilder("my test" + Environment.NewLine + "{#IFDEF TEST1}" + Environment.NewLine + "test1" + Environment.NewLine + "{#ENDIF TEST1}" + Environment.NewLine + "{#IFNDEF TEST2}" + Environment.NewLine + "test2" + Environment.NewLine + "{#ENDIFN TEST2}" + Environment.NewLine + "{#IFNDEF TEST3}" + Environment.NewLine + "test3" + Environment.NewLine + "{#ENDIFN TEST3}" + Environment.NewLine + "{#IFDEF TEST4}" + Environment.NewLine + "test4" + Environment.NewLine + "{#ENDIF TEST4}" + Environment.NewLine + "hallo" + Environment.NewLine); template.SetCodelet("TEST1", "test"); template.SetCodelet("TEST3", "test"); Assert.AreEqual("my test" + Environment.NewLine + "test1" + Environment.NewLine + "test2" + Environment.NewLine + "hallo" + Environment.NewLine, template.FinishWriting(true), "TEST4"); template = new ProcessTemplate(); template.FTemplateCode = new StringBuilder("my test" + Environment.NewLine + "{#IFDEF TEST5 OR TEST1}" + Environment.NewLine + "test5" + Environment.NewLine + "{#ENDIF TEST5 OR TEST1}" + Environment.NewLine); template.SetCodelet("TEST5", "test"); Assert.AreEqual("my test" + Environment.NewLine + "test5" + Environment.NewLine, template.FinishWriting(true), "TEST5"); template = new ProcessTemplate(); template.FTemplateCode = new StringBuilder("my test" + Environment.NewLine + "{#IFDEF TEST5 AND TEST6}" + Environment.NewLine + "test6" + Environment.NewLine + "{#ENDIF TEST5 AND TEST6}" + Environment.NewLine); template.SetCodelet("TEST6", "test"); Assert.AreEqual("my test" + Environment.NewLine, template.FinishWriting(true), "TEST6"); template = new ProcessTemplate(); template.FTemplateCode = new StringBuilder("my test" + Environment.NewLine + "{#IFDEF TEST6 AND TEST7}" + Environment.NewLine + "test7" + Environment.NewLine + "{#ENDIF TEST6 AND TEST7}" + Environment.NewLine); template.SetCodelet("TEST6", "test"); template.SetCodelet("TEST7", "test"); Assert.AreEqual("my test" + Environment.NewLine + "test7" + Environment.NewLine, template.FinishWriting(true), "TEST7"); template = new ProcessTemplate(); template.FTemplateCode = new StringBuilder("{#IFDEF TEST8}" + Environment.NewLine + "test8" + Environment.NewLine + "{#ENDIF TEST8}" + Environment.NewLine + "test8" + Environment.NewLine + "{#IFDEF TEST8}" + Environment.NewLine + "test8" + Environment.NewLine + "{#ENDIF TEST8}" + Environment.NewLine); template.SetCodelet("TEST8", "test"); Assert.AreEqual("test8" + Environment.NewLine + "test8" + Environment.NewLine + "test8" + Environment.NewLine, template.FinishWriting(true), "TEST8"); template = new ProcessTemplate(); template.FTemplateCode = new StringBuilder("{#IFNDEF TEST9}" + Environment.NewLine + "test8" + Environment.NewLine + "{#ENDIFN TEST9}" + Environment.NewLine + "test9" + Environment.NewLine + "{#IFNDEF TEST9}" + Environment.NewLine + "test8" + Environment.NewLine + "{#ENDIFN TEST9}" + Environment.NewLine); template.SetCodelet("TEST9", "test"); Assert.AreEqual("test9" + Environment.NewLine, template.FinishWriting(true), "TEST9"); template = new ProcessTemplate(); template.FTemplateCode = new StringBuilder("{#IFNDEF TEST10}" + Environment.NewLine + "test8" + Environment.NewLine + "{#ENDIFN TEST10}" + Environment.NewLine + "test9" + Environment.NewLine + "{#IFDEF TEST10}" + Environment.NewLine + "test10" + Environment.NewLine + "{#ENDIF TEST10}" + Environment.NewLine); template.SetCodelet("TEST10", "test"); Assert.AreEqual("test9" + Environment.NewLine + "test10" + Environment.NewLine, template.FinishWriting(true), "TEST10"); template = new ProcessTemplate(); template.FTemplateCode = new StringBuilder("{#IFDEF TEST10}" + Environment.NewLine + "{#IFDEF TEST11}" + Environment.NewLine + "{#IFDEF TEST11}" + Environment.NewLine + "test11" + Environment.NewLine + "{#ENDIF TEST11}" + Environment.NewLine + "{#ENDIF TEST11}" + Environment.NewLine + "{#IFNDEF TEST11}" + Environment.NewLine + "test10" + Environment.NewLine + "{#ENDIFN TEST11}" + Environment.NewLine + "{#ENDIF TEST10}" + Environment.NewLine + "{#IFNDEF TEST10}" + Environment.NewLine + "{#IFNDEF TEST11}" + Environment.NewLine + "{#IFDEF TEST11}" + Environment.NewLine + "test13" + Environment.NewLine + "{#ENDIF TEST11}" + Environment.NewLine + "{#ENDIFN TEST11}" + Environment.NewLine + "{#ENDIFN TEST10}" + Environment.NewLine + "test1" + Environment.NewLine); template.SetCodelet("TEST11", "test_11"); template.SetCodelet("TEST10", "test_10"); Assert.AreEqual("test11" + Environment.NewLine + "test1" + Environment.NewLine, template.FinishWriting(true), "TEST11"); }
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); } }
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); } }
static private void CreateClientGlue(TNamespace tn, SortedList <string, TypeDeclaration> connectors, string AOutputPath) { String OutputFile = AOutputPath + Path.DirectorySeparatorChar + "ClientGlue.M" + tn.Name + "-generated.cs"; Console.WriteLine("working on " + OutputFile); ProcessTemplate Template = new ProcessTemplate(FTemplateDir + Path.DirectorySeparatorChar + "ClientServerGlue" + Path.DirectorySeparatorChar + "ClientGlue.cs"); FUsingNamespaces = new SortedList <string, string>(); FModuleHasUIConnector = false; FUIConnectorsAdded = new List <string>(); // load default header with license and copyright Template.SetCodelet("GPLFILEHEADER", ProcessTemplate.LoadEmptyFileComment(FTemplateDir)); Template.SetCodelet("TOPLEVELMODULE", tn.Name); string InterfacePath = Path.GetFullPath(AOutputPath).Replace(Path.DirectorySeparatorChar, '/'); InterfacePath = InterfacePath.Substring(0, InterfacePath.IndexOf("csharp/ICT/Petra")) + "csharp/ICT/Petra/Shared/lib/Interfaces"; Template.AddToCodelet("USINGNAMESPACES", CreateInterfaces.AddNamespacesFromYmlFile(InterfacePath, tn.Name)); if (AOutputPath.Contains("ICT/Petra/Plugins/")) { // add namespaces that are required by the plugin InterfacePath = Path.GetFullPath(AOutputPath + "/../").Replace(Path.DirectorySeparatorChar, '/'); Template.AddToCodelet("USINGNAMESPACES", CreateInterfaces.AddNamespacesFromYmlFile(InterfacePath, "Plugin")); } string SharedPathName = "Ict.Petra.Shared.M" + tn.Name; if (SharedPathName.Contains("ServerAdmin")) { SharedPathName = "Ict.Petra.Server.App.Core." + tn.Name; } else if (OutputFile.Contains("ICT/Petra/Plugins")) { SharedPathName = "Ict.Petra.Plugins." + tn.Name; } InsertSubNamespaces(Template, connectors, tn.Name, SharedPathName, tn); if (FModuleHasUIConnector) { Template.AddToCodelet("USINGNAMESPACES", "using Ict.Petra.Shared.Interfaces.M" + tn.Name + ";" + Environment.NewLine); } foreach (string usingNamespace in FUsingNamespaces.Keys) { Template.AddToCodelet("USINGNAMESPACES", "using " + usingNamespace + ";" + Environment.NewLine); } if (OutputFile.Contains("ClientGlue.MServerAdmin")) { Template.SetCodelet("REMOTEOBJECTSNAMESPACE", "Ict.Petra.ServerAdmin.App.Core.RemoteObjects"); } else if (OutputFile.Contains("ICT/Petra/Plugins")) { string pluginWithNamespace = TAppSettingsManager.GetValue("plugin"); Template.SetCodelet("REMOTEOBJECTSNAMESPACE", pluginWithNamespace + ".RemoteObjects"); } else { Template.SetCodelet("REMOTEOBJECTSNAMESPACE", "Ict.Petra.Client.App.Core.RemoteObjects"); } Template.FinishWriting(OutputFile, ".cs", true); }
public ActionResult DetailJson(int id) { ProcessTemplate item = _ProcessTemplateService.FindById(id); return(Json(toProcessTemplatePOCO(item), JsonRequestBehavior.AllowGet)); }
public ActionResult CreateKendo([DataSourceRequest] DataSourceRequest request, ProcessTemplate item) { if (item != null && ModelState.IsValid) { _ProcessTemplateService.Add(item); } return(Json(new[] { item }.ToDataSourceResult(request, ModelState))); }
private void CreateAutoHierarchy(TNamespace tn, String AOutputPath) { String OutputFile = AOutputPath + Path.DirectorySeparatorChar + "M" + tn.Name + Path.DirectorySeparatorChar + "Instantiator.AutoHierarchy-generated.cs"; if (Directory.Exists(AOutputPath + Path.DirectorySeparatorChar + "M" + tn.Name + Path.DirectorySeparatorChar + "connect")) { OutputFile = AOutputPath + Path.DirectorySeparatorChar + "M" + tn.Name + Path.DirectorySeparatorChar + "connect" + Path.DirectorySeparatorChar + "Instantiator.AutoHierarchy-generated.cs"; } Console.WriteLine("working on " + OutputFile); SortedList <string, TypeDeclaration> connectors = TCollectConnectorInterfaces.GetConnectors(tn.Name); ProcessTemplate Template = new ProcessTemplate(FTemplateDir + Path.DirectorySeparatorChar + "ClientServerGlue" + Path.DirectorySeparatorChar + "Instantiator.cs"); // load default header with license and copyright Template.SetCodelet("GPLFILEHEADER", ProcessTemplate.LoadEmptyFileComment(FTemplateDir)); Template.SetCodelet("TOPLEVELMODULE", tn.Name); Template.AddToCodelet("USINGNAMESPACES", "using Ict.Petra.Shared.Interfaces.M" + tn.Name + ";" + Environment.NewLine); string InterfacePath = Path.GetFullPath(AOutputPath).Replace(Path.DirectorySeparatorChar, '/'); InterfacePath = InterfacePath.Substring(0, InterfacePath.IndexOf("csharp/ICT/Petra")) + "csharp/ICT/Petra/Shared/lib/Interfaces"; Template.AddToCodelet("USINGNAMESPACES", CreateInterfaces.AddNamespacesFromYmlFile(InterfacePath, tn.Name)); ProcessTemplate topLevelNamespaceSnippet = Template.GetSnippet("TOPLEVELNAMESPACE"); topLevelNamespaceSnippet.SetCodelet("SUBNAMESPACEREMOTABLECLASSES", ""); topLevelNamespaceSnippet.SetCodelet("TOPLEVELMODULE", tn.Name); topLevelNamespaceSnippet.InsertSnippet("LOADERCLASS", WriteLoaderClass(Template, tn.Name)); topLevelNamespaceSnippet.InsertSnippet("MAINREMOTABLECLASS", WriteRemotableClass( topLevelNamespaceSnippet, "Ict.Petra.Shared.M" + tn.Name, "TM" + tn.Name, "M" + tn.Name, true, tn.Children, connectors)); foreach (TNamespace sn in tn.Children.Values) { topLevelNamespaceSnippet.InsertSnippet("SUBNAMESPACEREMOTABLECLASSES", WriteRemotableClass( topLevelNamespaceSnippet, "Ict.Petra.Shared.M" + tn.Name + "." + sn.Name, sn.Name, sn.Name, false, sn.Children, connectors)); } Template.InsertSnippet("CONTENT", topLevelNamespaceSnippet); Template.FinishWriting(OutputFile, ".cs", true); }
private ProcessTemplate WriteRemotableClass(ProcessTemplate ATemplate, String FullNamespace, String Classname, String Namespace, Boolean HighestLevel, SortedList <string, TNamespace> children, SortedList <string, TypeDeclaration> connectors) { if ((children.Count == 0) && !HighestLevel) { return(new ProcessTemplate()); } ProcessTemplate remotableClassSnippet = ATemplate.GetSnippet("REMOTABLECLASS"); remotableClassSnippet.SetCodelet("SUBNAMESPACEREMOTABLECLASSES", string.Empty); remotableClassSnippet.SetCodelet("NAMESPACE", Namespace); remotableClassSnippet.SetCodelet("CLIENTOBJECTFOREACHPROPERTY", string.Empty); remotableClassSnippet.SetCodelet("SUBNAMESPACEPROPERTIES", string.Empty); foreach (TNamespace sn in children.Values) { ProcessTemplate subNamespaceSnippet = ATemplate.GetSnippet("SUBNAMESPACEPROPERTY"); string NamespaceName = Namespace + sn.Name; if (HighestLevel) { NamespaceName = sn.Name; } subNamespaceSnippet.SetCodelet("OBJECTNAME", sn.Name); subNamespaceSnippet.SetCodelet("NAMESPACENAME", NamespaceName); subNamespaceSnippet.SetCodelet("NAMESPACE", Namespace); remotableClassSnippet.InsertSnippet("SUBNAMESPACEPROPERTIES", subNamespaceSnippet); if (sn.Children.Count > 0) { // properties for each sub namespace foreach (TNamespace subnamespace in sn.Children.Values) { ATemplate.InsertSnippet("SUBNAMESPACEREMOTABLECLASSES", WriteRemotableClass(ATemplate, FullNamespace + "." + sn.Name + "." + subnamespace.Name, sn.Name + subnamespace.Name, NamespaceName + subnamespace.Name, false, subnamespace.Children, connectors)); } remotableClassSnippet.InsertSnippet("CLIENTOBJECTFOREACHPROPERTY", TCreateClientRemotingClass.AddClientRemotingClass( FTemplateDir, "T" + NamespaceName + "NamespaceRemote", "I" + NamespaceName + "Namespace", new List <TypeDeclaration>(), FullNamespace + "." + sn.Name, sn.Children )); } else { remotableClassSnippet.InsertSnippet("CLIENTOBJECTFOREACHPROPERTY", TCreateClientRemotingClass.AddClientRemotingClass( FTemplateDir, "T" + NamespaceName + "NamespaceRemote", "I" + NamespaceName + "Namespace", TCollectConnectorInterfaces.FindTypesInNamespace(connectors, FullNamespace + "." + sn.Name) )); } } return(remotableClassSnippet); }
/// <summary> /// Constructor /// </summary> public Capability() { Versioncontrol = new VersionControl(); ProcessTemplate = new ProcessTemplate(); }
public Capabilities(string sourceControlType, string templateTypeId) { versioncontrol = new Versioncontrol(sourceControlType); processTemplate = new ProcessTemplate(templateTypeId); }
/// <summary> /// Creates a HTML file that contains central documentation of the Error Codes that are used throughout OpenPetra code /// </summary> public static bool Execute(string ACSharpPath, string ATemplateFilePath, string AOutFilePath) { Dictionary <string, ErrCodeInfo> ErrorCodes = new Dictionary <string, ErrCodeInfo>(); CSParser parsedFile = new CSParser(ACSharpPath + "/ICT/Common/ErrorCodes.cs"); string ErrCodeCategoryNice = String.Empty; TLogging.Log("Creating HTML documentation of OpenPetra Error Codes..."); ProcessFile(parsedFile, ref ErrorCodes); parsedFile = new CSParser(ACSharpPath + "/ICT/Petra/Shared/ErrorCodes.cs"); ProcessFile(parsedFile, ref ErrorCodes); parsedFile = new CSParser(ACSharpPath + "/ICT/Common/Verification/StringChecks.cs"); ProcessFile(parsedFile, ref ErrorCodes); ProcessTemplate t = new ProcessTemplate(ATemplateFilePath); Dictionary <string, ProcessTemplate> snippets = new Dictionary <string, ProcessTemplate>(); snippets.Add("GENC", t.GetSnippet("TABLE")); snippets["GENC"].SetCodelet("TABLEDESCRIPTION", "GENERAL (<i>Ict.Common* Libraries only</i>)"); snippets.Add("GEN", t.GetSnippet("TABLE")); snippets["GEN"].SetCodelet("TABLEDESCRIPTION", "GENERAL (across the OpenPetra application)"); snippets.Add("PARTN", t.GetSnippet("TABLE")); snippets["PARTN"].SetCodelet("TABLEDESCRIPTION", "PARTNER Module"); snippets.Add("PERS", t.GetSnippet("TABLE")); snippets["PERS"].SetCodelet("TABLEDESCRIPTION", "PERSONNEL Module"); snippets.Add("FIN", t.GetSnippet("TABLE")); snippets["FIN"].SetCodelet("TABLEDESCRIPTION", "FINANCE Module"); snippets.Add("CONF", t.GetSnippet("TABLE")); snippets["CONF"].SetCodelet("TABLEDESCRIPTION", "CONFERENCE Module"); snippets.Add("FINDEV", t.GetSnippet("TABLE")); snippets["FINDEV"].SetCodelet("TABLEDESCRIPTION", "FINANCIAL DEVELOPMENT Module"); snippets.Add("SYSMAN", t.GetSnippet("TABLE")); snippets["SYSMAN"].SetCodelet("TABLEDESCRIPTION", "SYSTEM MANAGER Module"); foreach (string snippetkey in snippets.Keys) { snippets[snippetkey].SetCodelet("ABBREVIATION", snippetkey); snippets[snippetkey].SetCodelet("ROWS", string.Empty); } foreach (string code in ErrorCodes.Keys) { foreach (string snippetkey in snippets.Keys) { if (code.StartsWith(snippetkey + ".")) { ProcessTemplate row = t.GetSnippet("ROW"); row.SetCodelet("CODE", code); ErrCodeInfo ErrCode = ErrorCodes[code]; switch (ErrCode.Category) { case ErrCodeCategory.NonCriticalError: ErrCodeCategoryNice = "Non-critical Error"; break; default: ErrCodeCategoryNice = ErrCode.Category.ToString("G"); break; } row.AddToCodelet("SHORTDESCRIPTION", (ErrCode.ShortDescription)); row.AddToCodelet("FULLDESCRIPTION", (ErrCode.FullDescription)); row.AddToCodelet("ERRORCODECATEGORY", (ErrCodeCategoryNice)); row.AddToCodelet("DECLARINGCLASS", (ErrCode.ErrorCodeConstantClass)); snippets[snippetkey].InsertSnippet("ROWS", row); } } } foreach (string snippetkey in snippets.Keys) { t.InsertSnippet("TABLES", snippets[snippetkey]); } return(t.FinishWriting(AOutFilePath, ".html", true)); }
/// <summary> /// main function for creating a control /// </summary> /// <param name="ACtrl"></param> /// <param name="ATemplate"></param> /// <param name="AItemsPlaceholder"></param> /// <param name="ANodeName"></param> /// <param name="AWriter"></param> public static void InsertControl(TControlDef ACtrl, ProcessTemplate ATemplate, string AItemsPlaceholder, string ANodeName, TFormWriter AWriter) { XmlNode controlsNode = TXMLParser.GetChild(ACtrl.xmlNode, ANodeName); List <XmlNode> childNodes = TYml2Xml.GetChildren(controlsNode, true); if ((childNodes.Count > 0) && childNodes[0].Name.StartsWith("Row")) { foreach (XmlNode row in TYml2Xml.GetChildren(controlsNode, true)) { ProcessTemplate snippetRowDefinition = AWriter.FTemplate.GetSnippet("ROWDEFINITION"); StringCollection children = TYml2Xml.GetElements(controlsNode, row.Name); foreach (string child in children) { TControlDef childCtrl = AWriter.FCodeStorage.FindOrCreateControl(child, ACtrl.controlName); IControlGenerator ctrlGen = AWriter.FindControlGenerator(childCtrl); ProcessTemplate ctrlSnippet = ctrlGen.SetControlProperties(AWriter, childCtrl); ProcessTemplate snippetCellDefinition = AWriter.FTemplate.GetSnippet("CELLDEFINITION"); LayoutCellInForm(childCtrl, children.Count, ctrlSnippet, snippetCellDefinition); if ((children.Count == 1) && ctrlGen is RadioGroupSimpleGenerator) { // do not use the ROWDEFINITION, but insert control directly // this helps with aligning the label for the group radio buttons snippetRowDefinition.InsertSnippet("ITEMS", ctrlSnippet, ","); } else { snippetCellDefinition.InsertSnippet("ITEM", ctrlSnippet); snippetRowDefinition.InsertSnippet("ITEMS", snippetCellDefinition, ","); } } ATemplate.InsertSnippet(AItemsPlaceholder, snippetRowDefinition, ","); } } else { foreach (XmlNode childNode in childNodes) { string child = TYml2Xml.GetElementName(childNode); TControlDef childCtrl = AWriter.FCodeStorage.FindOrCreateControl(child, ACtrl.controlName); if ((ANodeName != "HiddenValues") && (childCtrl.controlTypePrefix == "hid")) { // somehow, hidden values get into the controls list as well. we don't want them there continue; } IControlGenerator ctrlGen = AWriter.FindControlGenerator(childCtrl); if (ctrlGen is FieldSetGenerator) { InsertControl(AWriter.FCodeStorage.FindOrCreateControl(child, ACtrl.controlName), ATemplate, AItemsPlaceholder, ANodeName, AWriter); } else { ProcessTemplate ctrlSnippet = ctrlGen.SetControlProperties(AWriter, childCtrl); ProcessTemplate snippetCellDefinition = AWriter.FTemplate.GetSnippet("CELLDEFINITION"); LayoutCellInForm(childCtrl, -1, ctrlSnippet, snippetCellDefinition); ATemplate.InsertSnippet(AItemsPlaceholder, ctrlSnippet, ","); } } } }
public ActionResult DeleteKendo([DataSourceRequest] DataSourceRequest request, ProcessTemplate item) { if (item != null) { _ProcessTemplateService.DeleteById(item.ProcessTemplateID); } return(Json(ModelState.ToDataSourceResult())); }
/// <summary> /// insert a method call /// </summary> private static void InsertMethodCall(ProcessTemplate snippet, TypeDeclaration connectorClass, MethodDeclaration m, ref List <string> AMethodNames) { string ParameterDefinition = string.Empty; string ActualParameters = string.Empty; AutoGenerationTools.FormatParameters(m.Parameters, out ActualParameters, out ParameterDefinition); // for standalone: add actual parameters directly snippet.AddToCodelet("ACTUALPARAMETERS", ActualParameters); string returntype = AutoGenerationTools.TypeToString(m.TypeReference, ""); if (!returntype.Contains("<")) { returntype = returntype == "string" || returntype == "String" ? "System.String" : returntype; returntype = returntype == "bool" || returntype == "Boolean" ? "System.Boolean" : returntype; if (returntype.Contains("UINT") || returntype.Contains("unsigned")) { returntype = returntype.Contains("UInt32") || returntype == "unsigned int" ? "System.UInt32" : returntype; returntype = returntype.Contains("UInt16") || returntype == "unsigned short" ? "System.UInt16" : returntype; returntype = returntype.Contains("UInt64") || returntype == "unsigned long" ? "System.UInt64" : returntype; } else { returntype = returntype.Contains("Int32") || returntype == "int" ? "System.Int32" : returntype; returntype = returntype.Contains("Int16") || returntype == "short" ? "System.Int16" : returntype; returntype = returntype.Contains("Int64") || returntype == "long" ? "System.Int64" : returntype; } returntype = returntype.Contains("Decimal") || returntype == "decimal" ? "System.Decimal" : returntype; } snippet.SetCodelet("RETURN", returntype != "void" ? "return " : string.Empty); // avoid duplicate names for webservice methods string methodname = m.Name; int methodcounter = 1; while (AMethodNames.Contains(methodname)) { methodcounter++; methodname = m.Name + methodcounter.ToString(); } AMethodNames.Add(methodname); snippet.SetCodelet("UNIQUEMETHODNAME", methodname); snippet.SetCodelet("METHODNAME", m.Name); snippet.SetCodelet("PARAMETERDEFINITION", ParameterDefinition); snippet.SetCodelet("RETURNTYPE", returntype); snippet.SetCodelet("WEBCONNECTORCLASS", connectorClass.Name); snippet.SetCodelet("ASSIGNRESULTANDRETURN", string.Empty); snippet.SetCodelet("ADDACTUALPARAMETERS", string.Empty); int ResultCounter = 0; if (CheckServerAdminToken(m)) { snippet.AddToCodelet("ADDACTUALPARAMETERS", "ActualParameters.Add(\"AServerAdminSecurityToken\", THttpConnector.ServerAdminSecurityToken" + ");" + Environment.NewLine); } foreach (ParameterDeclarationExpression p in m.Parameters) { if (((ParameterModifiers.Ref & p.ParamModifier) > 0) || ((ParameterModifiers.Out & p.ParamModifier) > 0)) { // need to assign the result to the ref and the out parameter snippet.AddToCodelet("ASSIGNRESULTANDRETURN", p.ParameterName + " = (" + p.TypeReference.ToString() + ") Result[" + ResultCounter.ToString() + "];" + Environment.NewLine); ResultCounter++; } if ((ParameterModifiers.Out & p.ParamModifier) == 0) { snippet.AddToCodelet("ADDACTUALPARAMETERS", "ActualParameters.Add(\"" + p.ParameterName + "\", " + p.ParameterName + ");" + Environment.NewLine); } } string expectedreturntype = GetExpectedReturnType(ResultCounter, returntype); snippet.SetCodelet("EXPECTEDRETURNTYPE", expectedreturntype); snippet.SetCodelet("RESULT", string.Empty); if ((returntype != "void") || (ResultCounter > 0)) { snippet.SetCodelet("RESULT", "List<object> Result = "); } if (returntype != "void") { snippet.AddToCodelet("ASSIGNRESULTANDRETURN", "return (" + returntype + ") Result[" + ResultCounter.ToString() + "];" + Environment.NewLine); } }
/// <summary> /// code for cascading functions /// </summary> /// <param name="AStore"></param> /// <param name="ACurrentTable"></param> /// <param name="ATemplate"></param> /// <param name="ASnippet"></param> /// <returns>false if no cascading available</returns> private static bool InsertMainProcedures(TDataDefinitionStore AStore, TTable ACurrentTable, ProcessTemplate ATemplate, ProcessTemplate ASnippet) { string csvListPrimaryKeyFields; string formalParametersPrimaryKey; string actualParametersPrimaryKey; Tuple <string, string, string>[] formalParametersPrimaryKeySeparate; string actualParametersPrimaryKeyFromPKArray = String.Empty; ASnippet.AddToCodelet("TABLENAME", TTable.NiceTableName(ACurrentTable.strName)); ASnippet.AddToCodelet("THISTABLELABEL", ACurrentTable.strLabel); PrepareCodeletsPrimaryKey(ACurrentTable, out csvListPrimaryKeyFields, out formalParametersPrimaryKey, out actualParametersPrimaryKey, out formalParametersPrimaryKeySeparate); for (int Counter = 0; Counter < formalParametersPrimaryKeySeparate.Length; Counter++) { actualParametersPrimaryKeyFromPKArray += "(" + formalParametersPrimaryKeySeparate[Counter].Item1 + ")" + "APrimaryKeyValues[" + Counter.ToString() + "], "; } // Strip off trailing ", " actualParametersPrimaryKeyFromPKArray = actualParametersPrimaryKeyFromPKArray.Substring(0, actualParametersPrimaryKeyFromPKArray.Length - 2); ASnippet.AddToCodelet("CSVLISTPRIMARYKEYFIELDS", csvListPrimaryKeyFields); ASnippet.AddToCodelet("FORMALPARAMETERSPRIMARYKEY", formalParametersPrimaryKey); ASnippet.AddToCodelet("ACTUALPARAMETERSPRIMARYKEY", actualParametersPrimaryKey); ASnippet.AddToCodelet("ACTUALPARAMETERSPRIMARYKEYFROMPKARRAY", actualParametersPrimaryKeyFromPKArray); for (int Counter = 0; Counter < ACurrentTable.GetPrimaryKey().strThisFields.Count; Counter++) { ProcessTemplate PKInfoDictBuilding = ASnippet.GetSnippet("PRIMARYKEYINFODICTBUILDING"); PKInfoDictBuilding.SetCodelet("PKCOLUMNLABEL", formalParametersPrimaryKeySeparate[Counter].Item3); PKInfoDictBuilding.SetCodelet("PKCOLUMNCONTENT", formalParametersPrimaryKeySeparate[Counter].Item2); ASnippet.InsertSnippet("PRIMARYKEYINFODICTBUILDING", PKInfoDictBuilding); } ASnippet.AddToCodelet("PRIMARYKEYCOLUMNCOUNT", ACurrentTable.GetPrimaryKey().strThisFields.Count.ToString()); foreach (TConstraint constraint in ACurrentTable.FReferenced) { if (AStore.GetTable(constraint.strThisTable).HasPrimaryKey()) { string csvListOtherPrimaryKeyFields; string notUsed; Tuple <string, string, string>[] formalParametersPrimaryKeySeparate2; TTable OtherTable = AStore.GetTable(constraint.strThisTable); PrepareCodeletsPrimaryKey(OtherTable, out csvListOtherPrimaryKeyFields, out notUsed, out notUsed, out formalParametersPrimaryKeySeparate2); // check if other foreign key exists that references the same table, e.g. // PBankAccess.LoadViaPPartnerPartnerKey // PBankAccess.LoadViaPPartnerContactPartnerKey string DifferentField = CodeGenerationAccess.FindOtherConstraintSameOtherTable( OtherTable.grpConstraint, constraint); string LoadViaProcedureName = TTable.NiceTableName(ACurrentTable.strName); string MyOtherTableName = "My" + TTable.NiceTableName(constraint.strThisTable); if (DifferentField.Length != 0) { LoadViaProcedureName += TTable.NiceFieldName(DifferentField); MyOtherTableName += TTable.NiceFieldName(DifferentField); } // for the moment, don't implement it for too big tables, e.g. s_user) if ((ACurrentTable.HasPrimaryKey() || (ACurrentTable.FReferenced.Count <= CASCADING_DELETE_MAX_REFERENCES)) && ((constraint.strThisTable != "a_ledger") && (!LoadViaProcedureName.StartsWith("SUser")))) { ProcessTemplate snippetDelete = ASnippet.GetSnippet("DELETEBYPRIMARYKEYCASCADING"); snippetDelete.SetCodelet("OTHERTABLENAME", TTable.NiceTableName(constraint.strThisTable)); snippetDelete.SetCodelet("MYOTHERTABLENAME", MyOtherTableName); snippetDelete.SetCodelet("VIAPROCEDURENAME", "Via" + LoadViaProcedureName); snippetDelete.SetCodelet("CSVLISTOTHERPRIMARYKEYFIELDS", csvListOtherPrimaryKeyFields); snippetDelete.SetCodelet("OTHERTABLEALSOCASCADING", "true"); ASnippet.InsertSnippet("DELETEBYPRIMARYKEYCASCADING", snippetDelete); snippetDelete = ASnippet.GetSnippet("DELETEBYTEMPLATECASCADING"); snippetDelete.SetCodelet("OTHERTABLENAME", TTable.NiceTableName(constraint.strThisTable)); snippetDelete.SetCodelet("MYOTHERTABLENAME", MyOtherTableName); snippetDelete.SetCodelet("VIAPROCEDURENAME", "Via" + LoadViaProcedureName); snippetDelete.SetCodelet("CSVLISTOTHERPRIMARYKEYFIELDS", csvListOtherPrimaryKeyFields); snippetDelete.SetCodelet("OTHERTABLEALSOCASCADING", "true"); ASnippet.InsertSnippet("DELETEBYTEMPLATECASCADING", snippetDelete); } if ((constraint.strThisTable != "a_ledger") && (!LoadViaProcedureName.StartsWith("SUser"))) { ProcessTemplate snippetCount = ASnippet.GetSnippet("COUNTBYPRIMARYKEYCASCADING"); snippetCount.SetCodelet("OTHERTABLENAME", TTable.NiceTableName(constraint.strThisTable)); snippetCount.SetCodelet("MYOTHERTABLENAME", MyOtherTableName); snippetCount.SetCodelet("VIAPROCEDURENAME", "Via" + LoadViaProcedureName); snippetCount.SetCodelet("CSVLISTOTHERPRIMARYKEYFIELDS", csvListOtherPrimaryKeyFields); snippetCount.SetCodelet("OTHERTABLEALSOCASCADING", "true"); for (int Counter = 0; Counter < OtherTable.GetPrimaryKey().strThisFields.Count; Counter++) { ProcessTemplate PKInfoDictBuilding2 = ASnippet.GetSnippet("PRIMARYKEYINFODICTBUILDING"); PKInfoDictBuilding2.SetCodelet("PKCOLUMNLABEL", formalParametersPrimaryKeySeparate2[Counter].Item3); PKInfoDictBuilding2.SetCodelet("PKCOLUMNCONTENT", "\"\""); snippetCount.InsertSnippet("PRIMARYKEYINFODICTBUILDING2", PKInfoDictBuilding2); } snippetCount.SetCodelet("PRIMARYKEYCOLUMNCOUNT2", OtherTable.GetPrimaryKey().strThisFields.Count.ToString()); ASnippet.InsertSnippet("COUNTBYPRIMARYKEYCASCADING", snippetCount); snippetCount = ASnippet.GetSnippet("COUNTBYTEMPLATECASCADING"); snippetCount.SetCodelet("OTHERTABLENAME", TTable.NiceTableName(constraint.strThisTable)); snippetCount.SetCodelet("OTHERTABLELABEL", OtherTable.strLabel); snippetCount.SetCodelet("MYOTHERTABLENAME", MyOtherTableName); snippetCount.SetCodelet("VIAPROCEDURENAME", "Via" + LoadViaProcedureName); snippetCount.SetCodelet("CSVLISTOTHERPRIMARYKEYFIELDS", csvListOtherPrimaryKeyFields); snippetCount.SetCodelet("OTHERTABLEALSOCASCADING", "true"); for (int Counter = 0; Counter < OtherTable.GetPrimaryKey().strThisFields.Count; Counter++) { ProcessTemplate PKInfoDictBuilding2 = ASnippet.GetSnippet("PRIMARYKEYINFODICTBUILDING"); PKInfoDictBuilding2.SetCodelet("PKCOLUMNLABEL", formalParametersPrimaryKeySeparate2[Counter].Item3); PKInfoDictBuilding2.SetCodelet("PKCOLUMNCONTENT", "\"\""); snippetCount.InsertSnippet("PRIMARYKEYINFODICTBUILDING2", PKInfoDictBuilding2); } snippetCount.SetCodelet("PRIMARYKEYCOLUMNCOUNT2", OtherTable.GetPrimaryKey().strThisFields.Count.ToString()); ASnippet.InsertSnippet("COUNTBYTEMPLATECASCADING", snippetCount); } } } return(true); }
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); } } }
/// <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); }
/// <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); }
/// <summary> /// create the code for the definition of a typed table /// </summary> /// <param name="Template"></param> /// <param name="currentTable"></param> /// <param name="origTable"></param> /// <param name="WhereToInsert"></param> /// <param name="CalledFromDataSet"></param> public static void InsertTableDefinition(ProcessTemplate Template, TTable currentTable, TTable origTable, string WhereToInsert, Boolean CalledFromDataSet) { ProcessTemplate snippet = Template.GetSnippet("TYPEDTABLE"); string derivedTable = ""; if (origTable != null) { snippet.SetCodelet("BASECLASSTABLE", TTable.NiceTableName(currentTable.strName) + "Table"); derivedTable = "new "; snippet.SetCodelet("TABLEID", origTable.iOrder.ToString()); } else { snippet.SetCodelet("BASECLASSTABLE", "TTypedDataTable"); snippet.SetCodelet("TABLEID", currentTable.iOrder.ToString()); } snippet.SetCodelet("NEW", derivedTable); snippet.SetCodeletComment("TABLE_DESCRIPTION", currentTable.strDescription); snippet.SetCodelet("TABLENAME", currentTable.strDotNetName); if (CalledFromDataSet) { snippet.SetCodelet("TABLEINTDS", "TableInTDS"); } else { snippet.SetCodelet("TABLEINTDS", ""); } if (currentTable.AvailableForCustomReport) { snippet.SetCodelet("AVAILABLEFORCUSTOMREPORT", "true"); } else { snippet.SetCodelet("AVAILABLEFORCUSTOMREPORT", "false"); } snippet.SetCodelet("CUSTOMREPORTPERMISSION", currentTable.CustomReportPermission); if (currentTable.strVariableNameInDataset != null) { snippet.SetCodelet("TABLEVARIABLENAME", currentTable.strVariableNameInDataset); } else { snippet.SetCodelet("TABLEVARIABLENAME", currentTable.strDotNetName); } snippet.SetCodelet("DBTABLENAME", currentTable.strName); snippet.SetCodelet("DBTABLELABEL", currentTable.strLabel); if (currentTable.HasPrimaryKey()) { TConstraint primKey = currentTable.GetPrimaryKey(); bool first = true; string primaryKeyColumns = ""; int prevIndex = -1; // the fields in the primary key should be used in the same order as in the table. // otherwise this is causing confusion. eg. a_processed_fee foreach (TTableField column in currentTable.grpTableField) { int newIndex = -1; if (primKey.strThisFields.Contains(column.strName)) { newIndex = primKey.strThisFields.IndexOf(column.strName); } else if (primKey.strThisFields.Contains(TTable.NiceFieldName(column))) { newIndex = primKey.strThisFields.IndexOf(TTable.NiceFieldName(column)); } if (newIndex != -1) { if (newIndex < prevIndex) { throw new Exception("Please fix the order of the fields in the primary key of table " + currentTable.strName); } prevIndex = newIndex; } } // the fields in the primary key should be used in the same order as in the table. // otherwise this is causing confusion. eg. a_processed_fee foreach (TTableField column in currentTable.grpTableField) { if (primKey.strThisFields.Contains(column.strName) || primKey.strThisFields.Contains(TTable.NiceFieldName(column))) { string columnName = column.strName; string toAdd = currentTable.grpTableField.IndexOf(currentTable.GetField(columnName)).ToString(); if (!first) { toAdd = ", " + toAdd; primaryKeyColumns += ","; } first = false; snippet.AddToCodelet("COLUMNPRIMARYKEYORDER", toAdd); primaryKeyColumns += "Column" + TTable.NiceFieldName(currentTable.GetField(columnName)); } } if (primaryKeyColumns.Length > 0) { snippet.SetCodelet("PRIMARYKEYCOLUMNS", primaryKeyColumns); snippet.SetCodelet("PRIMARYKEYCOLUMNSCOUNT", primKey.strThisFields.Count.ToString()); } } else { snippet.AddToCodelet("COLUMNPRIMARYKEYORDER", ""); } if (currentTable.HasUniqueKey()) { TConstraint primKey = currentTable.GetFirstUniqueKey(); bool first = true; foreach (string columnName in primKey.strThisFields) { string toAdd = currentTable.grpTableField.IndexOf(currentTable.GetField(columnName)).ToString(); if (!first) { toAdd = ", " + toAdd; } first = false; snippet.AddToCodelet("COLUMNUNIQUEKEYORDER", toAdd); } } else { snippet.AddToCodelet("COLUMNUNIQUEKEYORDER", ""); } int colOrder = 0; Boolean CustomReportFieldAdded = false; ProcessTemplate tempTemplate = null; foreach (TTableField col in currentTable.grpTableField) { col.strTableName = currentTable.strName; string columnOverwrite = ""; bool writeColumnProperties = true; if ((origTable != null) && (origTable.GetField(col.strName, false) != null)) { columnOverwrite = "new "; if (origTable.GetField(col.strName).iOrder == colOrder) { // same order number, save some lines of code by not writing them writeColumnProperties = false; } } if (writeColumnProperties && (columnOverwrite.Length == 0)) { tempTemplate = Template.GetSnippet("DATACOLUMN"); tempTemplate.SetCodeletComment("COLUMN_DESCRIPTION", col.strDescription); tempTemplate.SetCodelet("COLUMNNAME", TTable.NiceFieldName(col)); snippet.InsertSnippet("DATACOLUMNS", tempTemplate); } if (writeColumnProperties) { tempTemplate = Template.GetSnippet("COLUMNIDS"); tempTemplate.SetCodelet("COLUMNNAME", TTable.NiceFieldName(col)); tempTemplate.SetCodelet("COLUMNORDERNUMBER", colOrder.ToString()); tempTemplate.SetCodelet("NEW", columnOverwrite); snippet.InsertSnippet("COLUMNIDS", tempTemplate); } if (origTable == null) { tempTemplate = Template.GetSnippet("COLUMNINFO"); tempTemplate.SetCodelet("COLUMNORDERNUMBER", colOrder.ToString()); tempTemplate.SetCodelet("COLUMNNAME", TTable.NiceFieldName(col)); tempTemplate.SetCodelet("COLUMNDBNAME", col.strName); tempTemplate.SetCodelet("COLUMNLABEL", col.strLabel); tempTemplate.SetCodelet("COLUMNODBCTYPE", CodeGenerationPetra.ToOdbcTypeString(col)); tempTemplate.SetCodelet("COLUMNLENGTH", col.iLength.ToString()); tempTemplate.SetCodelet("COLUMNNOTNULL", col.bNotNull.ToString().ToLower()); tempTemplate.SetCodelet("COLUMNCOMMA", colOrder + 1 < currentTable.grpTableField.Count ? "," : ""); snippet.InsertSnippet("COLUMNINFO", tempTemplate); } tempTemplate = Template.GetSnippet("INITCLASSADDCOLUMN"); tempTemplate.SetCodelet("COLUMNDBNAME", col.strName); tempTemplate.SetCodelet("COLUMNDOTNETTYPE", col.GetDotNetType()); tempTemplate.SetCodelet("COLUMNDOTNETTYPENOTNULLABLE", col.GetDotNetType().Replace("?", "")); snippet.InsertSnippet("INITCLASSADDCOLUMN", tempTemplate); tempTemplate = Template.GetSnippet("INITVARSCOLUMN"); tempTemplate.SetCodelet("COLUMNDBNAME", col.strName); tempTemplate.SetCodelet("COLUMNNAME", TTable.NiceFieldName(col)); snippet.InsertSnippet("INITVARSCOLUMN", tempTemplate); if (col.bAvailableForCustomReport) { tempTemplate = Template.GetSnippet("INITVARSCUSTOMREPORTFIELDLIST"); if (CustomReportFieldAdded) { tempTemplate.SetCodelet("LISTDELIMITER", ","); } else { tempTemplate.SetCodelet("LISTDELIMITER", ""); } tempTemplate.SetCodelet("COLUMNDBNAME", col.strName); snippet.InsertSnippet("INITVARSCUSTOMREPORTFIELDLIST", tempTemplate); CustomReportFieldAdded = true; } if (writeColumnProperties) { tempTemplate = Template.GetSnippet("STATICCOLUMNPROPERTIES"); tempTemplate.SetCodelet("COLUMNDBNAME", col.strName); tempTemplate.SetCodelet("COLUMNNAME", TTable.NiceFieldName(col)); tempTemplate.SetCodelet("COLUMNHELP", col.strHelp.Replace("\"", "\\\"")); tempTemplate.SetCodelet("COLUMNLENGTH", col.iLength.ToString()); tempTemplate.SetCodelet("NEW", columnOverwrite); snippet.InsertSnippet("STATICCOLUMNPROPERTIES", tempTemplate); } colOrder++; } if (!CustomReportFieldAdded) { // fill snippet if nothing was added yet tempTemplate = Template.GetSnippet("INITVARSCUSTOMREPORTFIELDLISTEMPTY"); tempTemplate.SetCodelet("EMPTY", ""); snippet.InsertSnippet("INITVARSCUSTOMREPORTFIELDLIST", tempTemplate); } Template.InsertSnippet(WhereToInsert, snippet); }
static private void WriteWebConnector(string connectorname, TypeDeclaration connectorClass, ProcessTemplate Template) { List <string> MethodNames = new List <string>(); foreach (MethodDeclaration m in CSParser.GetMethods(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("WEBCONNECTOR"); InsertWebConnectorMethodCall(snippet, connectorClass, m, ref MethodNames); Template.InsertSnippet("WEBCONNECTORS", snippet); } }
/// <summary> /// main function for generating access methods for typed data sets /// </summary> /// <param name="AInputXmlfile"></param> /// <param name="AOutputPath"></param> /// <param name="ANameSpace"></param> /// <param name="store"></param> /// <param name="groups"></param> /// <param name="AFilename"></param> public static void CreateTypedDataSets(String AInputXmlfile, String AOutputPath, String ANameSpace, TDataDefinitionStore store, string[] groups, string AFilename) { Console.WriteLine("processing dataset " + ANameSpace); string templateDir = TAppSettingsManager.GetValue("TemplateDir", true); ProcessTemplate Template = new ProcessTemplate(templateDir + Path.DirectorySeparatorChar + "ORM" + Path.DirectorySeparatorChar + "DataSetAccess.cs"); // load default header with license and copyright Template.SetCodelet("GPLFILEHEADER", ProcessTemplate.LoadEmptyFileComment(templateDir)); Template.SetCodelet("NAMESPACE", ANameSpace); // if no dataset is defined yet in the xml file, the following variables can be empty Template.AddToCodelet("USINGNAMESPACES", ""); Template.AddToCodelet("CONTENTDATASETSANDTABLESANDROWS", ""); Template.AddToCodelet("USINGNAMESPACES", "using " + ANameSpace.Replace(".Server.", ".Shared.") + ";" + Environment.NewLine, false); TXMLParser parserDataSet = new TXMLParser(AInputXmlfile, false); XmlDocument myDoc = parserDataSet.GetDocument(); XmlNode startNode = myDoc.DocumentElement; if (startNode.Name.ToLower() == "petradatasets") { XmlNode cur = TXMLParser.NextNotBlank(startNode.FirstChild); while ((cur != null) && (cur.Name.ToLower() == "importunit")) { Template.AddToCodelet("USINGNAMESPACES", "using " + TXMLParser.GetAttribute(cur, "name") + ";" + Environment.NewLine, false); Template.AddToCodelet("USINGNAMESPACES", "using " + TXMLParser.GetAttribute(cur, "name").Replace(".Shared.", ".Server.") + ".Access;" + Environment.NewLine, false); cur = TXMLParser.GetNextEntity(cur); } while ((cur != null) && (cur.Name.ToLower() == "dataset")) { ProcessTemplate snippetDataset = Template.GetSnippet("TYPEDDATASET"); string datasetname = TXMLParser.GetAttribute(cur, "name"); snippetDataset.SetCodelet("DATASETNAME", datasetname); ProcessTemplate snippetSubmitChanges = snippetDataset.GetSnippet("SUBMITCHANGESFUNCTION"); snippetSubmitChanges.AddToCodelet("DATASETNAME", datasetname); List <TDataSetTable> tables = new List <TDataSetTable>(); XmlNode curChild = cur.FirstChild; // first collect the tables while (curChild != null) { if (curChild.Name.ToLower() == "table") { string tabletype = TTable.NiceTableName(TXMLParser.GetAttribute(curChild, "sqltable")); string variablename = (TXMLParser.HasAttribute(curChild, "name") ? TXMLParser.GetAttribute(curChild, "name") : tabletype); TDataSetTable table = new TDataSetTable( TXMLParser.GetAttribute(curChild, "sqltable"), tabletype, variablename, store.GetTable(tabletype)); tables.Add(table); } curChild = curChild.NextSibling; } foreach (TDataSetTable table in tables) { AddTableToDataset(tables, store.GetTable(table.tableorig), table.tablename, table.tablealias, snippetDataset, snippetSubmitChanges); } // there is one codelet for the dataset name. // only add the full submitchanges function if there are any table to submit if (snippetSubmitChanges.FCodelets.Count > 1) { snippetDataset.InsertSnippet("SUBMITCHANGESFUNCTION", snippetSubmitChanges); } else { snippetDataset.AddToCodelet("SUBMITCHANGESFUNCTION", ""); } Template.InsertSnippet("CONTENTDATASETSANDTABLESANDROWS", snippetDataset); cur = TXMLParser.GetNextEntity(cur); } } Template.FinishWriting(AOutputPath + Path.DirectorySeparatorChar + AFilename + "-generated.cs", ".cs", true); }
static private void CreateServerGlue(TNamespace tn, SortedList <string, TypeDeclaration> connectors, string AOutputPath) { String OutputFile = AOutputPath + Path.DirectorySeparatorChar + "ServerGlue.M" + tn.Name + "-generated.cs"; Console.WriteLine("working on " + OutputFile); ProcessTemplate Template = new ProcessTemplate(FTemplateDir + Path.DirectorySeparatorChar + "ClientServerGlue" + Path.DirectorySeparatorChar + "ServerGlue.cs"); // load default header with license and copyright Template.SetCodelet("GPLFILEHEADER", ProcessTemplate.LoadEmptyFileComment(FTemplateDir)); Template.SetCodelet("TOPLEVELMODULE", tn.Name); Template.SetCodelet("WEBCONNECTORS", string.Empty); Template.SetCodelet("UICONNECTORS", string.Empty); string InterfacePath = Path.GetFullPath(AOutputPath).Replace(Path.DirectorySeparatorChar, '/'); InterfacePath = InterfacePath.Substring(0, InterfacePath.IndexOf("csharp/ICT/Petra")) + "csharp/ICT/Petra/Shared/lib/Interfaces"; Template.AddToCodelet("USINGNAMESPACES", CreateInterfaces.AddNamespacesFromYmlFile(InterfacePath, tn.Name)); if (AOutputPath.Contains("ICT/Petra/Plugins/")) { Template.AddToCodelet("USINGNAMESPACES", "using Ict.Petra.Server.App.WebService;" + Environment.NewLine); // add namespaces that are required by the plugin InterfacePath = Path.GetFullPath(AOutputPath + "/../").Replace(Path.DirectorySeparatorChar, '/'); Template.AddToCodelet("USINGNAMESPACES", CreateInterfaces.AddNamespacesFromYmlFile(InterfacePath, "Plugin")); } FUsingNamespaces = new SortedList <string, string>(); FContainsAsynchronousExecutionProgress = false; foreach (string connector in connectors.Keys) { if (connector.EndsWith("UIConnector")) { WriteUIConnector(connector, connectors[connector], Template); } else { WriteWebConnector(connector, connectors[connector], Template); } } if (FContainsAsynchronousExecutionProgress) { Template.InsertSnippet("UICONNECTORS", Template.GetSnippet("ASYNCEXECPROCESSCONNECTOR")); if (!FUsingNamespaces.ContainsKey("Ict.Petra.Server.MCommon")) { FUsingNamespaces.Add("Ict.Petra.Server.MCommon", "Ict.Petra.Server.MCommon"); } } foreach (string usingNamespace in FUsingNamespaces.Keys) { Template.AddToCodelet("USINGNAMESPACES", "using " + usingNamespace + ";" + Environment.NewLine); } if (OutputFile.Replace("\\", "/").Contains("ICT/Petra/Plugins")) { string pluginWithNamespace = TAppSettingsManager.GetValue("plugin"); Template.SetCodelet("WEBSERVICENAMESPACE", pluginWithNamespace + ".WebService"); } else { Template.SetCodelet("WEBSERVICENAMESPACE", "Ict.Petra.Server.App.WebService"); } Template.FinishWriting(OutputFile, ".cs", true); }
/// <summary> /// create code for a table that is part of a dataset /// </summary> /// <param name="ATables"></param> /// <param name="ASqltable"></param> /// <param name="tabletype"></param> /// <param name="variablename"></param> /// <param name="snippetDataset"></param> /// <param name="ASnippetSubmitChanges"></param> private static void AddTableToDataset( List <TDataSetTable> ATables, TTable ASqltable, string tabletype, string variablename, ProcessTemplate snippetDataset, ProcessTemplate ASnippetSubmitChanges) { ProcessTemplate tempSnippet; if (ASqltable != null) { string SequenceColumn = ""; string SequenceName = ""; foreach (TTableField tablefield in ASqltable.grpTableField) { // is there a field filled by a sequence? // yes: get the next value of that sequence and assign to row if (tablefield.strSequence.Length > 0) { SequenceName = tablefield.strSequence; SequenceColumn = tablefield.strName; // assume only one sequence per table break; } } tempSnippet = snippetDataset.GetSnippet("SUBMITCHANGES"); tempSnippet.SetCodelet("ORIGTABLENAME", TTable.NiceTableName(ASqltable.strName)); tempSnippet.SetCodelet("TABLETYPENAME", tabletype); tempSnippet.SetCodelet("TABLEVARIABLENAME", variablename); tempSnippet.SetCodelet("SQLOPERATION", "eDelete"); tempSnippet.SetCodelet("SEQUENCENAMEANDFIELD", ""); ASnippetSubmitChanges.InsertSnippetPrepend("SUBMITCHANGESDELETE", tempSnippet); tempSnippet = snippetDataset.GetSnippet("SUBMITCHANGES"); tempSnippet.SetCodelet("ORIGTABLENAME", TTable.NiceTableName(ASqltable.strName)); tempSnippet.SetCodelet("TABLETYPENAME", tabletype); tempSnippet.SetCodelet("TABLEVARIABLENAME", variablename); tempSnippet.SetCodelet("SQLOPERATION", "eInsert | TTypedDataAccess.eSubmitChangesOperations.eUpdate"); tempSnippet.SetCodelet("SEQUENCENAMEANDFIELD", ""); if (SequenceName.Length > 0) { tempSnippet.SetCodelet("SEQUENCENAMEANDFIELD", ", \"" + SequenceName + "\", \"" + SequenceColumn + "\""); // look for other tables in the dataset that have a foreign key on the sequenced column // eg. p_location_key_i is set when storing p_location. // now we should update p_partner_location, which still has negative values in p_location_key_i foreach (TDataSetTable table in ATables) { foreach (TConstraint constraint in table.grpConstraint) { if ((constraint.strType == "foreignkey") && (constraint.strOtherTable == ASqltable.strName) && constraint.strOtherFields.Contains(SequenceColumn)) { tempSnippet.SetCodelet("TABLEROWTYPE", TTable.NiceTableName(ASqltable.strName) + "Row"); tempSnippet.SetCodelet("SEQUENCEDCOLUMNNAME", TTable.NiceFieldName(SequenceColumn)); ProcessTemplate updateSnippet = snippetDataset.GetSnippet("UPDATESEQUENCEINOTHERTABLES"); bool canbeNull = !table.GetField(constraint.strThisFields[constraint.strOtherFields.IndexOf(SequenceColumn)]).bNotNull; updateSnippet.SetCodelet("TESTFORNULL", canbeNull ? "!otherRow.Is{#REFCOLUMNNAME}Null() && " : ""); updateSnippet.SetCodelet("REFERENCINGTABLEROWTYPE", TTable.NiceTableName(table.tablename) + "Row"); updateSnippet.SetCodelet("REFERENCINGTABLENAME", table.tablealias); updateSnippet.SetCodelet("REFCOLUMNNAME", TTable.NiceFieldName(constraint.strThisFields[constraint.strOtherFields.IndexOf(SequenceColumn)])); updateSnippet.SetCodelet("SEQUENCEDCOLUMNNAME", TTable.NiceFieldName(SequenceColumn)); tempSnippet.InsertSnippet("UPDATESEQUENCEINOTHERTABLES", updateSnippet); } } } } ASnippetSubmitChanges.InsertSnippet("SUBMITCHANGESINSERT", tempSnippet); ASnippetSubmitChanges.AddToCodelet("SUBMITCHANGESUPDATE", ""); } }
/// <summary> /// situation 2: bridging tables /// for example p_location and p_partner are connected through p_partner_location /// it would be helpful, to be able to do: /// location.LoadViaPartner(partnerkey) to get all locations of the partner /// partner.loadvialocation(locationkey) to get all partners living at that location /// general solution: pick up all foreign keys from other tables (B) to the primary key of the current table (A), /// where the other table has a foreign key to another table (C), using other fields in the primary key of (B) than the link to (A). /// get all tables that reference the current table /// </summary> /// <param name="AStore"></param> /// <param name="ACurrentTable"></param> /// <param name="ATemplate"></param> /// <param name="ASnippet"></param> private static void InsertViaLinkTable(TDataDefinitionStore AStore, TTable ACurrentTable, ProcessTemplate ATemplate, ProcessTemplate ASnippet) { // step 1: collect all the valid constraints of such link tables ArrayList OtherLinkConstraints = new ArrayList(); ArrayList References = new ArrayList(); foreach (TConstraint Reference in ACurrentTable.GetReferences()) { TTable LinkTable = AStore.GetTable(Reference.strThisTable); try { TConstraint LinkPrimaryKey = LinkTable.GetPrimaryKey(); if (StringHelper.Contains(LinkPrimaryKey.strThisFields, Reference.strThisFields)) { // check how many constraints from the link table are from fields in the primary key // a link table only should have 2 // so find the other one TConstraint OtherLinkConstraint = null; bool IsLinkTable = false; foreach (TConstraint LinkConstraint in LinkTable.grpConstraint) { // check if there is another constraint for the primary key of the link table. if (ValidForeignKeyConstraintForLoadVia(LinkConstraint) && (LinkConstraint != Reference) && (StringHelper.Contains(LinkPrimaryKey.strThisFields, LinkConstraint.strThisFields))) { if (OtherLinkConstraint == null) { OtherLinkConstraint = LinkConstraint; IsLinkTable = true; } else { IsLinkTable = false; } } else if (ValidForeignKeyConstraintForLoadVia(LinkConstraint) && (LinkConstraint != Reference) && (!StringHelper.Contains(LinkPrimaryKey.strThisFields, LinkConstraint.strThisFields)) && StringHelper.ContainsSome(LinkPrimaryKey.strThisFields, LinkConstraint.strThisFields)) { // if there is a key that partly is in the primary key, then this is not a link table. OtherLinkConstraint = LinkConstraint; IsLinkTable = false; } } if ((IsLinkTable) && (OtherLinkConstraint.strOtherTable != Reference.strOtherTable)) { // collect the links. then we are able to name them correctly, once we need them OtherLinkConstraints.Add(OtherLinkConstraint); References.Add(Reference); } } } catch (Exception) { // Console.WriteLine(e.Message); } } // step2: implement the link tables, using correct names for the procedures int Count = 0; foreach (TConstraint OtherLinkConstraint in OtherLinkConstraints) { TTable OtherTable = AStore.GetTable(OtherLinkConstraint.strOtherTable); string ProcedureName = "Via" + TTable.NiceTableName(OtherTable.strName); // check if other foreign key exists that references the same table, e.g. // PPartnerAccess.LoadViaSUserPRecentPartners // PPartnerAccess.LoadViaSUserPCustomisedGreeting // also PFoundationProposalAccess.LoadViaPFoundationPFoundationProposalDetail and // TODO AlreadyExistsProcedureSameName necessary for PPersonAccess.LoadViaPUnit (p_field_key_n) and PPersonAccess.LoadViaPUnitPmGeneralApplication // Question: does PPersonAccess.LoadViaPUnitPmGeneralApplication make sense? if (FindOtherConstraintSameOtherTable2(OtherLinkConstraints, OtherLinkConstraint) || LoadViaHasAlreadyBeenImplemented(OtherLinkConstraint) // TODO || AlreadyExistsProcedureSameName(ProcedureName) || ((ProcedureName == "ViaPUnit") && (OtherLinkConstraint.strThisTable == "pm_general_application")) ) { ProcedureName += TTable.NiceTableName(OtherLinkConstraint.strThisTable); } ATemplate.AddToCodelet("USINGNAMESPACES", GetNamespace(OtherTable.strGroup), false); ProcessTemplate snippetLinkTable = ATemplate.GetSnippet("VIALINKTABLE"); snippetLinkTable.SetCodelet("VIAPROCEDURENAME", ProcedureName); snippetLinkTable.SetCodelet("OTHERTABLENAME", TTable.NiceTableName(OtherTable.strName)); snippetLinkTable.SetCodelet("SQLOTHERTABLENAME", OtherTable.strName); snippetLinkTable.SetCodelet("SQLLINKTABLENAME", OtherLinkConstraint.strThisTable); string notUsed; int notUsedInt; string formalParametersOtherPrimaryKey; string actualParametersOtherPrimaryKey; PrepareCodeletsPrimaryKey(OtherTable, out formalParametersOtherPrimaryKey, out actualParametersOtherPrimaryKey, out notUsed, out notUsedInt); PrepareCodeletsPrimaryKey(ACurrentTable, out notUsed, out notUsed, out notUsed, out notUsedInt); string whereClauseForeignKey; string whereClauseViaOtherTable; string odbcParametersForeignKey; PrepareCodeletsForeignKey( OtherTable, OtherLinkConstraint, out whereClauseForeignKey, out whereClauseViaOtherTable, out odbcParametersForeignKey, out notUsedInt, out notUsed); string whereClauseViaLinkTable; string whereClauseAllViaTables; PrepareCodeletsViaLinkTable( (TConstraint)References[Count], OtherLinkConstraint, out whereClauseViaLinkTable, out whereClauseAllViaTables); snippetLinkTable.SetCodelet("FORMALPARAMETERSOTHERPRIMARYKEY", formalParametersOtherPrimaryKey); snippetLinkTable.SetCodelet("ACTUALPARAMETERSOTHERPRIMARYKEY", actualParametersOtherPrimaryKey); snippetLinkTable.SetCodelet("ODBCPARAMETERSFOREIGNKEY", odbcParametersForeignKey); snippetLinkTable.SetCodelet("WHERECLAUSEVIALINKTABLE", whereClauseViaLinkTable); snippetLinkTable.SetCodelet("WHERECLAUSEALLVIATABLES", whereClauseAllViaTables); ASnippet.InsertSnippet("VIALINKTABLE", snippetLinkTable); Count = Count + 1; } }
public ProcessTemplateHelper(ProcessTemplate processTemplate, bool failIfTypeUnknown = false) { _processTemplate = processTemplate; _failIfTypeUnknown = failIfTypeUnknown; }
private static void PrepareParametersForMethod( ProcessTemplate snippet, TypeReference AReturnType, List <ParameterDeclarationExpression> AParameters, string AMethodName, ref List <string> AMethodNames) { string ParameterDefinition = string.Empty; string ActualParameters = string.Empty; snippet.SetCodelet("LOCALVARIABLES", string.Empty); string returnCodeFatClient = string.Empty; string returnCodeJSClient = string.Empty; int returnCounter = 0; foreach (ParameterDeclarationExpression p in AParameters) { string parametertype = p.TypeReference.ToString(); bool ArrayParameter = false; // check if the parametertype is not a generic type, eg. dictionary or list if (!parametertype.Contains("<")) { if (parametertype.EndsWith("[]")) { ArrayParameter = true; //Console.WriteLine("ArrayParameter found: " + parametertype); } parametertype = parametertype == "string" || parametertype == "String" ? "System.String" : parametertype; parametertype = parametertype == "bool" || parametertype == "Boolean" ? "System.Boolean" : parametertype; if (parametertype.Contains("UINT") || parametertype.Contains("unsigned")) { parametertype = parametertype.Contains("UInt32") || parametertype == "unsigned int" ? "System.UInt32" : parametertype; parametertype = parametertype.Contains("UInt16") || parametertype == "unsigned short" ? "System.UInt16" : parametertype; parametertype = parametertype.Contains("UInt64") || parametertype == "unsigned long" ? "System.UInt64" : parametertype; } else { parametertype = parametertype.Contains("Int32") || parametertype == "int" ? "System.Int32" : parametertype; parametertype = parametertype.Contains("Int16") || parametertype == "short" ? "System.Int16" : parametertype; parametertype = parametertype.Contains("Int64") || parametertype == "long" ? "System.Int64" : parametertype; } parametertype = parametertype.Contains("Decimal") || parametertype == "decimal" ? "System.Decimal" : parametertype; if (ArrayParameter && !(parametertype.EndsWith("[]"))) { // need to restore Array type! parametertype += "[]"; //Console.WriteLine("ArrayParameter found - new parametertype = " + parametertype); } } bool EnumParameter = parametertype.EndsWith("Enum"); bool BinaryParameter = !((parametertype.StartsWith("System.Int64")) || (parametertype.StartsWith("System.Int32")) || (parametertype.StartsWith("System.Int16")) || (parametertype.StartsWith("System.String")) || (parametertype.StartsWith("System.Boolean")) || EnumParameter); if (ActualParameters.Length > 0) { ActualParameters += ", "; } // ignore out parameters in the web service method definition if ((ParameterModifiers.Out & p.ParamModifier) == 0) { if (ParameterDefinition.Length > 0) { ParameterDefinition += ", "; } if ((!BinaryParameter) && (!ArrayParameter) && (!EnumParameter)) { ParameterDefinition += parametertype + " " + p.ParameterName; } else { ParameterDefinition += "string " + p.ParameterName; } } // for string parameters, check if they have been encoded binary due to special characters in the string; // this obviously does not apply to out parameters if ((parametertype == "System.String") && ((ParameterModifiers.Out & p.ParamModifier) == 0)) { snippet.AddToCodelet( "LOCALVARIABLES", p.ParameterName + " = (string) THttpBinarySerializer.DeserializeObject(" + p.ParameterName + ",\"System.String\");" + Environment.NewLine); } // EnumParameters are also binary encoded // this obviously does not apply to out parameters if (EnumParameter && ((ParameterModifiers.Out & p.ParamModifier) == 0)) { snippet.AddToCodelet( "LOCALVARIABLES", p.ParameterName + " = THttpBinarySerializer.DeserializeObject(" + p.ParameterName + ",\"System.String\").ToString();" + Environment.NewLine); } if ((ParameterModifiers.Out & p.ParamModifier) != 0) { snippet.AddToCodelet("LOCALVARIABLES", parametertype + " " + p.ParameterName + ";" + Environment.NewLine); ActualParameters += "out " + p.ParameterName; } else if ((ParameterModifiers.Ref & p.ParamModifier) != 0) { if (BinaryParameter) { snippet.AddToCodelet("LOCALVARIABLES", parametertype + " Local" + p.ParameterName + " = " + " (" + parametertype + ")THttpBinarySerializer.DeserializeObject(" + p.ParameterName + ",\"binary\");" + Environment.NewLine); ActualParameters += "ref Local" + p.ParameterName; } else if (EnumParameter) { snippet.AddToCodelet("LOCALVARIABLES", parametertype + " Local" + p.ParameterName + " = " + " (" + parametertype + ") Enum.Parse(typeof(" + parametertype + "), " + p.ParameterName + ");" + Environment.NewLine); ActualParameters += "ref Local" + p.ParameterName; } else { ActualParameters += "ref " + p.ParameterName; } } else { if (BinaryParameter || ArrayParameter) { ActualParameters += "(" + parametertype + ")THttpBinarySerializer.DeserializeObject(" + p.ParameterName + ",\"binary\")"; } else if (EnumParameter) { ActualParameters += " (" + parametertype + ") Enum.Parse(typeof(" + parametertype + "), " + p.ParameterName + ")"; } else { ActualParameters += p.ParameterName; } } if (((ParameterModifiers.Ref & p.ParamModifier) > 0) || ((ParameterModifiers.Out & p.ParamModifier) > 0)) { returnCodeFatClient += (returnCodeFatClient.Length > 0 ? "+\",\"+" : string.Empty) + "THttpBinarySerializer.SerializeObjectWithType(" + (((ParameterModifiers.Ref & p.ParamModifier) > 0 && BinaryParameter) ? "Local" : string.Empty) + p.ParameterName + ")"; if (returnCounter == 1) { returnCodeJSClient = "\"{ \\\"0\\\": \" + " + returnCodeJSClient; } if (returnCounter > 0) { returnCodeJSClient += " + \", \\\"" + returnCounter.ToString() + "\\\": \" + "; } returnCodeJSClient += "THttpBinarySerializer.SerializeObjectWithType(" + (((ParameterModifiers.Ref & p.ParamModifier) > 0 && BinaryParameter) ? "Local" : string.Empty) + p.ParameterName + ")"; returnCounter++; } } if (AReturnType != null) { string returntype = AutoGenerationTools.TypeToString(AReturnType, ""); if (!returntype.Contains("<")) { returntype = returntype == "string" || returntype == "String" ? "System.String" : returntype; returntype = returntype == "bool" || returntype == "Boolean" ? "System.Boolean" : returntype; if (returntype.Contains("UINT") || returntype.Contains("unsigned")) { returntype = returntype.Contains("UInt32") || returntype == "unsigned int" ? "System.UInt32" : returntype; returntype = returntype.Contains("UInt16") || returntype == "unsigned short" ? "System.UInt16" : returntype; returntype = returntype.Contains("UInt64") || returntype == "unsigned long" ? "System.UInt64" : returntype; } else { returntype = returntype.Contains("Int32") || returntype == "int" ? "System.Int32" : returntype; returntype = returntype.Contains("Int16") || returntype == "short" ? "System.Int16" : returntype; returntype = returntype.Contains("Int64") || returntype == "long" ? "System.Int64" : returntype; } returntype = returntype.Contains("Decimal") || returntype == "decimal" ? "System.Decimal" : returntype; } if (returnCounter > 0) { if (returntype != "void") { returnCodeFatClient += (returnCodeFatClient.Length > 0 ? "+\",\"+" : string.Empty) + "THttpBinarySerializer.SerializeObjectWithType(Result)"; if (returnCounter == 1) { returnCodeJSClient = "\"{ \\\"0\\\": \" + " + returnCodeJSClient; } returnCodeJSClient += "+\", \\\"" + returnCounter.ToString() + "\\\": \"+" + "THttpBinarySerializer.SerializeObjectWithType(Result)"; returnCounter++; } returntype = "string"; } else if (returntype == "System.String") { returntype = "string"; returnCodeFatClient = "THttpBinarySerializer.SerializeObjectWithType(Result)"; returnCodeJSClient = "Result"; } else if (!((returntype == "System.Int64") || (returntype == "System.Int32") || (returntype == "System.Int16") || (returntype == "System.UInt64") || (returntype == "System.UInt32") || (returntype == "System.UInt16") || (returntype == "System.Decimal") || (returntype == "System.Boolean")) && (returntype != "void")) { returntype = "string"; returnCodeFatClient = returnCodeJSClient = "THttpBinarySerializer.SerializeObject(Result)"; } string localreturn = AutoGenerationTools.TypeToString(AReturnType, ""); if (localreturn == "void") { localreturn = string.Empty; } else if ((returnCodeFatClient.Length > 0) || (returnCodeJSClient.Length > 0)) { localreturn += " Result = "; } else { localreturn = "return "; } if (returnCounter > 1) { returnCodeJSClient += "+ \"}\""; } snippet.SetCodelet("RETURN", string.Empty); if ((returnCodeFatClient.Length > 0) || (returnCodeJSClient.Length > 0)) { snippet.SetCodelet("RETURN", returntype != "void" ? "return isJSClient()?" + returnCodeJSClient + ":" + returnCodeFatClient + ";" : string.Empty); } snippet.SetCodelet("RETURNTYPE", returntype); snippet.SetCodelet("LOCALRETURN", localreturn); } //Console.WriteLine("Final ParameterDefinition = " + ParameterDefinition); snippet.SetCodelet("PARAMETERDEFINITION", ParameterDefinition); snippet.SetCodelet("ACTUALPARAMETERS", ActualParameters); // avoid duplicate names for webservice methods string methodname = AMethodName; int methodcounter = 1; while (AMethodNames.Contains(methodname)) { methodcounter++; methodname = AMethodName + methodcounter.ToString(); } AMethodNames.Add(methodname); snippet.SetCodelet("UNIQUEMETHODNAME", methodname); }
/// <summary> /// fill in the attributes for the control /// </summary> public virtual ProcessTemplate SetControlProperties(TFormWriter writer, TControlDef ACtrl) { if (FAlreadyInserted.Contains(ACtrl.controlName)) { throw new Exception("Cannot insert control " + ACtrl.controlName + " several times into a form"); } FAlreadyInserted.Add(ACtrl.controlName); ProcessTemplate snippetControl = writer.FTemplate.GetSnippet(FControlDefinitionSnippetName); snippetControl.SetCodelet("ITEMNAME", ACtrl.controlName); snippetControl.SetCodelet("ITEMID", ACtrl.controlName); snippetControl.SetCodelet("XTYPE", FControlType); if (ACtrl.HasAttribute("xtype")) { snippetControl.SetCodelet("XTYPE", ACtrl.GetAttribute("xtype")); } if (ACtrl.HasAttribute("maxLength")) { snippetControl.SetCodelet("MAXLENGTH", ACtrl.GetAttribute("maxLength")); } if (ACtrl.HasAttribute("minLength")) { snippetControl.SetCodelet("MINLENGTH", ACtrl.GetAttribute("minLength")); } if (ACtrl.HasAttribute("regex")) { snippetControl.SetCodelet("REGEX", ACtrl.GetAttribute("regex")); } ((TExtJsFormsWriter)writer).AddResourceString(snippetControl, "LABEL", ACtrl, ACtrl.Label); ((TExtJsFormsWriter)writer).AddResourceString(snippetControl, "HELP", ACtrl, ACtrl.GetAttribute("Help")); if (ACtrl.HasAttribute("allowBlank") && (ACtrl.GetAttribute("allowBlank") == "true")) { snippetControl.SetCodelet("ALLOWBLANK", "true"); } if (ACtrl.HasAttribute("inputType")) { snippetControl.SetCodelet("INPUTTYPE", ACtrl.GetAttribute("inputType")); } if (ACtrl.HasAttribute("vtype")) { snippetControl.SetCodelet("VTYPE", ACtrl.GetAttribute("vtype")); } if (ACtrl.HasAttribute("DateFormat")) { snippetControl.SetCodelet("DATEFORMAT", ACtrl.GetAttribute("DateFormat")); } if (ACtrl.HasAttribute("ShowToday")) { snippetControl.SetCodelet("SHOWTODAY", ACtrl.GetAttribute("ShowToday")); } if (ACtrl.HasAttribute("MinDateYear")) { snippetControl.SetCodelet("MINYEAR", ACtrl.GetAttribute("MinDateYear")); snippetControl.SetCodelet("MINMONTH", ACtrl.GetAttribute("MinDateMonth")); snippetControl.SetCodelet("MINDAY", ACtrl.GetAttribute("MinDateDay")); } if (ACtrl.HasAttribute("MaxDateYear")) { snippetControl.SetCodelet("MAXYEAR", ACtrl.GetAttribute("MaxDateYear")); snippetControl.SetCodelet("MAXMONTH", ACtrl.GetAttribute("MaxDateMonth")); snippetControl.SetCodelet("MAXDAY", ACtrl.GetAttribute("MaxDateDay")); } if (ACtrl.HasAttribute("DefaultYear")) { snippetControl.SetCodelet("DEFAULTYEAR", ACtrl.GetAttribute("DefaultYear")); snippetControl.SetCodelet("DEFAULTMONTH", ACtrl.GetAttribute("DefaultMonth")); snippetControl.SetCodelet("DEFAULTDAY", ACtrl.GetAttribute("DefaultDay")); } if (ACtrl.HasAttribute("otherPasswordField")) { snippetControl.SetCodelet("OTHERPASSWORDFIELD", ACtrl.GetAttribute("otherPasswordField")); writer.FTemplate.SetCodelet("PASSWORDTWICE", "yes"); ((TExtJsFormsWriter)writer).AddResourceString(snippetControl, "strErrorPasswordLength", null, ACtrl.GetAttribute("ValidationErrorLength")); ((TExtJsFormsWriter)writer).AddResourceString(snippetControl, "strErrorPasswordNoMatch", null, ACtrl.GetAttribute("ValidationErrorMatching")); } if (ACtrl.GetAttribute("vtype") == "forcetick") { writer.FTemplate.SetCodelet("FORCECHECKBOX", "true"); ((TExtJsFormsWriter)writer).AddResourceString(snippetControl, "strErrorCheckboxRequired", null, ACtrl.GetAttribute("ErrorCheckboxRequired")); } if (FDefaultWidth != -1) { snippetControl.SetCodelet("WIDTH", FDefaultWidth.ToString()); } snippetControl.SetCodelet("CUSTOMATTRIBUTES", ""); return(snippetControl); }
public static void ForUpdate(this ProcessTemplate dest, ProcessTemplate update) { dest.Name = update.Name; }
/// <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"); string ReasonForAutomValidation; bool CheckForEmptyDateGenerated; snippet.SetCodeletComment("TABLE_DESCRIPTION", currentTable.strDescription); snippet.SetCodelet("TABLENAME", currentTable.strDotNetName); foreach (TTableField col in currentTable.grpTableField) { ProcessTemplate columnTemplate; ProcessTemplate validateColumnTemplate; 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); } } Template.InsertSnippet(WhereToInsert, snippet); }