From 7f0eb11f4774aeec4cf14badbf7241f23fb1a98c Mon Sep 17 00:00:00 2001 From: Rich Date: Wed, 22 Apr 2009 13:04:26 +0000 Subject: [PATCH] Various updates to MyGeneration Moved ItemInsert code to ItemInsertExt.cs --- PROMS/MyGeneration/csla_21/CSLA_Objects.csgen | 1147 +++++++++++------ PROMS/MyGeneration/csla_21/FilteredColumns.cs | 17 +- PROMS/MyGeneration/csla_21/FormatColumns.cs | 2 +- .../MyGeneration/csla_21/NamingConvention.cs | 10 +- PROMS/MyGeneration/csla_21/vlnCSLA_SQL.csgen | 38 +- PROMS/MyGeneration/csla_21/vlnSQL_Debug.csgen | 72 +- PROMS/MyGeneration/csla_21/vlnSQL_List.csgen | 45 +- .../VEPROMS.CSLA.Library/Extension/ItemExt.cs | 141 -- 8 files changed, 871 insertions(+), 601 deletions(-) diff --git a/PROMS/MyGeneration/csla_21/CSLA_Objects.csgen b/PROMS/MyGeneration/csla_21/CSLA_Objects.csgen index 04f43b20..7e7d85fa 100644 --- a/PROMS/MyGeneration/csla_21/CSLA_Objects.csgen +++ b/PROMS/MyGeneration/csla_21/CSLA_Objects.csgen @@ -50,7 +50,7 @@ public class GeneratedGui : DotNetScriptGui // Namespace GuiLabel label2 = ui.AddLabel( "label2", "Namespace: ", "Provide your objects namespace." ); label2.Width = 280; - GuiTextBox classNamespace = ui.AddTextBox( "classNamespace", "Volian.CSLA.Library", "Provide your objects namespace." ); + GuiTextBox classNamespace = ui.AddTextBox( "classNamespace", "VEPROMS.CSLA.Library", "Provide your objects namespace." ); classNamespace.Width = 280; GuiLabel label3 = ui.AddLabel( "label3", "Member prefix: ", "Provide your Prefix." ); @@ -238,7 +238,7 @@ public class GeneratedTemplate : DotNetScriptTemplate public bool AddToClassList(string className) { - if(_classList.Contains(className)) + if (_classList.Contains(className)) { _duplicateList.Add(className); return false; @@ -252,17 +252,17 @@ public class GeneratedTemplate : DotNetScriptTemplate public delegate bool Filter(IColumn column); public string Debug(string str) { - if(_chkDebug && str.CompareTo(_tbDebug) >= 0)return "/**** MyGeneration Debug " + str + " ****/"; + if (_chkDebug && str.CompareTo(_tbDebug) >= 0)return "/**** MyGeneration Debug " + str + " ****/"; return ""; } public string DebugLine(string str) { - if(_chkDebug && str.CompareTo(_tbDebug) >= 0)return "\r\n/**** MyGeneration Debug " + str + " ****/"; + if (_chkDebug && str.CompareTo(_tbDebug) >= 0)return "\r\n/**** MyGeneration Debug " + str + " ****/"; return ""; } public void SaveFile() { - if(_chkCreateFiles) + if (_chkCreateFiles) { output.save( Path.Combine( _exportPath, _className + ".cs" ), false ); output.clear(); @@ -271,8 +271,9 @@ public class GeneratedTemplate : DotNetScriptTemplate public GeneratedTemplate( ZeusContext context ) : base( context ) {} public override void Render() - { - if(context.Objects.ContainsKey("DnpUtils"))DnpUtils.SaveInputToCache(context); + { + DateTime tStart = DateTime.Now; + if (context.Objects.ContainsKey("DnpUtils"))DnpUtils.SaveInputToCache(context); try{ InitializeDictionaries(); _dbName = input["chooseDatabase"].ToString(); @@ -299,13 +300,13 @@ public class GeneratedTemplate : DotNetScriptTemplate _chkPartEXT=(bool)input["chkPartEXT"]; _chkPartCM=(bool)input["chkPartCM"]; _chkPartL4N=(bool)input["chkPartL4N"]; - if(_chkPartL4N) + if (_chkPartL4N) { - _databaseLogDebug = "if(_MyLog.IsDebugEnabled)_MyLog.DebugFormat"; - _databaseLogInfo = "if(_MyLog.IsInfoEnabled)_MyLog.InfoFormat"; - _databaseLogWarn = "if(_MyLog.IsWarnEnabled)_MyLog.WarnFormat"; - _databaseLogError = "if(_MyLog.IsErrorEnabled)_MyLog.Error"; - _databaseLogFatal = "if(_MyLog.IsFatalEnabled)_MyLog.Fatal"; + _databaseLogDebug = "if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat"; + _databaseLogInfo = "if (_MyLog.IsInfoEnabled) _MyLog.InfoFormat"; + _databaseLogWarn = "if (_MyLog.IsWarnEnabled) _MyLog.WarnFormat"; + _databaseLogError = "if (_MyLog.IsErrorEnabled) _MyLog.Error"; + _databaseLogFatal = "if (_MyLog.IsFatalEnabled) _MyLog.Fatal"; } else { @@ -321,7 +322,7 @@ public class GeneratedTemplate : DotNetScriptTemplate _tbDebug=(string)input["tbDebug"]; _classList=new ArrayList(); _duplicateList=new ArrayList(); - if(_chkDatabase)GenerateDatabase(); + if (_chkDatabase)GenerateDatabase(); foreach( string _newTable in _selectedTables ) { _workingTable = MyMeta.Databases[_dbName].Tables[_newTable]; @@ -329,7 +330,7 @@ public class GeneratedTemplate : DotNetScriptTemplate } GeneratePropertyDescriptor(); GenerateCommonRules(); - if(_duplicateList.Count > 0) + if (_duplicateList.Count > 0) { WriteLine("Duplicate Classes"); foreach(string s in _duplicateList) @@ -337,6 +338,8 @@ public class GeneratedTemplate : DotNetScriptTemplate WriteLine("[{0}]",s); } } + DateTime tEnd = DateTime.Now; + WriteLine(string.Format("Total Generation Time: {0} Seconds",TimeSpan.FromTicks(tEnd.Ticks - tStart.Ticks).TotalSeconds)); //foreach( string _newView in _selectedViews ) //{ // IView _workingView = MyMeta.Databases[_dbName].Views[_newView]; @@ -357,6 +360,7 @@ public class GeneratedTemplate : DotNetScriptTemplate dicRead["DateTime"]="{fmember} = dr.GetDateTime(\"{fname}\");"; dicRead["timestamp"]="dr.GetBytes(\"{fname}\", 0, {fmember}, 0, 8);"; dicRead["image"]="{fmember} = (byte[])dr.GetValue(\"{fname}\");"; + dicRead["varbinary"]="{fmember} = (byte[])dr.GetValue(\"{fname}\");"; dicRead["int"]="{fmember} = dr.GetInt32(\"{fname}\");"; dicRead["Int32"]="{fmember} = dr.GetInt32(\"{fname}\");"; dicRead["Int16"]="{fmember} = dr.GetInt16(\"{fname}\");"; @@ -381,27 +385,27 @@ public class GeneratedTemplate : DotNetScriptTemplate dicRead["decimal?"]="{fmember} = ({ctype})dr.GetValue(\"{fname}\");"; dicRead["bool?"]="{fmember} = ({ctype})dr.GetValue(\"{fname}\");"; dicRead["long?"]="{fmember} = ({ctype})dr.GetValue(\"{fname}\");"; - dicRead["DateTime?"]="if(!dr.IsDBNull(dr.GetOrdinal(\"{fname}\"))) {fmember} = dr.GetDateTime(\"{fname}\");"; + dicRead["DateTime?"]="if (!dr.IsDBNull(dr.GetOrdinal(\"{fname}\"))) {fmember} = dr.GetDateTime(\"{fname}\");"; } private void GenerateClassFiles(ITable tbl) { - if(_chkGenerateMain)GenerateMainClass(tbl); + if (_chkGenerateMain)GenerateMainClass(tbl); Hashtable dicAlias = new Hashtable(); foreach(IForeignKey fk in tbl.ForeignKeys) { - if(tbl == fk.PrimaryTable) + if (tbl == fk.PrimaryTable) { - if(!IsPrimaryKey(fk)) + if (!IsPrimaryKey(fk)) { //string sAlias = GetAlias(dicAlias,fk.ForeignTable); string sAlias = GetAlias(fk); - if(_chkFKList)GenerateFKListClass(fk,sAlias); - if(_chkFKItem && fk.PrimaryTable != fk.ForeignTable )GenerateFKClass(fk,sAlias); + if (_chkFKList)GenerateFKListClass(fk,sAlias); + if (_chkFKItem && fk.PrimaryTable != fk.ForeignTable )GenerateFKClass(fk,sAlias); } } } - if(_chkInfoList && AnyNotOneToOne(tbl))GenerateInfoListClass(tbl); // InfoList if any non 1 to 1 relationships - if(_chkInfo)GenerateInfoClass(tbl); + if (_chkInfoList && AnyNotOneToOne(tbl))GenerateInfoListClass(tbl); // InfoList if any non 1 to 1 relationships + if (_chkInfo)GenerateInfoClass(tbl); } // private void ShowForeignKey(ForeignKey fk) // { @@ -414,11 +418,11 @@ public class GeneratedTemplate : DotNetScriptTemplate { _className = ClassName( tbl ); _PropDescList.Add(_className); - if(!AddToClassList(_className))return; + if (!AddToClassList(_className))return; _tableName = tbl.Alias; vlnHeader("\r\nusing System.Collections.Generic;\r\nusing Csla.Validation;"); string sInterface=""; - if(_chkPartCM) + if (_chkPartCM) { //sInterface = ", ICustomTypeDescriptor"; %> @@ -430,30 +434,30 @@ public class GeneratedTemplate : DotNetScriptTemplate Log4Net(); vlnRefreshInfo(); vlnCollection(tbl,UniqueIndexes(tbl),false); - if(_chkPartBM)vlnBusinessMethods(tbl.Columns); - if(_chkPartVR)vlnValidationRules(tbl.Columns); - if(_chkPartAR)vlnAuthorizationRules(tbl.Columns); - if(_chkPartFM)vlnFactoryMethods(tbl.Columns); - if(_chkPartDA)vlnDataAccessPortal(tbl.Columns); - if(_chkPartEX)vlnExists(tbl.Columns); - if(_chkPartDF)vlnDefaults(tbl.Columns); + if (_chkPartBM)vlnBusinessMethods(tbl.Columns); + if (_chkPartVR)vlnValidationRules(tbl.Columns); + if (_chkPartAR)vlnAuthorizationRules(tbl.Columns); + if (_chkPartFM)vlnFactoryMethods(tbl.Columns); + if (_chkPartDA)vlnDataAccessPortal(tbl.Columns); + if (_chkPartEX)vlnExists(tbl.Columns); + if (_chkPartDF)vlnDefaults(tbl.Columns); vlnFooterCM(""); - if(_chkPartEXT)vlnExtension(tbl.Columns); + if (_chkPartEXT)vlnExtension(tbl.Columns); SaveFile(); } private void GenerateFKListClass(IForeignKey fk,string sAlias) { _className = ClassName( fk.PrimaryTable ) + ClassesName( fk.ForeignTable )+sAlias; _className = FKClassesName(fk)+sAlias; - if(!AddToClassList(_className))return; - if(fk.PrimaryTable == fk.ForeignTable) + if (!AddToClassList(_className))return; + if (fk.PrimaryTable == fk.ForeignTable) _subclassName = ClassName( fk.PrimaryTable); else _subclassName = ClassName( fk.PrimaryTable) + ClassName( fk.ForeignTable )+sAlias; _tableName = "//TODO: No Table Name"; - vlnHeader("\r\nusing Csla.Validation;"); + vlnHeader("\r\nusing System.Collections.Generic;\r\nusing Csla.Validation;"); string sInterface = ""; - if(_chkPartCM) + if (_chkPartCM) { sInterface = ", ICustomTypeDescriptor"; %> @@ -463,10 +467,10 @@ public class GeneratedTemplate : DotNetScriptTemplate public partial class <%=_className%> : BusinessListBase<<%=_className%>, <%=_subclassName%>><%=sInterface%>, IVEHasBrokenRules {<% Log4Net(); - if(_chkPartBM)vlnBusinessMethodsFKList(fk,sAlias); - if(_chkPartVR)vlnValidationRulesFKList(fk,sAlias); - if(_chkPartFM)vlnFactoryMethodsFKList(fk,sAlias); - if(_chkPartDA)vlnDataAccessPortalFKList(fk,sAlias); + if (_chkPartBM)vlnBusinessMethodsFKList(fk,sAlias); + if (_chkPartVR)vlnValidationRulesFKList(fk,sAlias); + if (_chkPartFM)vlnFactoryMethodsFKList(fk,sAlias); + if (_chkPartDA)vlnDataAccessPortalFKList(fk,sAlias); vlnFooterCM(ClassesName( fk.ForeignTable ) + sAlias); SaveFile(); } @@ -474,11 +478,11 @@ public class GeneratedTemplate : DotNetScriptTemplate { _className = ClassName( fk.PrimaryTable ) + ClassName( fk.ForeignTable ) + sAlias; _PropDescList.Add(_className); - if(!AddToClassList(_className))return; + if (!AddToClassList(_className))return; _tableName = fk.ForeignTable.Alias; - vlnHeader("\r\nusing Csla.Validation;"); + vlnHeader("\r\nusing System.Collections.Generic;\r\nusing Csla.Validation;"); string sInterface=""; - if(_chkPartCM) + if (_chkPartCM) { //sInterface = ", ICustomTypeDescriptor"; %> @@ -488,25 +492,25 @@ public class GeneratedTemplate : DotNetScriptTemplate public partial class <%=_className%> : BusinessBase<<%=_className%>><%=sInterface%>, IVEHasBrokenRules {<% Log4Net(); - if(_chkPartBM)vlnBusinessMethodsFKItem(fk,sAlias); - if(_chkPartVR)vlnValidationRulesFKItem(fk,sAlias); - if(_chkPartAR)vlnAuthorizationRulesFKItem(fk,sAlias); - if(_chkPartFM)vlnFactoryMethodsFKItem(fk,sAlias); - if(_chkPartDA)vlnDataAccessPortalFKItem(fk,sAlias); - if(_chkPartDF)vlnDefaults(fk.ForeignTable.Columns); + if (_chkPartBM)vlnBusinessMethodsFKItem(fk,sAlias); + if (_chkPartVR)vlnValidationRulesFKItem(fk,sAlias); + if (_chkPartAR)vlnAuthorizationRulesFKItem(fk,sAlias); + if (_chkPartFM)vlnFactoryMethodsFKItem(fk,sAlias); + if (_chkPartDA)vlnDataAccessPortalFKItem(fk,sAlias); + if (_chkPartDF)vlnDefaults(fk.ForeignTable.Columns); vlnFooterCM(""); - if(_chkPartEXT)vlnExtension(fk.ForeignTable.Columns); + if (_chkPartEXT)vlnExtension(fk.ForeignTable.Columns); SaveFile(); } private void vlnFooterCM(string displayName) { - if(_chkPartCM) + if (_chkPartCM) { - if(displayName!="")vlnComponentModelFKList(); + if (displayName!="")vlnComponentModelFKList(); %> } // Class<% - if(displayName!="")vlnPropertyDescriptorFKList(); - if(displayName!="")vlnConvertorFKList(displayName); + if (displayName!="")vlnPropertyDescriptorFKList(); + if (displayName!="")vlnConvertorFKList(displayName); else vlnConvertorFKItem(); %> } // Namespace @@ -523,12 +527,12 @@ public class GeneratedTemplate : DotNetScriptTemplate private void GenerateInfoListClass( ITable tbl ) { _className = ClassName( tbl ) + "InfoList"; - if(!AddToClassList(_className))return; + if (!AddToClassList(_className))return; _tableName = tbl.Alias; _subclassName = ClassName( tbl ) + "Info"; vlnHeader("\r\nusing System.Collections.Generic;"); string sInterface=""; - if(_chkPartCM) + if (_chkPartCM) { sInterface = ", ICustomTypeDescriptor"; %> @@ -538,7 +542,7 @@ public class GeneratedTemplate : DotNetScriptTemplate public partial class <%=_className%> : ReadOnlyListBase<<%=_className%>, <%=_subclassName%>><%=sInterface%>, IDisposable {<% Log4Net(); - if(_chkPartBM) + if (_chkPartBM) { %> #region Business Methods @@ -567,8 +571,8 @@ public class GeneratedTemplate : DotNetScriptTemplate } } #endregion<%} - if(_chkPartFM)vlnFactoryMethodsInfoList(tbl.Columns); - if(_chkPartDA)vlnDataAccessPortalInfoList(tbl.Columns); + if (_chkPartFM)vlnFactoryMethodsInfoList(tbl.Columns); + if (_chkPartDA)vlnDataAccessPortalInfoList(tbl.Columns); vlnFooterCM(ClassesName( tbl ) ); SaveFile(); } @@ -576,11 +580,11 @@ public class GeneratedTemplate : DotNetScriptTemplate { _className = ClassName( tbl ) + "Info"; _PropDescList.Add(_className); - if(!AddToClassList(_className))return; + if (!AddToClassList(_className))return; _tableName = tbl.Alias; vlnHeader("\r\nusing System.Collections.Generic;","\r\n\tpublic delegate void " + _className + "Event(object sender);"); string sInterface=""; - if(_chkPartCM) + if (_chkPartCM) { //sInterface = ", ICustomTypeDescriptor"; %> @@ -596,9 +600,9 @@ public class GeneratedTemplate : DotNetScriptTemplate }<% Log4Net(); vlnCollection(tbl,new ArrayList(),true); - if(_chkPartBM)vlnBusinessMethodsInfo(tbl.Columns); - if(_chkPartFM)vlnFactoryMethodsInfo(tbl.Columns); - if(_chkPartDA)vlnDataAccessPortalInfo(tbl.Columns); + if (_chkPartBM)vlnBusinessMethodsInfo(tbl.Columns); + if (_chkPartFM)vlnFactoryMethodsInfo(tbl.Columns); + if (_chkPartDA)vlnDataAccessPortalInfo(tbl.Columns); vlnInfoExtension(tbl.Columns);//20070410 vlnFooterCM(""); SaveFile(); @@ -621,7 +625,7 @@ public class GeneratedTemplate : DotNetScriptTemplate } private void vlnHeader(string sUsing,string sDelegate,bool serialize) { - if(_chkVolian){ + if (_chkVolian){ %>// ======================================================================== // Copyright 2007 - Volian Enterprises, Inc. All rights reserved. // Volian Enterprises - Proprietary Information - DO NOT COPY OR DISTRIBUTE @@ -641,7 +645,7 @@ using Csla; using Csla.Data; using System.Configuration; using System.IO;<% - if(_chkPartCM) + if (_chkPartCM) { %> using System.ComponentModel;<% @@ -652,7 +656,7 @@ namespace <%=_nameSpace%> /// /// <%=_className%> Generated by MyGeneration using the CSLA Object Mapping template /// <% - if(serialize) + if (serialize) { %> [Serializable()]<% @@ -662,10 +666,10 @@ namespace <%=_nameSpace%> { IColumns colsi = ind.Columns; IColumns colsp = ind.Table.PrimaryKeys; - if(colsi.Count != colsp.Count)return false; + if (colsi.Count != colsp.Count)return false; for(int i=0;i ArrayList retval = new ArrayList(); foreach(Index ind in tbl.Indexes) { - if(!IsPrimaryKey(ind) && ind.Unique) + if (!IsPrimaryKey(ind) && ind.Unique) { retval.Add(ind); } @@ -690,49 +694,69 @@ namespace <%=_nameSpace%> string pKeysType = FormatColumns("{ctype} {local}",tbl.PrimaryKeys,", ",""); %> #region Collection - protected static List<<%=_className%>> _AllList = new List<<%=_className%>>(); - private static Dictionary> _AllByPrimaryKey = new Dictionary>();<% + private static List<<%=_className%>> _CacheList = new List<<%=_className%>>(); + protected static void AddToCache(<%=_className%> <%=LocalName(_className)%>) + { + if (!_CacheList.Contains(<%=LocalName(_className)%>)) _CacheList.Add(<%=LocalName(_className)%>); // In AddToCache + } + protected static void RemoveFromCache(<%=_className%> <%=LocalName(_className)%>) + { + while (_CacheList.Contains(<%=LocalName(_className)%>)) _CacheList.Remove(<%=LocalName(_className)%>); // In RemoveFromCache + } + private static Dictionary>> _CacheByPrimaryKey = new Dictionary>>();<% //ArrayList uniqueIndexes=UniqueIndexes(tbl); foreach(IIndex ind in uniqueIndexes) { string sBy = FormatColumns("{name}",ind.Columns,"_",""); %> - private static Dictionary> _AllBy<%=sBy%> = new Dictionary>();<% + private static Dictionary>> _CacheBy<%=sBy%> = new Dictionary>>();<% } %> private static void ConvertListToDictionary() { List<<%=_className%>> remove = new List<<%=_className%>>(); - foreach (<%=_className%> tmp in _AllList) + foreach (<%=_className%> tmp in _CacheList) { - _AllByPrimaryKey[<%=pKey%>]=tmp; // Primary Key<% + if (!_CacheByPrimaryKey.ContainsKey(<%=pKey%>)) + { + _CacheByPrimaryKey[<%=pKey%>] = new List<<%=_className%>>(); // Add new list for PrimaryKey<% foreach(IIndex ind in uniqueIndexes) { string sBy = FormatColumns("{name}",ind.Columns,"_",""); string sKey = FormatColumns("tmp.{prop}.ToString()",ind.Columns," + \"_\" + ",""); %> - _AllBy<%=sBy%>[<%=sKey%>] = tmp; // Unique Index<% + _CacheBy<%=sBy%>[<%=sKey%>] = new List<<%=_className%>>(); // Add new list for <%=sBy%><% + } +%> + } + _CacheByPrimaryKey[<%=pKey%>].Add(tmp); // Add to Primary Key list<% + foreach(IIndex ind in uniqueIndexes) + { + string sBy = FormatColumns("{name}",ind.Columns,"_",""); + string sKey = FormatColumns("tmp.{prop}.ToString()",ind.Columns," + \"_\" + ",""); +%> + _CacheBy<%=sBy%>[<%=sKey%>].Add(tmp); // Unique Index<% } %> remove.Add(tmp); } foreach (<%=_className%> tmp in remove) - _AllList.Remove(tmp); + RemoveFromCache(tmp); }<% - if(bInfo && AnyNotOneToOne(_workingTable)) // AddList function for infolist - Any non 1 to 1 relationships + if (bInfo && AnyNotOneToOne(_workingTable)) // AddList function for infolist - Any non 1 to 1 relationships { %> internal static void AddList(<%=_className%>List lst) { - foreach (<%=_className%> item in lst) _AllList.Add(item); + foreach (<%=_className%> item in lst) AddToCache(item); }<% } %> - public static <%=_className%> GetExistingByPrimaryKey(<%=pKeysType%>) + protected static <%=_className%> GetCachedByPrimaryKey(<%=pKeysType%>) { ConvertListToDictionary(); string key = <%=pKey2%>; - if (_AllByPrimaryKey.ContainsKey(key)) return _AllByPrimaryKey[key]; + if (_CacheByPrimaryKey.ContainsKey(key)) return _CacheByPrimaryKey[key][0]; return null; }<% foreach(IIndex ind in uniqueIndexes) @@ -742,11 +766,11 @@ namespace <%=_nameSpace%> string sKeysType = FormatColumns("{ctype} {local}",ind.Columns,", ",""); string sKeys = FormatColumns("{local}",ind.Columns,", ",""); %> - public static <%=_className%> GetExistingBy<%=sBy%>(<%=sKeysType%>) + protected static <%=_className%> GetCachedBy<%=sBy%>(<%=sKeysType%>) { ConvertListToDictionary(); string key = <%=sKey%>; - if (_AllBy<%=sBy%>.ContainsKey(key)) return _AllBy<%=sBy%>[key]; + if (_CacheBy<%=sBy%>.ContainsKey(key)) return _CacheBy<%=sBy%>[key][0]; return null; }<% } @@ -772,9 +796,9 @@ namespace <%=_nameSpace%> private string ParentCheck(IColumn col) // 20070221 - Logic to check for parent value { IForeignKey pfk = FKParentFK(col.Table); - if(pfk == null)return null; + if (pfk == null)return null; IColumn relCol = RelatedColumnF(col,pfk); - if(relCol==null) return null; + if (relCol==null) return null; return FormatColumn("\r\n\t\t\t\tif (_" + ParentName(pfk) + " != null) return _" + ParentName(pfk) + ".{prop};",relCol); } private void vlnProperties(IColumns Columns) @@ -786,24 +810,24 @@ namespace <%=_nameSpace%> // bool bRelatedObject = true; vlnIdentity(col); // string sParentCheck = ParentCheck(col); -// if(sParentCheck != null) +// if (sParentCheck != null) // { // bReadOnly=true; // bRelatedObject=false; // } // Need logic to handle parent child string sParentCheck=""; - if(IsRelObj(col)) + if (IsRelObj(col)) sParentCheck =FormatColumn("\r\n\t\t\t\tif ({!member} != null) {member} = {!member}.{!column};",col); vlnProperty(CSLAType( col ),MemberName(col) - ,PropertyName(col),InitializeValue( col ),GetDescription(col),bReadOnly || IsRelObj(col),col.IsInPrimaryKey,false,null,sParentCheck,null); -// if(bRelatedObject) + ,PropertyName(col),InitializeValue( col ),GetDescription(col),bReadOnly || IsRelObj(col),col.IsInPrimaryKey,false,null,sParentCheck,null,null); +// if (bRelatedObject) vlnRelObjProperty(col,bReadOnly,false); } // Add Foreign Key Properties - This should be controllable // foreach(IColumn field in Columns) // { -// if( field.IsInForeignKey && field.IsInPrimaryKey) +// if (field.IsInForeignKey && field.IsInPrimaryKey) // { //A column that's in a fk and in the pk represents a fk relationship //from another table, a one-to-many relationship. (This might be @@ -815,73 +839,123 @@ namespace <%=_nameSpace%> Hashtable dicAlias = new Hashtable(); foreach(IForeignKey fk in _workingTable.ForeignKeys) { - if(fk.PrimaryTable == _workingTable){ + if (fk.PrimaryTable == _workingTable){ //string sAlias = GetAlias(dicAlias,fk.ForeignTable); string sAlias = GetAlias(fk); // string sList = _className + ClassesName( fk.ForeignTable ); string sList = FKClassName(fk ); string sLists = FKClassesName(fk ); vlnProperty("int",MemberName(sList) + sAlias + "Count" ,sList + sAlias + "Count", " = 0;", - "Count of " + sLists + " for this " + ClassName(_workingTable) + Debug("20070501.3"),true,false,false,null,null,null); - if(!IsPrimaryKey(fk)){ + "Count of " + sLists + " for this " + ClassName(_workingTable) + Debug("20070501.3"),true,false,false,null,null,null,null); + if (!IsPrimaryKey(fk)){ //vlnProperty(sLists+sAlias,MemberName(sLists)+sAlias,sLists + sAlias, - //" = " + sLists+sAlias + ".New();","Related Field" + Debug("20070501.2"),true,false,true,fk,null,null); + //" = " + sLists+sAlias + ".New();","Related Field" + Debug("20070501.2"),true,false,true,fk,null,null,null); vlnProperty(sLists+sAlias,MemberName(sLists)+sAlias,sLists + sAlias, - " = null;","Related Field" + Debug("20070501.2"),true,false,true,fk,null,null); + " = null;","Related Field" + Debug("20070501.2"),true,false,true,fk,null,null,null); //sExtDirty += " || " + MemberName(sLists+sAlias) + ".IsDirty"; //sExtValid += " && " + MemberName(sLists+sAlias) + ".IsValid"; - sExtDirty += string.Format(" || ({0} == null? false : {0}.IsDirty)",MemberName(sLists+sAlias)); - sExtValid += string.Format(" && ({0} == null? true : {0}.IsValid)",MemberName(sLists+sAlias)); + sExtDirty += string.Format(" || ({0} == null ? false : {0}.IsDirtyList(list))",MemberName(sLists+sAlias)); + sExtValid += string.Format(" && ({0} == null ? true : {0}.IsValid)",MemberName(sLists+sAlias)); } else { string sItem = ClassName(fk.ForeignTable); //vlnProperty(sItem+sAlias, MemberName("My" + sItem)+sAlias,"My" + sItem + sAlias, - //" = My" + sItem+sAlias + ".New();","Related Field",true,false,true,fk,null); - string sCheck = string.Format("\r\n\t\t\t\tif ( {0} == null) {0} = {1}.New({2});", + //" = My" + sItem+sAlias + ".New();","Related Field",true,false,true,fk,null,null); + string sCheck = string.Format("\r\n\t\t\t\tif ({0} == null) {0} = {1}.New({2});", MemberName("My" + sItem)+sAlias, sItem, OneToOne(fk) ? "this" : FormatColumns("{member}",fk.PrimaryColumns,", ","")); vlnProperty(sItem+sAlias, MemberName("My" + sItem)+sAlias,"My" + sItem + sAlias, - " = null;","Related Field" + Debug("20070501.1"),true,false,true,fk,sCheck,null); + " = null;","Related Field" + Debug("20070501.1"),true,false,true,fk,sCheck,null,null); bool bReq = !fk.ForeignColumns[0].IsNullable; - sExtDirty += string.Format(" || ({0} == null? false : {0}.IsDirty)",MemberName("My" + sItem+sAlias)); - sExtValid += string.Format(" && ({0} == null? true : {0}.IsValid)",MemberName("My" + sItem+sAlias)); + sExtDirty += string.Format(" || ({0} == null ? false : {0}.IsDirtyList(list))",MemberName("My" + sItem+sAlias)); + sExtValid += string.Format(" && ({0} == null ? true : {0}.IsValid)",MemberName("My" + sItem+sAlias)); } } else // { - if(IsPrimaryKey1(fk) && !IsPrimaryKey(fk)){ + if (IsPrimaryKey1(fk) && !IsPrimaryKey(fk)){ bool bReq = !fk.ForeignColumns[0].IsNullable; string sClass = ClassName(fk.PrimaryTable.Name) + GetNewAlias(fk,fk); //sExtDirty += string.Format(" || ({0} == null? " + bReq.ToString().ToLower() + " : {0}.IsDirty)",MemberName("My" + sClass)); //sExtValid += string.Format(" && ({0} == null? " + (!bReq).ToString().ToLower() + " : {0}.IsValid)",MemberName("My" + sClass)); - sExtDirty += string.Format(" || ({0} == null? false : {0}.IsDirty)",MemberName("My" + sClass)); - sExtValid += string.Format(" && ({0} == null? true : {0}.IsValid)",MemberName("My" + sClass)); + sExtDirty += string.Format(" || ({0} == null ? false : {0}.IsDirtyList(list))",MemberName("My" + sClass)); + sExtValid += string.Format(" && ({0} == null ? true : {0}.IsValid)",MemberName("My" + sClass)); } } } - if(sExtDirty!="")vlnDirty(sExtDirty); - //if(sExtValid!="")vlnOverride("Valid",sExtValid); + //if (sExtDirty!="") + vlnDirty(sExtDirty); + //if (sExtValid!="")vlnOverride("Valid",sExtValid); vlnValid(sExtValid); // } // } } private void vlnDirty(string sExtension) { + if(sExtension == "") + { %> public override bool IsDirty { - get { return base.IsDirty<%=sExtension%>; } + get { return base.IsDirty; } + } + public bool IsDirtyList(List list) + { + return base.IsDirty; }<% + } + else + { + %> + public override bool IsDirty + { + get + { + if ( base.IsDirty ) + return true; + return IsDirtyList(new List()); + } + } + public bool IsDirtyList(List list) + { + if (base.IsDirty || list.Contains(this)) + return base.IsDirty; + list.Add(this); + return base.IsDirty<%=sExtension%>; + }<% + } } private void vlnValid(string sExtension) { + if(sExtension == "") + { %> public override bool IsValid { - get { return (IsNew && !IsDirty ? true : base.IsValid)<%=sExtension%>; } + get { return (IsNew && !IsDirty) ? true : base.IsValid; } + } + public bool IsValidList(List list) + { + return (IsNew && !IsDirty) ? true : base.IsValid; }<% + } + else + { + %> + public override bool IsValid + { + get { return IsValidList(new List()); } + } + public bool IsValidList(List list) + { + if(list.Contains(this)) + return (IsNew && !IsDirty) ? true : base.IsValid; + list.Add(this); + return ((IsNew && !IsDirty) ? true : base.IsValid)<%=sExtension%>; + }<% + } } private void vlnIdentity(IColumn column) { - if(column.IsAutoKey) + if (column.IsAutoKey) { string sProp=FormatColumn("{prop}",column); %> @@ -894,37 +968,54 @@ namespace <%=_nameSpace%> } private void vlnLazyLoad(string sType,string sMemberName,string sPropertyName,IForeignKey fk) { - if(fk==null)return; - //if(OneToOne(fk.ForeignTable))return; - if(OneToOne(fk))return; + if (fk==null)return; + //if (OneToOne(fk.ForeignTable))return; + if (OneToOne(fk))return; string sBy = FormatColumns("{name}",fk.ForeignColumns,"_",""); string sKeys=FormatColumns("{prop}",fk.PrimaryColumns,", ",""); string sRelClass=FKClassesName(fk) + GetAlias(fk); string sClassName=MemberName(FKClassName(fk) + GetAlias(fk));//20070207 %> - if(<%=sClassName%>Count > 0 && <%=sMemberName%> == null) + if (<%=sClassName%>Count < 0 || (<%=sClassName%>Count > 0 && <%=sMemberName%> == null)) <%=sMemberName%> = <%=sType%>.GetBy<%=sBy%>(<%=sKeys%>); - else if(<%=sMemberName%> == null) + if (<%=sClassName%>Count < 0 ) + <%=sClassName%>Count = <%=sMemberName%> == null ? 0 : <%=sMemberName%>.Count; + if (<%=sMemberName%> == null) <%=sMemberName%> = <%=sRelClass%>.New();<% } - private void vlnProperty(string sType,string sMemberName,string sPropertyName,string sDefault,string sDescription,bool bReadOnly,bool bPrimaryKey,bool bCompModel,IForeignKey fk,string sParentCheck,string sParentCheck2) + private void vlnResetLazyLoad(string sType,string sMemberName,string sPropertyName,IForeignKey fk) + { + if (fk==null)return; + //if (OneToOne(fk.ForeignTable))return; + if (OneToOne(fk))return; + string sBy = FormatColumns("{name}",fk.ForeignColumns,"_",""); + string sKeys=FormatColumns("{prop}",fk.PrimaryColumns,", ",""); + string sRelClass=FKClassesName(fk) + GetAlias(fk); + string sClassName=MemberName(FKClassName(fk) + GetAlias(fk));//20070207 +%> + public void Reset<%=sMemberName%>() + { + <%=sClassName%>Count = -1; + }<% + } + private void vlnProperty(string sType,string sMemberName,string sPropertyName,string sDefault,string sDescription,bool bReadOnly,bool bPrimaryKey,bool bCompModel,IForeignKey fk,string sParentCheck,string sParentCheck2, string sParentCheck3) { string suffix = (sPropertyName==_className?"Fld":""); %> private <%=ReturnType(sType)%> <%=sMemberName%><%=suffix%><%=sDefault%><% - if(!sDefault.EndsWith("timestamp")){ - if(sDescription != ""){ + if (!sDefault.EndsWith("timestamp")){ + if (sDescription != ""){ %> /// /// <%=sDescription%> /// <% } - if(_chkPartCM && bCompModel) + if (_chkPartCM && bCompModel) { %> [TypeConverter(typeof(<%=sType%>Converter))]<% } - if(bPrimaryKey){ + if (bPrimaryKey){ %> [System.ComponentModel.DataObjectField(true, true)]<% } @@ -934,10 +1025,10 @@ namespace <%=_nameSpace%> [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { - CanReadProperty("<%=sPropertyName%><%=suffix%>",true);<%vlnLazyLoad(sType,sMemberName,sPropertyName,fk);%><%=sParentCheck%> + CanReadProperty("<%=sPropertyName%><%=suffix%>", true);<%vlnLazyLoad(sType,sMemberName,sPropertyName,fk);%><%=sParentCheck%> return <%=sMemberName%><%=suffix%><%=ReturnMember(sType)%>; }<% - if(!bReadOnly){ + if (!bReadOnly){ switch(sType) { case "SmartDate": @@ -945,7 +1036,7 @@ namespace <%=_nameSpace%> [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { - CanWriteProperty("<%=sPropertyName%><%=suffix%>",true); + CanWriteProperty("<%=sPropertyName%><%=suffix%>", true); if (value == null) value = string.Empty; <%=sMemberName%><%=suffix%> = value; try @@ -968,13 +1059,22 @@ namespace <%=_nameSpace%> [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { - CanWriteProperty("<%=sPropertyName%><%=suffix%>",true);<% - if(sType=="string"){ + CanWriteProperty("<%=sPropertyName%><%=suffix%>", true);<% + if (sType=="string"){ %> if (value == null) value = string.Empty;<% } + if(sParentCheck2 ==null) // 20080722RHM + { +%> + if (<%=sMemberName%><%=suffix%> != value)<% + } + else// 20080722RHM + { +%> + if (<%=sParentCheck3%>)<% + } %> - if (<%=sMemberName%><%=suffix%> != value) { <%=sMemberName%><%=suffix%><%=ReturnMember(sType)%> = value;<%=sParentCheck2%> PropertyHasChanged(); @@ -984,7 +1084,7 @@ namespace <%=_nameSpace%> } } %> - }<% + }<%vlnResetLazyLoad(sType,sMemberName,sPropertyName,fk);%><% } } @@ -1005,7 +1105,7 @@ namespace <%=_nameSpace%> { string keyID=""; string sep="("; - if(Columns.Count==1){ + if (Columns.Count==1){ keyID=MemberName(Columns[0]); } else @@ -1013,7 +1113,7 @@ namespace <%=_nameSpace%> foreach(IColumn field in Columns) { keyID+=sep+MemberName(field)+ ".ToString()"; - sep="+\".\"+"; + sep=" + \".\" + "; } keyID+=").GetHashCode()"; } @@ -1041,23 +1141,24 @@ namespace <%=_nameSpace%> %> #region ValidationRules [NonSerialized] - private bool _CheckingBrokenRules=false; + private bool _CheckingBrokenRules = false; public IVEHasBrokenRules HasBrokenRules {<%=Debug("20070509.vlnValidationRules")%> - get { - if(_CheckingBrokenRules)return null; + get + { + if (_CheckingBrokenRules) return null; if ((IsDirty || !IsNew) && BrokenRulesCollection.Count > 0) return this; try { - _CheckingBrokenRules=true; + _CheckingBrokenRules = true; IVEHasBrokenRules hasBrokenRules = null;<% - vlnBrokenRuleObjects(Columns); + vlnBrokenRuleObjects(Columns); %> return hasBrokenRules; } finally { - _CheckingBrokenRules=false; + _CheckingBrokenRules = false; } } } @@ -1074,13 +1175,13 @@ namespace <%=_nameSpace%> {<% foreach(IColumn field in Columns) { - if(field.LanguageType=="string") + if (field.LanguageType=="string") { vlnAddRequired(field); - if(field.CharacterMaxLength < 2147483647) + if (field.CharacterMaxLength < 2147483647) vlnAddMaxLength(PropertyName(field),field.CharacterMaxLength); } - if(CSLAType( field )=="SmartDate") + if (CSLAType( field )=="SmartDate") { vlnAddRequired(field); string sName = PropertyName(field); @@ -1088,7 +1189,7 @@ namespace <%=_nameSpace%> ValidationRules.AddRule<<%=_className%>>(<%=sName%>Valid, "<%=sName%>");<% } string sObjectRequired = RequiredRelatedColumn(field); - if(sObjectRequired != null) + if (sObjectRequired != null) { %> ValidationRules.AddRule<<%=_className%>>(<%=sObjectRequired%>Required, "<%=sObjectRequired%>");<% @@ -1106,7 +1207,7 @@ namespace <%=_nameSpace%> }<% foreach(IColumn field in Columns) { - if(CSLAType( field )=="SmartDate") + if (CSLAType( field )=="SmartDate") { string sName = PropertyName(field); string sMember = MemberName(field); @@ -1129,7 +1230,7 @@ namespace <%=_nameSpace%> foreach(IColumn col in Columns) { string sColumn = RequiredRelatedColumn(col); - if(sColumn != null){ // Let the Validation Rules handle required fields + if (sColumn != null){ // Let the Validation Rules handle required fields string sMemberRaw = MemberName(col); string sMemberReq = MemberName(sColumn); %> @@ -1162,7 +1263,7 @@ namespace <%=_nameSpace%> private void vlnAddRequired(IColumn column) { string sName = PropertyName(column); - if(!column.IsNullable) + if (!column.IsNullable) { %> ValidationRules.AddRule( @@ -1184,14 +1285,14 @@ namespace <%=_nameSpace%> //TODO: Who can read/write which fields<% foreach(IColumn field in Columns) { - if(field.DataTypeName != "timestamp"){ + if (field.DataTypeName != "timestamp"){ %> //AuthorizationRules.AllowRead(<%=PropertyName(field)%>, "");<% } } foreach(IColumn field in Columns) { - if(!(field.IsInPrimaryKey || field.IsAutoKey || field.IsComputed)) + if (!(field.IsInPrimaryKey || field.IsAutoKey || field.IsComputed)) { %> //AuthorizationRules.AllowWrite(<%=PropertyName(field)%>, "");<% @@ -1232,16 +1333,16 @@ namespace <%=_nameSpace%> // Loop through Foreign Keys associated with the Primary Key foreach(IForeignKey fk in _workingTable.ForeignKeys) { - if(fk.PrimaryTable == _workingTable) + if (fk.PrimaryTable == _workingTable) { bool isPrimary = true; foreach(IColumn c in fk.PrimaryColumns) { isPrimary &= c.IsInPrimaryKey; } - if(isPrimary) + if (isPrimary) { - if(fk.PrimaryTable == fk.ForeignTable) + if (fk.PrimaryTable == fk.ForeignTable) { sRelatedCounts1 += "\r\n\t\t\t\tusedByCount += " + MemberName(FKClassName1(fk)) + "Count;"; } @@ -1253,7 +1354,7 @@ namespace <%=_nameSpace%> } } sRelatedCounts += sRelatedCounts1; - if(sRelatedCounts != "") + if (sRelatedCounts != "") { %> /// @@ -1280,7 +1381,7 @@ namespace <%=_nameSpace%> } private bool MatchingColumns(IList cols1,IList cols2) { - if(cols1.Count != cols2.Count)return false; + if (cols1.Count != cols2.Count)return false; ArrayList cols=new ArrayList(); foreach(IColumn col in cols1)cols.Add(col.Name); foreach(IColumn col in cols2)cols.Remove(col.Name); @@ -1309,23 +1410,55 @@ namespace <%=_nameSpace%> #region Factory Methods public int CurrentEditLevel { get { return EditLevel; } } + private static int _<%=_className%>Unique = 0; + protected static int <%=_className%>Unique + { get { return ++_<%=_className%>Unique; } } + private int _My<%=_className%>Unique = <%=_className%>Unique; + public int My<%=_className%>Unique + { get { return _My<%=_className%>Unique; } } protected <%=_className%>() {/* require use of factory methods */ - _AllList.Add(this); + AddToCache(this); } public void Dispose() { - _AllList.Remove(this); - _AllByPrimaryKey.Remove(<%=pKeys%>);<% + RemoveFromDictionaries(); + } + private void RemoveFromDictionaries() + { + RemoveFromCache(this); + if (_CacheByPrimaryKey.ContainsKey(<%=pKeys%>)) + { + List<<%=_className%>> list<%=_className%> = _CacheByPrimaryKey[<%=pKeys%>]; // Get the list of items + while (list<%=_className%>.Contains(this)) list<%=_className%>.Remove(this); // Remove the item from the list + if (list<%=_className%>.Count == 0) //If there are no items left in the list + _CacheByPrimaryKey.Remove(<%=pKeys%>); // remove the list + }<% + ArrayList uniqueIndexes=UniqueIndexes(_workingTable); IIndex makeIndex=null; + if(uniqueIndexes.Count > 0) + { +%> + string myKey;<% + } foreach(IIndex ind in uniqueIndexes) { string sBy = FormatColumns("{name}",ind.Columns,"_",""); string sKey = FormatColumns("{prop}.ToString()",ind.Columns," + \"_\" + ",""); - if(MatchingColumns(ind.Columns,makeList))makeIndex=ind; + if (MatchingColumns(ind.Columns,makeList))makeIndex=ind; %> - _AllBy<%=sBy%>.Remove(<%=sKey%>);<% + myKey = null; + foreach (string key in _CacheBy<%=sBy%>.Keys) + if (_CacheBy<%=sBy%>[key].Contains(this)) + myKey = key; + if (myKey != null) + { + List<<%=_className%>> list<%=_className%> = _CacheBy<%=sBy%>[myKey]; // Get the list of items + list<%=_className%>.Remove(this); // Remove the item from the list + if (list<%=_className%>.Count == 0) //If there are no items left in the list + _CacheBy<%=sBy%>.Remove(myKey); // remove the list + }<% } string sMakeListParamTypes = ""; string sMakeListParams = ""; @@ -1347,38 +1480,41 @@ namespace <%=_nameSpace%> } }<% // if makelist != reqlist create a new for reqlist - if(!SameList(makeList,reqList) && reqList.Count > 0) + if (!SameList(makeList,reqList) && reqList.Count > 0) { BuildLists(reqList,ref sMakeListParamTypes, ref sMakeListParams, ref sSetTmp, ref sParentCheck); - BuildNew(sMakeListParamTypes,sMakeListParams,sSetTmp,sParentCheck); + BuildNew(sMakeListParamTypes,sMakeListParams,sSetTmp,sParentCheck); + if(SameList(reqList,makeList4)) + BuildMake(sMakeListParamTypes,sMakeListParams,sSetTmp,sParentCheck + Debug("20070427.4"),makeIndex); } BuildLists(makeList,ref sMakeListParamTypes, ref sMakeListParams, ref sSetTmp, ref sParentCheck); BuildNew(sMakeListParamTypes,sMakeListParams,sSetTmp,sParentCheck ); BuildMake(sMakeListParamTypes,sMakeListParams,sSetTmp,sParentCheck + Debug("20070427.3"),makeIndex); - if(!SameList(makeList,makeList4) && !SameList(reqList,makeList4) && makeList4.Count > 0) + if (!SameList(makeList,makeList4) && !SameList(reqList,makeList4) && makeList4.Count > 0) { BuildLists(makeList4,ref sMakeListParamTypes, ref sMakeListParams, ref sSetTmp, ref sParentCheck); BuildNew(sMakeListParamTypes,sMakeListParams,sSetTmp,sParentCheck); BuildMake(sMakeListParamTypes,sMakeListParams,sSetTmp,sParentCheck + Debug("20070427.4"),makeIndex); } - if(makeList3.Count > 0) + if (makeList3.Count > 0) { %> public static <%=_className%> Make<%=_className%>(<%=FormatColumns("{rtype} {local}",makeList2,", ","")%>) {<%=DebugLine("20070427.1")%> <%=_className%> tmp = <%=_className%>.New(<%=FormatColumns("{local}",makeList,", ","")%>); <%=FormatColumns(dicCheck,makeList3,"\r\n","\t\t\t")%> - tmp = tmp.Save(); - return tmp; + <%=_className%> tmp2 = tmp.Save(); + tmp.Dispose(); + return tmp2; }<% } string sExtra1= ""; string sExtra2= ""; - if(FKParent(_workingTable)){ + if (FKParent(_workingTable)){ sExtra1=", " + _className + " " + ParentName(fkParent).ToLower(); sExtra2=", " + ParentName(fkParent).ToLower(); } - if(OneToOne(_workingTable) && !SameList(makeList,_workingTable.PrimaryKeys) && !SameList(reqList,_workingTable.PrimaryKeys) && !SameList(makeList4,_workingTable.PrimaryKeys)) + if (OneToOne(_workingTable) && !SameList(makeList,_workingTable.PrimaryKeys) && !SameList(reqList,_workingTable.PrimaryKeys) && !SameList(makeList4,_workingTable.PrimaryKeys)) { BuildLists(_workingTable.PrimaryKeys,ref sMakeListParamTypes, ref sMakeListParams, ref sSetTmp, ref sParentCheck); sSetTmp += "\r\n\t\t\ttmp.MarkClean();"; @@ -1392,13 +1528,17 @@ namespace <%=_nameSpace%> throw new System.Security.SecurityException("User not authorized to view a <%=_className%>"); try { - <%=_className%> tmp = GetExistingByPrimaryKey(<%=sKeys%>); + <%=_className%> tmp = GetCachedByPrimaryKey(<%=sKeys%>); if (tmp == null) { tmp = DataPortal.Fetch<<%=_className%>>(new PKCriteria(<%=sKeys%>)); - _AllList.Add(tmp); + AddToCache(tmp); + } + if (tmp.ErrorMessage == "No Record Found") + { + tmp.Dispose(); // Clean-up <%=_className%> + tmp = null; } - if (tmp.ErrorMessage == "No Record Found") tmp = null; return tmp; } catch (Exception ex) @@ -1407,7 +1547,7 @@ namespace <%=_nameSpace%> } }<% //IForeignKey fkParent = FKParentFK(_workingTable); - if(fkParent != null && _doOldParent) + if (fkParent != null && _doOldParent) { string parKeys = FormatColumns("{member}",fkParent.ForeignColumns,", "); %> @@ -1417,13 +1557,17 @@ namespace <%=_nameSpace%> throw new System.Security.SecurityException("User not authorized to view a <%=_className%>"); try { - <%=_className%> tmp = GetExistingByPrimaryKey(<%=parKeys%>); + <%=_className%> tmp = GetCachedByPrimaryKey(<%=parKeys%>); if (tmp == null) { tmp = DataPortal.Fetch<<%=_className%>>(new <%=sParent%>Criteria(<%=parKeys%>)); - _AllList.Add(tmp); + AddToCache(tmp); + } + if (tmp.ErrorMessage == "No Record Found") + { + tmp.Dispose(); // Clean-up <%=_className%> + tmp = null; } - if (tmp.ErrorMessage == "No Record Found") tmp = null; return tmp; } catch (Exception ex) @@ -1439,19 +1583,23 @@ namespace <%=_nameSpace%> string sKeyType = FormatColumns("{ctype} {local}",ind.Columns,", ",""); string sKey = FormatColumns("{local}",ind.Columns,", ",""); %> - private static <%=_className%> GetBy<%=sBy%>(<%=sKeyType%>) + public static <%=_className%> GetBy<%=sBy%>(<%=sKeyType%>) { if (!CanGetObject()) throw new System.Security.SecurityException("User not authorized to view a <%=_className%>"); try { - <%=_className%> tmp = GetExistingBy<%=sBy%>(<%=sKey%>); + <%=_className%> tmp = GetCachedBy<%=sBy%>(<%=sKey%>); if (tmp == null) { - tmp=DataPortal.Fetch<<%=_className%>>(new <%=sBy%>Criteria(<%=sKey%>)); - _AllList.Add(tmp); + tmp = DataPortal.Fetch<<%=_className%>>(new <%=sBy%>Criteria(<%=sKey%>)); + AddToCache(tmp); + } + if (tmp.ErrorMessage == "No Record Found") + { + tmp.Dispose(); // Clean-up <%=_className%> + tmp = null; } - if (tmp.ErrorMessage == "No Record Found") tmp = null; return tmp; } catch (Exception ex) @@ -1470,7 +1618,7 @@ namespace <%=_nameSpace%> { ReadData(dr); }<% - if(FKParent(_workingTable)){ + if (FKParent(_workingTable)){ %> private <%=_className%>(SafeDataReader dr<%=sExtra1%>) { @@ -1509,7 +1657,8 @@ namespace <%=_nameSpace%> { BuildRefreshList(); <%=_className%> <%=LocalName(_className)%> = base.Save(); - _AllList.Add(<%=LocalName(_className)%>);//Refresh the item in AllList + RemoveFromDictionaries(); // if save is successful remove the previous Folder from the cache + AddToCache(<%=LocalName(_className)%>);//Refresh the item in AllList ProcessRefreshList(); return <%=LocalName(_className)%>; } @@ -1535,7 +1684,7 @@ namespace <%=_nameSpace%> %> public static <%=_className%> Make<%=_className%>(<%=sMakeListParamTypes%>) {<%=DebugLine("20070427.2")%><% - if(makeIndex != null) + if (makeIndex != null) { %> <%=_className%> tmp = null; @@ -1550,7 +1699,11 @@ namespace <%=_nameSpace%> } %> if (tmp.IsSavable) - tmp = tmp.Save(); + { + <%=_className%> tmp2 = tmp; + tmp = tmp2.Save(); + tmp2.Dispose(); + } else { Csla.Validation.BrokenRulesCollection brc = tmp.ValidationRules.GetBrokenRules(); @@ -1577,16 +1730,16 @@ namespace <%=_nameSpace%> sClass + "Info.Refresh(tmp);"; foreach(IForeignKey fk in _workingTable.ForeignKeys) // 20070220 { - if(_workingTable != fk.PrimaryTable && IsPrimaryKey1(fk) && !IsPrimaryKey(fk)) + if (_workingTable != fk.PrimaryTable && IsPrimaryKey1(fk) && !IsPrimaryKey(fk)) { - sProcess += string.Format("\r\n\t\t\t\tif(tmp._My{1} != null) {0}Info.Refresh(tmp._My{1});",ClassName(fk.PrimaryTable.Name),ClassName(fk.PrimaryTable.Name) + GetNewAlias(fk,fk)); + sProcess += string.Format("\r\n\t\t\t\tif (tmp._My{1} != null) {0}Info.Refresh(tmp._My{1});",ClassName(fk.PrimaryTable.Name),ClassName(fk.PrimaryTable.Name) + GetNewAlias(fk,fk)); } } sProcess += "\r\n\t\t\t}"; Hashtable dicAlias = new Hashtable(); foreach(IForeignKey fk in _workingTable.ForeignKeys) // 20070220 { - if(fk.PrimaryTable == fk.ForeignTable) // Parent Child + if (fk.PrimaryTable == fk.ForeignTable) // Parent Child { sCheck += "\r\n\t\t\tif (_" + ChildName(fk) + sClasses + " != null && _" + ChildName(fk) + sClasses + ".IsDirty)\r\n\t\t\t{\r\n\t\t\t\tforeach (" + sClass + " tmp in _" + ChildName(fk) + sClasses + ")\r\n\t\t\t\t{\r\n\t\t\t\t\ttmp.AddToRefreshList(" + @@ -1594,7 +1747,7 @@ namespace <%=_nameSpace%> } else { - if(!IsPrimaryKey(fk) && _workingTable == fk.PrimaryTable){ + if (!IsPrimaryKey(fk) && _workingTable == fk.PrimaryTable){ //string sAlias = GetAlias(dicAlias,fk.ForeignTable); string sAlias = GetAlias(fk); string sItem = ClassName(fk.ForeignTable); @@ -1606,7 +1759,7 @@ namespace <%=_nameSpace%> sRefreshRelated1 += ", _Refresh" + sFItems; sRefreshDeclare += ", List<" + sFItem + "> refresh" + sFItems; sCheck += "\r\n\t\t\tif (" + MemberName(sFItems) + " != null && " + MemberName(sFItems) + ".IsDirty)\r\n\t\t\t{\r\n\t\t\t\tforeach (" + sFItem + - " tmp in " + MemberName(sFItems) + ")\r\n\t\t\t\t{\r\n\t\t\t\t\tif(tmp.IsDirty)refresh" + sFItems + + " tmp in " + MemberName(sFItems) + ")\r\n\t\t\t\t{\r\n\t\t\t\t\tif (tmp.IsDirty) refresh" + sFItems + ".Add(tmp);\r\n\t\t\t\t}\r\n\t\t\t}"; sProcess += "\r\n\t\t\tforeach (" + sFItem + " tmp in _Refresh" + sFItems + ")\r\n\t\t\t{\r\n\t\t\t\t" + sItem + "Info.Refresh(" + (ForeignPrimary(fk)?"this, ":"") + "tmp);\r\n\t\t\t}"; @@ -1667,7 +1820,7 @@ namespace <%=_nameSpace%> private void vlnReadData(IColumns cols,bool bEditable) { IList cols2=cols; - if(!bEditable)cols2=NotTimestamp(cols); + if (!bEditable)cols2=NotTimestamp(cols); %> private void ReadData(SafeDataReader dr) { @@ -1678,8 +1831,8 @@ namespace <%=_nameSpace%> //Hashtable dicAlias = new Hashtable(); foreach(IForeignKey FK in _workingTable.ForeignKeys) { - //if(FK.PrimaryTable == _workingTable && !IsPrimaryKey(FK)) - if(FK.PrimaryTable == _workingTable) // 20071023 + //if (FK.PrimaryTable == _workingTable && !IsPrimaryKey(FK)) + if (FK.PrimaryTable == _workingTable) // 20071023 { string sAlias = GetAlias(FK); string sClass = FKClassName(FK); @@ -1688,7 +1841,7 @@ namespace <%=_nameSpace%> <%=MemberName(sClass)+ sAlias%>Count = dr.GetInt32("<%=sField + sAlias%>Count");<% } } - if(bEditable){ + if (bEditable){ %> MarkOld();<% } @@ -1710,7 +1863,7 @@ namespace <%=_nameSpace%> // Parent Criteria IForeignKey fkParent = FKParentFK(_workingTable); string sParent = ParentName(fkParent); - if(fkParent != null && _doOldParent) + if (fkParent != null && _doOldParent) { string parKeys = FormatColumns("{member}",fkParent.ForeignColumns,", "); string parValues=FormatColumns("\t\t\t\t{member} = {local};",fkParent.ForeignColumns,"\r\n"); @@ -1759,7 +1912,7 @@ namespace <%=_nameSpace%> vlnReadData(Columns,true); vlnDataPortalFetch("PK",_workingTable.PrimaryKeys,_className,true); // IForeignKey fkParent = FKParentFK(_workingTable); - if(fkParent != null && _doOldParent) + if (fkParent != null && _doOldParent) { // string sParent = ParentName(fkParent); vlnDataPortalFetch(sParent,fkParent.ForeignColumns,sParent + _className,false); @@ -1772,9 +1925,9 @@ namespace <%=_nameSpace%> string sUpdateMyList=""; foreach(IForeignKey fk in _workingTable.ForeignKeys) // 20070220 { - if(_workingTable != fk.PrimaryTable && IsPrimaryKey1(fk) && !IsPrimaryKey(fk)) + if (_workingTable != fk.PrimaryTable && IsPrimaryKey1(fk) && !IsPrimaryKey(fk)) { - sUpdateMyList += string.Format("\r\n\t\t\t\tif(_My{0} != null) _My{0}.Update();",ClassName(fk.PrimaryTable.Name) + GetNewAlias(fk,fk)); + sUpdateMyList += string.Format("\r\n\t\t\t\tif (_My{0} != null) _My{0}.Update();",ClassName(fk.PrimaryTable.Name) + GetNewAlias(fk,fk)); } } // DataPortal_Insert @@ -1818,7 +1971,7 @@ namespace <%=_nameSpace%> // Input All Fields - Except Calculated Columns<% foreach(IColumn column in Columns) { - if((!column.IsAutoKey) && (!column.IsComputed)) + if ((!column.IsAutoKey) && (!column.IsComputed)) { output.write(FormatColumn("\r\n\t\t\t\t\t{ifLogicP}cm.Parameters.AddWithValue(\"{@}\", {?dbprefix}{Parent}{?dbsuffix});",column));// 20070316 } @@ -1827,7 +1980,7 @@ namespace <%=_nameSpace%> // Output Calculated Columns<% foreach(IColumn column in Columns) { - if((column.IsAutoKey) || (column.IsComputed)) + if ((column.IsAutoKey) || (column.IsComputed)) { output.write(FormatColumn("\r\n\t\t\t\t\tSqlParameter param{member} = new SqlParameter(\"{@new}\", {sqltype});",column)); output.write(FormatColumn("\r\n\t\t\t\t\tparam{member}.Direction = ParameterDirection.Output;",column)); @@ -1840,7 +1993,7 @@ namespace <%=_nameSpace%> // Save all values being returned from the Procedure<% foreach(IColumn column in Columns) { - if((column.IsAutoKey) || (column.IsComputed)) + if ((column.IsAutoKey) || (column.IsComputed)) { output.write(FormatColumn("\r\n\t\t\t\t\t{member} = ({ctype})cm.Parameters[\"{@new}\"].Value;",column)); } @@ -1851,7 +2004,7 @@ namespace <%=_nameSpace%> // update child objects<% foreach(IColumn field in Columns) { - if( field.IsInForeignKey && field.IsInPrimaryKey) + if (field.IsInForeignKey && field.IsInPrimaryKey) { //A column that's in a fk and in the pk represents a fk relationship //from another table, a one-to-many relationship. (This might be @@ -1859,9 +2012,9 @@ namespace <%=_nameSpace%> //... and then we have to add collections for the foreign tables. foreach( IForeignKey fk in field.ForeignKeys ) { - if(fk.PrimaryTable == _workingTable){ + if (fk.PrimaryTable == _workingTable){ string sObjName; - if(!IsPrimaryKey(fk)){ + if (!IsPrimaryKey(fk)){ sObjName = FKClassesName( fk ) + GetAlias(fk); %> if (<%=MemberName(sObjName)%> != null) <%=MemberName(sObjName)%>.Update(this);<% @@ -1893,12 +2046,12 @@ namespace <%=_nameSpace%> string sepi=""; foreach(IColumn column in Columns) { - if((!column.IsComputed)) + if ((!column.IsComputed)) { - if(!column.IsAutoKey){ + if (!column.IsAutoKey){ sValuesI+=FormatColumn("\r\n\t\t\t\t\t{ifLogicL}cm.Parameters.AddWithValue(\"{@}\", {parent}{?dbtype});",column); } - if(IsParentCol(column)){ + if (IsParentCol(column)){ sKeysTypesI+=sepi + _className + " my" + ParentName(column.ForeignKeys[0]); sKeysI+=sepi + "my" + ParentName(column.ForeignKeys[0]); } @@ -1926,7 +2079,7 @@ namespace <%=_nameSpace%> // Output Calculated Columns<% foreach(IColumn column in Columns) { - if((column.IsAutoKey) || (column.IsComputed)) + if ((column.IsAutoKey) || (column.IsComputed)) { output.write(FormatColumn("\r\n\t\t\t\t\tSqlParameter param{member} = new SqlParameter(\"{@new}\", {sqltype});",column)); output.write(FormatColumn("\r\n\t\t\t\t\tparam{member}.Direction = ParameterDirection.Output;",column)); @@ -1940,13 +2093,13 @@ namespace <%=_nameSpace%> IColumn tsCol=null; foreach(IColumn column in Columns) { - if((column.IsAutoKey) || (column.IsComputed)) + if ((column.IsAutoKey) || (column.IsComputed)) { - if(column.DataTypeName=="timestamp")tsCol=column; + if (column.DataTypeName=="timestamp")tsCol=column; else output.write(FormatColumn("\r\n\t\t\t\t\t{local} = ({ctype})cm.Parameters[\"{@new}\"].Value;",column)); } } - if(tsCol != null) + if (tsCol != null) output.write(FormatColumn("\r\n\t\t\t\t\treturn ({ctype})cm.Parameters[\"{@new}\"].Value;",tsCol)); else output.write("\r\n\t\t\t// No Timestamp value to return"); @@ -2007,7 +2160,7 @@ namespace <%=_nameSpace%> // Output Calculated Columns<% foreach(IColumn column in Columns) { - if(column.IsComputed) + if (column.IsComputed) { output.write(FormatColumn("\r\n\t\t\t\t\t\tSqlParameter param{member} = new SqlParameter(\"{@new}\", {sqltype});",column)); output.write(FormatColumn("\r\n\t\t\t\t\t\tparam{member}.Direction = ParameterDirection.Output;",column)); @@ -2020,7 +2173,7 @@ namespace <%=_nameSpace%> // Save all values being returned from the Procedure<% foreach(IColumn column in Columns) { - if(column.IsComputed) + if (column.IsComputed) { output.write(FormatColumn("\r\n\t\t\t\t\t\t{member} = ({ctype})cm.Parameters[\"{@new}\"].Value;",column)); } @@ -2032,7 +2185,7 @@ namespace <%=_nameSpace%> // use the open connection to update child objects<% foreach(IColumn field in Columns) { - if( field.IsInForeignKey && field.IsInPrimaryKey) + if (field.IsInForeignKey && field.IsInPrimaryKey) { //A column that's in a fk and in the pk represents a fk relationship //from another table, a one-to-many relationship. (This might be @@ -2040,9 +2193,9 @@ namespace <%=_nameSpace%> //... and then we have to add collections for the foreign tables. foreach( IForeignKey fk in field.ForeignKeys ) { - if(fk.PrimaryTable == _workingTable){ + if (fk.PrimaryTable == _workingTable){ string sObjName; - if(!IsPrimaryKey(fk)){ + if (!IsPrimaryKey(fk)){ sObjName = FKClassesName( fk ) + GetAlias( fk ); %> if (<%=MemberName(sObjName)%> != null) <%=MemberName(sObjName)%>.Update(this);<% @@ -2073,12 +2226,12 @@ namespace <%=_nameSpace%> string sepu=""; foreach(IColumn column in Columns) { - //if((!column.IsComputed)) + //if ((!column.IsComputed)) //{ // Commentted out the following two lines for Permissions - // if(!column.IsAutoKey) + // if (!column.IsAutoKey) sValuesU+=FormatColumn("\r\n\t\t\t\t\t{ifLogicL}cm.Parameters.AddWithValue(\"{@}\", {parent}{?dbtype});",column); - if(IsParentCol(column)){ + if (IsParentCol(column)){ sKeysTypesU+=sepi + _className + " my" + sParent; sKeysU+=sepi + "my" + sParent; } @@ -2090,7 +2243,7 @@ namespace <%=_nameSpace%> sepu=", "; //} } - if(OneToOne(_workingTable)) // 20070314 + if (OneToOne(_workingTable)) // 20070314 { IForeignKey fk = _workingTable.PrimaryKeys[0].ForeignKeys[0]; string sPrimaryTable = ClassName(fk.PrimaryTable); @@ -2103,15 +2256,15 @@ namespace <%=_nameSpace%> sepi=""; foreach(IColumn column in fk.ForeignTable.Columns) { - if(column.DataTypeName=="timestamp") + if (column.DataTypeName=="timestamp") sTimestamp=FormatColumn("{member} = ",column); - if(!IsIn(column,fk.ForeignColumns)) + if (!IsIn(column,fk.ForeignColumns)) { string sRef = ParentRef(column); - if(sRef==null)sRef=FormatColumn("{?ref}{?dbprefix}{!propmember}{?dbsuff}",column); + if (sRef==null)sRef=FormatColumn("{?ref}{?dbprefix}{!propmember}{?dbsuff}",column); sUpdate+=sepu+sRef; sepu=", "; - if(!column.IsComputed)// && !column.IsAutoKey + if (!column.IsComputed)// && !column.IsAutoKey { sInsert+=sepi+sRef; sepi=", "; @@ -2134,12 +2287,12 @@ namespace <%=_nameSpace%> if (!this.IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - <%=sTimestamp%><%=_className%>.Add(cn, <%=sInsert%>); - else - <%=sTimestamp%><%=_className%>.Update(cn, <%=sUpdate%>); - MarkOld(); + SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; + if (IsNew) + <%=sTimestamp%><%=_className%>.Add(cn, <%=sInsert%>); + else + <%=sTimestamp%><%=_className%>.Update(cn, <%=sUpdate%>); + MarkOld(); } }<% } @@ -2155,10 +2308,10 @@ namespace <%=_nameSpace%> sepi=""; foreach(IColumn column in Columns) { - if(column.DataTypeName=="timestamp") + if (column.DataTypeName=="timestamp") sTimestamp=FormatColumn("{member} = ",column); string sRef = FormatColumn("{?ref}{?dbprefix}{!member}{?dbsuff}",column); - if(!column.IsComputed)// && !column.IsAutoKey + if (!column.IsComputed)// && !column.IsAutoKey { sInsert+=sepi+sRef; sepi=", "; @@ -2171,9 +2324,9 @@ namespace <%=_nameSpace%> string sepdd = ""; foreach(IColumn column in _workingTable.PrimaryKeys) { - //if(IsIn(column,fk.ForeignColumns)) + //if (IsIn(column,fk.ForeignColumns)) //sDelete+=sepdd+FormatColumn("{!localcolumn}",column); - //sDelete+=sepdd+FormatColumn("/*1*/{rmember}",RelatedColumn(column,fk)); + //sDelete+=sepdd+FormatColumn("{rmember}",RelatedColumn(column,fk)); //else sDelete+=sepdd+FormatColumn("{member}",column); sepdd=", "; @@ -2191,7 +2344,7 @@ namespace <%=_nameSpace%> <%=sTimestamp%><%=_className%>.Update(cn, <%=sUpdate%>); MarkOld(); }<% - if(vlnChildObjects(Columns)) + if (vlnChildObjects(Columns)) { %> } @@ -2223,7 +2376,7 @@ namespace <%=_nameSpace%> // Output Calculated Columns<% foreach(IColumn column in Columns) { - if(column.IsComputed) + if (column.IsComputed) { output.write(FormatColumn("\r\n\t\t\t\t\tSqlParameter param{member} = new SqlParameter(\"{@new}\", {sqltype});",column)); output.write(FormatColumn("\r\n\t\t\t\t\tparam{member}.Direction = ParameterDirection.Output;",column)); @@ -2237,13 +2390,13 @@ namespace <%=_nameSpace%> tsCol=null; foreach(IColumn column in Columns) { - if(column.IsComputed) + if (column.IsComputed) { - if(column.DataTypeName=="timestamp")tsCol=column; + if (column.DataTypeName=="timestamp")tsCol=column; else output.write(FormatColumn("\r\n\t\t\t\t\t{local} = ({ctype})cm.Parameters[\"{@new}\"].Value;",column)); } } - if(tsCol != null) + if (tsCol != null) output.write(FormatColumn("\r\n\t\t\t\t\treturn ({ctype})cm.Parameters[\"{@new}\"].Value;",tsCol)); else output.write("\r\n\t\t\t\t// No Timestamp value to return"); @@ -2330,7 +2483,7 @@ private bool vlnChildObjects(IColumns Columns) bool retval = false; foreach(IColumn field in Columns) { - if( field.IsInForeignKey && field.IsInPrimaryKey) + if (field.IsInForeignKey && field.IsInPrimaryKey) { //A column that's in a fk and in the pk represents a fk relationship //from another table, a one-to-many relationship. (This might be @@ -2338,12 +2491,12 @@ private bool vlnChildObjects(IColumns Columns) //... and then we have to add collections for the foreign tables. foreach( IForeignKey fk in field.ForeignKeys ) { - if(fk.PrimaryTable == _workingTable) + if (fk.PrimaryTable == _workingTable) { string sObjName; - if(!IsPrimaryKey(fk)){ // Items that use this table's Primary Key + if (!IsPrimaryKey(fk)){ // Items that use this table's Primary Key sObjName = FKClassesName( fk ) + GetAlias( fk ); - if(fk.PrimaryTable == fk.ForeignTable)retval = true; + if (fk.PrimaryTable == fk.ForeignTable)retval = true; %> if (<%=MemberName(sObjName)%> != null) <%=MemberName(sObjName)%>.Update(this);<% } @@ -2363,7 +2516,7 @@ private void vlnBrokenRuleObjects(IColumns Columns) { foreach(IColumn field in Columns) { - if( field.IsInForeignKey && field.IsInPrimaryKey) + if (field.IsInForeignKey && field.IsInPrimaryKey) { //A column that's in a fk and in the pk represents a fk relationship //from another table, a one-to-many relationship. (This might be @@ -2371,20 +2524,20 @@ private void vlnBrokenRuleObjects(IColumns Columns) //... and then we have to add collections for the foreign tables. foreach( IForeignKey fk in field.ForeignKeys ) { - if(fk.PrimaryTable == _workingTable) + if (fk.PrimaryTable == _workingTable) { string sObjName; - if(!IsPrimaryKey(fk)) + if (!IsPrimaryKey(fk)) { // Items that use this table's Primary Key sObjName = FKClassesName( fk ) + GetAlias(fk); %> - if (<%=MemberName(sObjName)%> != null && (hasBrokenRules = <%=MemberName(sObjName)%>.HasBrokenRules) != null) return hasBrokenRules;<% + if (<%=MemberName(sObjName)%> != null && (hasBrokenRules = <%=MemberName(sObjName)%>.HasBrokenRules) != null) return hasBrokenRules;<% } else { string sMemberName = MemberName("My" + ClassName( fk.ForeignTable )+ GetNewAlias(fk,fk)); %> - if (<%=sMemberName%> != null && (hasBrokenRules = <%=sMemberName%>.HasBrokenRules) != null) return hasBrokenRules;<% + if (<%=sMemberName%> != null && (hasBrokenRules = <%=sMemberName%>.HasBrokenRules) != null) return hasBrokenRules;<% } } } @@ -2393,11 +2546,11 @@ private void vlnBrokenRuleObjects(IColumns Columns) { foreach( IForeignKey fk in field.ForeignKeys ) { - if(fk.PrimaryTable != _workingTable && IsPrimaryKey1(fk) && !IsPrimaryKey(fk)) + if (fk.PrimaryTable != _workingTable && IsPrimaryKey1(fk) && !IsPrimaryKey(fk)) { string sMemberName = MemberName("My" + ClassName(fk.PrimaryTable.Name) + GetNewAlias(fk,fk)); %> - if (<%=sMemberName%> != null && (hasBrokenRules = <%=sMemberName%>.HasBrokenRules) != null) return hasBrokenRules;<% + if (<%=sMemberName%> != null && (hasBrokenRules = <%=sMemberName%>.HasBrokenRules) != null) return hasBrokenRules;<% } } } @@ -2409,15 +2562,15 @@ private void vlnBrokenRuleObjects(IForeignKey myFk) // Exclude one to one & ForeignKey Relationship foreach(IColumn field in Columns) { - if( !field.IsInForeignKey || !field.IsInPrimaryKey) + if (!field.IsInForeignKey || !field.IsInPrimaryKey) { foreach( IForeignKey fk in field.ForeignKeys ) { - if(fk.PrimaryTable != _workingTable && IsPrimaryKey1(fk) && !IsPrimaryKey(fk)) + if (fk.PrimaryTable != _workingTable && IsPrimaryKey1(fk) && !IsPrimaryKey(fk)) { string sMemberName = MemberName("My" + ClassName(fk.PrimaryTable.Name) + GetNewAlias(fk,fk)); %> - if (<%=sMemberName%> != null && (hasBrokenRules = <%=sMemberName%>.HasBrokenRules) != null) return hasBrokenRules;<% + if (<%=sMemberName%> != null && (hasBrokenRules = <%=sMemberName%>.HasBrokenRules) != null) return hasBrokenRules;<% } } } @@ -2429,15 +2582,15 @@ private void vlnTest(IForeignKey myFk) // 20070517 // Exclude one to one & ForeignKey Relationship foreach(IColumn field in Columns) { - if(!field.IsInForeignKey || !field.IsInPrimaryKey) + if (!field.IsInForeignKey || !field.IsInPrimaryKey) { foreach( IForeignKey fk in field.ForeignKeys ) { - if(fk.PrimaryTable != _workingTable && IsPrimaryKey1(fk) && !IsPrimaryKey(fk)) + if (fk.PrimaryTable != _workingTable && IsPrimaryKey1(fk) && !IsPrimaryKey(fk)) { string sMemberName = MemberName("My" + ClassName(fk.PrimaryTable.Name) + GetNewAlias(fk,fk)); %> - if (<%=sMemberName%> != null && (hasBrokenRules = <%=sMemberName%>.HasBrokenRules) != null) return hasBrokenRules;<% + if (<%=sMemberName%> != null && (hasBrokenRules = <%=sMemberName%>.HasBrokenRules) != null) return hasBrokenRules;<% } } } @@ -2445,11 +2598,11 @@ private void vlnTest(IForeignKey myFk) // 20070517 } private string RequiredRelatedColumn(IColumn field) { - if(!field.IsInPrimaryKey && !field.IsNullable) + if (!field.IsInPrimaryKey && !field.IsNullable) { foreach( IForeignKey fk in field.ForeignKeys ) { - if(fk.PrimaryTable != _workingTable && IsPrimaryKey1(fk) && !IsPrimaryKey(fk)) + if (fk.PrimaryTable != _workingTable && IsPrimaryKey1(fk) && !IsPrimaryKey(fk)) { return "My" + ClassName(fk.PrimaryTable.Name) + GetNewAlias(fk,fk); } @@ -2489,33 +2642,33 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get //dicRead1 = new Hashtable(); //dicRead1["timestamp"]="\r\n\t\t\t\t\t\tdr.GetBytes(\"{name}\", 0, {member}, 0, 8);";// TODO: Need to handle TimeStamp //output.write(FormatColumns(dicRead1,Columns,"")); -// if(_workingTable != fk.ForeignTable) +// if (_workingTable != fk.ForeignTable) // FKSelect(fk,tbl); // TODO: Fix This See Below // foreach(IColumn field in Columns) // { -// if( field.IsInForeignKey && field.IsInPrimaryKey) +// if (field.IsInForeignKey && field.IsInPrimaryKey) // { //A column that's in a fk and in the pk represents a fk relationship //from another table, a one-to-many relationship. (This might be //a bad assumption for a table with a composite primary key.) //... and then we have to add collections for the foreign tables. // foreach( IForeignKey fk in field.ForeignKeys ) - if(getChildren) + if (getChildren) { Hashtable dicAlias = new Hashtable(); foreach(IForeignKey fk in _workingTable.ForeignKeys) { - if(fk.PrimaryTable == _workingTable){ + if (fk.PrimaryTable == _workingTable){ //string sAlias = GetAlias(dicAlias,fk.ForeignTable); string sAlias = GetAlias(fk); string sObjName=""; - if(!IsPrimaryKey(fk)){ + if (!IsPrimaryKey(fk)){ sObjName = FKClassesName( fk ) + GetAlias(fk); string sExtra = FKAndString(_className, fk, ", this" ); // else // sObjName = ClassName( fk.ForeignTable ); - if(fk.PrimaryTable != fk.ForeignTable){ + if (fk.PrimaryTable != fk.ForeignTable){ %> // load child objects dr.NextResult(); @@ -2620,7 +2773,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get #region extension <%=_className%>Extension <%=MemberName(_className)%>Extension = new <%=_className%>Extension(); [Serializable()] - partial class <%=_className%>Extension : extensionBase {} + partial class <%=_className%>Extension : extensionBase { } [Serializable()] class extensionBase { @@ -2646,7 +2799,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get foreach(IColumn column in HasDefaults(columns)) { string sConvert ="{default}"; - if(FormatColumn("{rtype}",column).StartsWith("bool"))sConvert="Convert.ToBoolean({default})"; + if (FormatColumn("{rtype}",column).StartsWith("bool"))sConvert="Convert.ToBoolean({default})"; %> public virtual <%=FormatColumn("{rtype} Default{prop}",column)%> { @@ -2771,17 +2924,17 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get ArrayList fkCols = new ArrayList(); //output.write("\r\n// FK.P " + fk.PrimaryTable.Name + " FK.F " +fk.ForeignTable.Name); bool bManyToMany = false; -// if(fk.ForeignTable != fk.PrimaryTable) +// if (fk.ForeignTable != fk.PrimaryTable) // { // foreach(IForeignKey pk in fk.ForeignTable.ForeignKeys) // { // //output.write("\r\n// PK.P " + pk.PrimaryTable.Name + " PK.F " +pk.ForeignTable.Name); -// if(pk.ForeignTable == fk.ForeignTable && pk.PrimaryTable != fk.PrimaryTable && pk.PrimaryTable != pk.ForeignTable && ForeignRequired(pk)) +// if (pk.ForeignTable == fk.ForeignTable && pk.PrimaryTable != fk.PrimaryTable && pk.PrimaryTable != pk.ForeignTable && ForeignRequired(pk)) // { // foreach(IColumn col in pk.ForeignColumns){ // //output.write("\r\n// col " + col.Name + " IsInPrimaryKey " + col.IsInPrimaryKey.ToString()); -// //if(col.IsInPrimaryKey) -// if(!col.IsNullable){ +// //if (col.IsInPrimaryKey) +// if (!col.IsNullable){ // fkCols.Add(col); // } // } @@ -2790,21 +2943,21 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get // } foreach(IForeignKey pk in fk.ForeignTable.ForeignKeys) { - if(!bManyToMany && ManyToMany(_workingTable,fk,pk)) + if (!bManyToMany && ManyToMany(_workingTable,fk,pk)) { bManyToMany = true; foreach(IColumn col in pk.ForeignColumns) - if(!col.IsNullable) fkCols.Add(col); + if (!col.IsNullable) fkCols.Add(col); } } // fkCols = new ArrayList(); - if(fkCols.Count == 0){ + if (fkCols.Count == 0){ // bManyToMany = false; %> // One To Many<% foreach(IColumn col in fk.ForeignTable.PrimaryKeys) { - if(!IsIn(col,fk.ForeignColumns)) + if (!IsIn(col,fk.ForeignColumns)) fkCols.Add(col); } } @@ -2832,12 +2985,12 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get bool bParentRef=false; foreach(IColumn column in fk.ForeignTable.Columns) { - if(IsRequired(column) && !column.IsComputed && !column.IsAutoKey) + if (IsRequired(column) && !column.IsComputed && !column.IsAutoKey) { // 20070220 // sKeysTypes+=sep+FormatColumn("{ctype} {local}",column); // sKeys+=sep+FormatColumn("{local}",column); - if(!IsIn(column,fk.ForeignColumns)) + if (!IsIn(column,fk.ForeignColumns)) { sKeysTypes+=sep2+FormatColumn("{!type} {!local}",column); sKeys+=sep2+FormatColumn("{!local}",column); @@ -2848,7 +3001,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get sep2=", "; sep3=" && "; } else { - if(!bParentRef && FKParentFK(_workingTable) == fk){ + if (!bParentRef && FKParentFK(_workingTable) == fk){ // WriteLine("\r\n\r\n// 20070305 Column {0}\r\n",column.Name); reqKeys="my"+ParentName(fk)+sep2+reqKeys; reqKeysTypes=FormatColumn("{ParentType}",column)+sep2+reqKeysTypes; @@ -2863,8 +3016,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get } string reqKeysContain = (SameList(reqCols,fkCols)?sFkKeys:reqKeys); IList uniqueMatch = FindUnique(uniqueChildren,reqCols); -// WriteLine("\r\n//20070302 - {0}", uniqueMatch); -// if(uniqueMatch != null)WriteLine("\r\n//20070302 - {0}", uniqueMatch[0]); + //if (uniqueMatch != null)WriteLine("\r\n//20090108 - \r\n\tuniqueMatch {0}\r\n\treqCols {1}", ColumnListToString(uniqueMatch),ColumnListToString(reqCols) ); string newString = (fkCols.Count==1 && sTestTypes == "int" ? "new " : ""); %> public <%=newString%><%=sFkClassName%> this[<%=sFkKeysTypes%>] @@ -2888,9 +3040,9 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get return <%=slName%>; return null; }<% - if(bManyToMany) + if (bManyToMany) { - if(reqKeys!=""){ // Has Required Fields + if (reqKeys!=""){ // Has Required Fields %> public <%=sFkClassName%> Add(<%=reqKeysTypes%>)// Many to Many with required fields { @@ -2906,7 +3058,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get } else { - if(uniqueMatch != null) + if (uniqueMatch != null && uniqueMatch.Count > 1) { %> public <%=sFkClassName%> Add(<%=reqKeysTypes%>)// Many to Many with unique fields @@ -2939,17 +3091,17 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get string sParent = ""; string sParentUse = ""; - //if("Child" + ClassesName(sFkClassName) == _className) + //if ("Child" + ClassesName(sFkClassName) == _className) //{ // sParent = sFkClassName + " parent, "; // sParentUse = "parent, "; //} - if(uniqueMatch != null) + if (uniqueMatch != null) { %> public <%=sFkClassName%> Add(<%=reqKeysTypes%>) // One to Many with unique fields { - if (!Contains(<%=FormatColumns("{local}",uniqueMatch,", ","")%>)) + if (!Contains(<%=FormatColumns("{!local}",uniqueMatch,", ","")%>)) { <%=sFkClassName%> <%=slName%> = <%=sFkClassName%>.New(<%=reqKeys%>); this.Add(<%=slName%>); @@ -2964,12 +3116,14 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get %> public <%=sFkClassName%> Add(<%=sParent%><%=sKeysTypes%>) // One to Many { - <%=sFkClassName%> <%=slName%> = <%=sFkClassName%>.New(<%=sParentUse%><%=sKeys%>); - this.Add(<%=slName%>); - return <%=slName%>; + <%=sFkClassName%> <%=slName%> = <%=sFkClassName%>.New(<%=sParentUse%><%=sKeys%>); + this.Add(<%=slName%>); + return <%=slName%>; }<% } } + if(fkCols.Count == 1 && uniqueMatch != null && uniqueMatch.Count == 1 && fkCols[0]==uniqueMatch[0]) + uniqueMatch=null; %> public void Remove(<%=sFkKeysTypes%>) { @@ -2995,9 +3149,42 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get if (<%=sFkCheck%>) return true; return false; - }<% + } + public bool IsDirtyList(List list) + { + // any non-new deletions make us dirty + foreach (<%=sFkClassName%> item in DeletedList) + if (!item.IsNew) + return true; + // run through all the child objects + // and if any are dirty then then + // collection is dirty + foreach (<%=sFkClassName%> child in this) + if (child.IsDirtyList(list)) + return true; + return false; + } + public override bool IsValid + { + get { return IsValidList(new List()); } + } + public bool IsValidList(List list) + { + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (<%=sFkClassName%> child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + }<% foreach(IList lst in uniqueChildren){ - if(!SameTypes(lst,fkCols)){ // Has Required Fields 20070302 + if (!SameTypes(lst,fkCols)){ // Has Required Fields 20070302 + if(lst.Count == 1 && uniqueMatch != null && uniqueMatch.Count == 1 && lst[0]==uniqueMatch[0]) + uniqueMatch=null; string sLstKeysTypes = FormatColumns("{ctype} {local}",lst,", "); // string sKeys = FormatColumns("{local}",lst,", "); string sLstCheck = FormatColumns(slName +".{prop} == {local}",lst," && "); @@ -3018,6 +3205,27 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get }<% } } + if(uniqueMatch != null && uniqueMatch.Count == 1) + { + IColumn col =(IColumn)uniqueMatch[0]; + string sLstKeysTypes = FormatColumn("{!type} {!local}",col); + string sLstCheck = FormatColumn(slName +".{prop} == {!local}.{!column}",col); +%> + public bool Contains(<%=sLstKeysTypes%>) + { + foreach (<%=sFkClassName%> <%=slName%> in this) + if (<%=sLstCheck%>) + return true; + return false; + } + public bool ContainsDeleted(<%=sLstKeysTypes%>) + { + foreach (<%=sFkClassName%> <%=slName%> in DeletedList) + if (<%=sLstCheck%>) + return true; + return false; + }<% + } %> #endregion<% } @@ -3029,7 +3237,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get string sFkClassName = _subclassName; string sExtra1=""; string sExtra2=""; - if(fk.PrimaryTable == fk.ForeignTable){ + if (fk.PrimaryTable == fk.ForeignTable){ sExtra1=", " + _subclassName + " parent"; sExtra2=", parent"; } @@ -3044,7 +3252,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get { return new <%=sFkClassListName%>(dr<%=sExtra2%>); }<% -// if(fk.PrimaryTable==fk.ForeignTable) +// if (fk.PrimaryTable==fk.ForeignTable) // { // Get Children 20070205 string sBy = FormatColumns("{name}",fk.ForeignColumns,"_",""); @@ -3085,7 +3293,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get string sPrimaryLocal = LocalName(sPrimaryTable); string sExtra1=""; string sExtra2=""; - if(fk.PrimaryTable == fk.ForeignTable){ + if (fk.PrimaryTable == fk.ForeignTable){ sExtra1=", " + _subclassName + " parent"; sExtra2=", parent"; } @@ -3103,7 +3311,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get string sClassP = FormatColumns("{name}",fk.ForeignColumns,"_",""); string sBy = ClassesName(fk.ForeignTable) + "By" + FormatColumns("{name}",fk.ForeignColumns,"_",""); string sSelfParam = ""; - if(fk.ForeignTable == fk.PrimaryTable) + if (fk.ForeignTable == fk.PrimaryTable) { sBy = ChildName(fk) + ClassesName(_workingTable); sSelfParam = ", " + FormatColumns("criteria.{prop}",fk.ForeignColumns,"",""); @@ -3176,7 +3384,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get foreach (<%=sFkClassName%> obj in this) {<% // Logic changes for children - if(fk.PrimaryTable == fk.ForeignTable) + if (fk.PrimaryTable == fk.ForeignTable) { %> if (obj.IsNew) @@ -3321,8 +3529,8 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get /// public partial class <%=_className%>PropertyDescriptor : vlnListPropertyDescriptor { - private <%=_subclassName%> Item { get { return (<%=_subclassName%>) _Item;} } - public <%=_className%>PropertyDescriptor(<%=_className%> collection, int index):base(collection, index){;} + private <%=_subclassName%> Item { get { return (<%=_subclassName%>)_Item; } } + public <%=_className%>PropertyDescriptor(<%=_className%> collection, int index) : base(collection, index) { ;} } #endregion<% } @@ -3372,7 +3580,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get if (destType == typeof(string) && value is <%=_className%>) { // Return department and department role separated by comma. - return ((<%=_className%>) value).Items.Count.ToString() + " <%=sDisplayName%>"; + return ((<%=_className%>)value).Items.Count.ToString() + " <%=sDisplayName%>"; } return base.ConvertTo(context, culture, value, destType); } @@ -3397,36 +3605,36 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get string sep=""; foreach(IColumn column in fk.ForeignTable.Columns) { - if(!IsIn(column,fk.ForeignColumns)) + if (!IsIn(column,fk.ForeignColumns)) { bool bReadOnly = column.IsInPrimaryKey || column.IsAutoKey || column.IsComputed; string sCheck=(IsRelObj(column)?FormatColumn("\r\n\t\t\t\tif ({!member} != null) {member} = {!member}.{!column};",column):null); vlnProperty(CSLAType( column ),MemberName(column) - ,PropertyName(column),InitializeValue( column ),GetDescription(column),bReadOnly || IsRelObj(column),column.IsInPrimaryKey,false,null,sCheck,null); + ,PropertyName(column),InitializeValue( column ),GetDescription(column),bReadOnly || IsRelObj(column),column.IsInPrimaryKey,false,null,sCheck,null,null); vlnRelObjProperty(column,bReadOnly,false); - if(column.IsInPrimaryKey){ + if (column.IsInPrimaryKey){ sKey+=sep+MemberName(column); sep=".ToString() + "; } } - if((sep != "") && (sKey.IndexOf(sep) > 0)) + if ((sep != "") && (sKey.IndexOf(sep) > 0)) sKey="(" + sKey + ".ToString()).GetHashCode()"; } // Foreign Key Related Table Fields // 20070220 Hashtable dicAlias = new Hashtable(); foreach(IForeignKey pk in fk.ForeignTable.ForeignKeys) { - if(pk.ForeignTable == fk.ForeignTable && pk.PrimaryTable != fk.PrimaryTable && pk.PrimaryTable.Name != pk.ForeignTable.Name && ForeignRequired(pk)) + if (pk.ForeignTable == fk.ForeignTable && pk.PrimaryTable != fk.PrimaryTable && pk.PrimaryTable.Name != pk.ForeignTable.Name && ForeignRequired(pk)) { //sAlias = GetAlias(dicAlias,pk.PrimaryTable); sAlias = GetAlias(pk); foreach(IColumn column in pk.PrimaryTable.Columns) { - if((!IsIn(column,pk.PrimaryColumns)) && (column.DataTypeName != "timestamp")) + if ((!IsIn(column,pk.PrimaryColumns)) && (column.DataTypeName != "timestamp")) { string sProp = ClassName(pk.PrimaryTable) + sAlias + "_" + PropertyName(column); vlnProperty(CSLAType( column ),MemberName(sProp) - ,sProp,InitializeValue( column ),GetDescription(column),true,column.IsInPrimaryKey,false,null,null,null); + ,sProp,InitializeValue( column ),GetDescription(column),true,column.IsInPrimaryKey,false,null,null,null,null); } } } @@ -3457,13 +3665,14 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get foreach(IColumn col in fk.ForeignTable.Columns) { string sColumn = RequiredRelatedColumn(col); - if(sColumn != null){ // Let the Validation Rules handle IsDirty and IsValid - LazyLoad should be ignored. - sExtDirty += string.Format(" || ({0} == null ? false : {0}.IsDirty)",MemberName(sColumn)); + if (sColumn != null){ // Let the Validation Rules handle IsDirty and IsValid - LazyLoad should be ignored. + sExtDirty += string.Format(" || ({0} == null ? false : {0}.IsDirtyList(list))",MemberName(sColumn)); sExtValid += string.Format(" && ({0} == null ? true : {0}.IsValid)",MemberName(sColumn)); } } - if(sExtDirty!="")vlnDirty(sExtDirty); - if(sExtValid!="")vlnValid(sExtValid); + //if (sExtDirty!="") + vlnDirty(sExtDirty); + vlnValid(sExtValid); %> #endregion<% } @@ -3471,7 +3680,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get { string sFkClassListName = ClassName( fk.PrimaryTable ) + ClassesName( fk.ForeignTable ) + sAlias; string sFkClassName; - if( fk.PrimaryTable == fk.ForeignTable) + if (fk.PrimaryTable == fk.ForeignTable) sFkClassName = ClassName( fk.ForeignTable ) + sAlias; else sFkClassName = ClassName( fk.PrimaryTable ) + ClassName( fk.ForeignTable ) + sAlias; @@ -3484,8 +3693,8 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get {<%=Debug("20070509.vlnValidationRulesFKList")%> get { - IVEHasBrokenRules hasBrokenRules=null; - foreach(<%=sFkClassName%> <%=sPrimaryLocal%> in this) + IVEHasBrokenRules hasBrokenRules = null; + foreach (<%=sFkClassName%> <%=sPrimaryLocal%> in this) if ((hasBrokenRules = <%=sPrimaryLocal%>.HasBrokenRules) != null) return hasBrokenRules; return hasBrokenRules; } @@ -3494,8 +3703,8 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get { get { - IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + IVEHasBrokenRules hasBrokenRules = HasBrokenRules; + return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); } } #endregion<% @@ -3509,24 +3718,24 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get %> #region ValidationRules [NonSerialized] - private bool _CheckingBrokenRules=false; + private bool _CheckingBrokenRules = false; public IVEHasBrokenRules HasBrokenRules {<%=Debug("20070509.vlnValidationRulesFKItem")%> get { - if(_CheckingBrokenRules)return null; + if (_CheckingBrokenRules) return null; if (BrokenRulesCollection.Count > 0) return this; try { - _CheckingBrokenRules=true; - IVEHasBrokenRules hasBrokenRules = null;<% - vlnBrokenRuleObjects(fk); + _CheckingBrokenRules = true; + IVEHasBrokenRules hasBrokenRules = null;<% + vlnBrokenRuleObjects(fk); %> - return hasBrokenRules; + return hasBrokenRules; } finally { - _CheckingBrokenRules=false; + _CheckingBrokenRules = false; } } } @@ -3543,15 +3752,15 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get {<% foreach(IColumn column in fk.ForeignTable.Columns) { - if(!(IsIn(column,fk.ForeignColumns) || column.IsInPrimaryKey || column.IsAutoKey || column.IsComputed)) + if (!(IsIn(column,fk.ForeignColumns) || column.IsInPrimaryKey || column.IsAutoKey || column.IsComputed)) { - if(column.LanguageType=="string") + if (column.LanguageType=="string") { vlnAddRequired(column); - if(column.CharacterMaxLength < 2147483647) + if (column.CharacterMaxLength < 2147483647) vlnAddMaxLength(PropertyName(column),column.CharacterMaxLength); } - if(CSLAType( column )=="SmartDate") + if (CSLAType( column )=="SmartDate") { vlnAddRequired(column); string sName = PropertyName(column); @@ -3559,7 +3768,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get ValidationRules.AddRule<<%=_className%>>(<%=sName%>Valid, "<%=sName%>");<% } string sObjectRequired = RequiredRelatedColumn(column); - if(sObjectRequired != null) + if (sObjectRequired != null) { %> ValidationRules.AddRule<<%=_className%>>(<%=sObjectRequired%>Required, "<%=sObjectRequired%>");<% @@ -3571,9 +3780,9 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get }<% foreach(IColumn column in fk.ForeignTable.Columns) { - if(!(IsIn(column,fk.ForeignColumns) || column.IsInPrimaryKey || column.IsAutoKey || column.IsComputed)) + if (!(IsIn(column,fk.ForeignColumns) || column.IsInPrimaryKey || column.IsAutoKey || column.IsComputed)) { - if(CSLAType( column )=="SmartDate") + if (CSLAType( column )=="SmartDate") { string sName = PropertyName(column); string sMember = MemberName(column); @@ -3597,7 +3806,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get foreach(IColumn col in fk.ForeignTable.Columns) { string sColumn = RequiredRelatedColumn(col); - if(sColumn != null){ // Let the Validation Rules handle required fields + if (sColumn != null){ // Let the Validation Rules handle required fields string sMemberRaw = MemberName(col); string sMemberReq = MemberName(sColumn); %> @@ -3641,11 +3850,11 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get //TODO: Who can read/write which fields<% foreach(IColumn column in fk.ForeignTable.Columns) { - if(!(IsIn(column,fk.ForeignColumns)) && column.DataTypeName != "timestamp") + if (!(IsIn(column,fk.ForeignColumns)) && column.DataTypeName != "timestamp") { %> //AuthorizationRules.AllowRead(<%=PropertyName(column)%>, "");<% - if(!(column.IsInPrimaryKey || column.IsAutoKey || column.IsComputed)) + if (!(column.IsInPrimaryKey || column.IsAutoKey || column.IsComputed)) { %> //AuthorizationRules.AllowWrite(<%=PropertyName(column)%>, "");<% @@ -3699,45 +3908,45 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get ArrayList pks = new ArrayList(); foreach(IColumn column in fk.ForeignTable.Columns) { - if(!IsIn(column,fk.ForeignColumns)) + if (!IsIn(column,fk.ForeignColumns)) { - if(IsRequired(column) && !column.IsComputed && !column.IsAutoKey) + if (IsRequired(column) && !column.IsComputed && !column.IsAutoKey) { sKeysTypes+=sep+FormatColumn("{!type} {!local}",column); sKeys+=sep+FormatColumn("{!local}",column); - if(IsRelObj(column)) + if (IsRelObj(column)) sValues+=sep + FormatColumn("{!local}",column); // 20070301 else sValues+=sep+RelatedObject(fk,column); - if(IsRelObj(column)) + if (IsRelObj(column)) sValues2+=sep + FormatColumn("{!type} {!local}",column); // 20070301 else sValues2+=sep + RelatedObjectType2(fk,column); // 20070301 foreach(IForeignKey pk in column.ForeignKeys) - if(!pks.Contains(pk)) + if (!pks.Contains(pk)) { pks.Add(pk.Name); //sValues2+=" /* " + pk.Name + " */ "; } sep=", "; - if(!column.IsInForeignKey || IsRelObj(column)){ - //if(CSLAType(column)=="SmartDate") + if (!column.IsInForeignKey || IsRelObj(column)){ + //if (CSLAType(column)=="SmartDate") // sInit+=sep2 + FormatColumn("\t\t{member} = new SmartDate({local});",column); //else - if(IsRelObj(column)) - sInit+=sep2 + FormatColumn("\t\t\t{!member} = {!local};",column); + if (IsRelObj(column)) + sInit+=sep2 + FormatColumn("\t\t\t{!member} = {!local};",column); else - sInit+=sep2 + FormatColumn("\t\t\t{member} = {local};",column); + sInit+=sep2 + FormatColumn("\t\t\t{member} = {local};",column); sep2="\r\n"; } else { IForeignKey pk = column.ForeignKeys[0]; - if(pk == FKParentFK(column.Table)) + if (pk == FKParentFK(column.Table)) { IColumn colf = RelatedColumnF(column,pk); - if(colf != null){ - sInit+=sep2 + FormatColumn("\t\t\t{member} = ",column) + FormatColumn("{rmember};",colf); + if (colf != null){ + sInit+=sep2 + FormatColumn("\t\t\t{member} = ",column) + FormatColumn("{rmember};",colf); sep2="\r\n"; } } @@ -3749,7 +3958,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get //Hashtable dicAlias = new Hashtable(); foreach(IForeignKey pk in fk.ForeignTable.ForeignKeys) { - if(pks.Contains(pk.Name) && pk.ForeignTable == fk.ForeignTable && pk.PrimaryTable.Name != pk.ForeignTable.Name && pk.Name != fk.Name && ForeignRequired(pk)) + if (pks.Contains(pk.Name) && pk.ForeignTable == fk.ForeignTable && pk.PrimaryTable.Name != pk.ForeignTable.Name && pk.Name != fk.Name && ForeignRequired(pk)) { //sAlias = GetAlias(dicAlias,pk.PrimaryTable); sAlias = GetNewAlias(fk,pk); @@ -3757,22 +3966,22 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get { IColumn col = RelatedColumn(column,pk); col =col.Table.Columns[col.Name]; - if(!IsRelObj(col)) + if (!IsRelObj(col)) { string sProp = ClassName(pk.PrimaryTable) + sAlias + "_" + PropertyName(column); string sLocal = LocalName(ClassName(pk.PrimaryTable))+ sAlias; string sMember = MemberName(sProp); - if(IsIn(column,pk.PrimaryColumns)) + if (IsIn(column,pk.PrimaryColumns)) { sInit+=sep2 + "\t\t\t" + MemberName(RelatedColumn(column,pk)) + " = " + sLocal + "." + PropertyName(column) + ";"; sep2="\r\n"; } else { - if(pk.PrimaryTable != fk.PrimaryTable) + if (pk.PrimaryTable != fk.PrimaryTable) { - if(column.DataTypeName != "timestamp"){ - if(CSLAType(column)=="SmartDate") + if (column.DataTypeName != "timestamp"){ + if (CSLAType(column)=="SmartDate") sInit+=sep2 + "\t\t\t" + sMember + " = new SmartDate(" + sLocal + "." + PropertyName(column) + ");"; else sInit+=sep2 + "\t\t\t" + sMember + " = " + sLocal + "." + PropertyName(column) + ";"; @@ -3807,15 +4016,15 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get <%=FormatColumns("{member} = " + extMName + ".Default{prop};",HasDefaults(fk),"\r\n","\t\t\t")%> ValidationRules.CheckRules(); }<% - if(sValues2 != "") { - //if(sInit=="")sInit = "// No Initialization"; + if (sValues2 != "") { + //if (sInit=="")sInit = "// No Initialization"; //else sInit = "// Initialization\r\n" + sInit; %> private <%=sFkClassName%>(<%=sValues2%>) { MarkAsChild(); // TODO: Add any initialization & defaults -<%=FormatColumns("{member} = " + extMName + ".Default{prop};",HasDefaults(fk),"\r\n","\t\t\t")%> +<%=FormatColumns("\t\t\t{member} = {class}.Next{prop};\r\n",AutoKey(fk),"","")%><%=FormatColumns("{member} = " + extMName + ".Default{prop};",HasDefaults(fk),"\r\n","\t\t\t")%> <%=sInit%> ValidationRules.CheckRules(); }<% @@ -3855,29 +4064,29 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get { foreach(IColumn column in fk.ForeignTable.Columns) { - if(column.DataTypeName=="timestamp") + if (column.DataTypeName=="timestamp") sTimestamp=FormatColumn("{member} = ",column); - if(!IsIn(column,fk.ForeignColumns)) + if (!IsIn(column,fk.ForeignColumns)) { sRead+=sepr+FormatColumn(dicRead,column,"\t\t\t\t",""); sepr="\r\n"; string sRef = ParentRef(column); - if(sRef==null) + if (sRef==null) { - if(column.IsComputed || column.IsAutoKey) + if (column.IsComputed || column.IsAutoKey) sRef=FormatColumn("ref {?dbprefix}{member}{?dbsuff}",column); else - //if(column.IsInPrimaryKey) // 20070326 + //if (column.IsInPrimaryKey) // 20070326 // sRef=FormatColumn("{?dbprefix}{!membercolumn}{?dbsuff}",column);// 20070323 //else - if(FormatColumn("{!type}",column)==ClassName(fk.ForeignTable)) + if (FormatColumn("{!type}",column)==ClassName(fk.ForeignTable)) sRef=FormatColumn("{?dbprefix}{!membercolumn}{?dbsuff}",column);// 20070326 else sRef=FormatColumn("{?dbprefix}{!member}{?dbsuff}",column);// 20070326 } sUpdate+=sepu + sRef; sepu=", "; - if(!column.IsComputed)// && !column.IsAutoKey + if (!column.IsComputed)// && !column.IsAutoKey { sInsert+=sepi+sRef; sepi=", "; @@ -3886,7 +4095,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get else { string sRef; - if(IsRelObj(column)) + if (IsRelObj(column)) sRef = FormatColumn("{?dbprefix}{!local}{?dbsuff}",column); else sRef = FormatColumn("{?dbprefix}{rmember}{?dbsuff}",RelatedColumn(column,fk)); @@ -3899,9 +4108,9 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get } foreach(IColumn column in fk.ForeignTable.PrimaryKeys) { - if(IsIn(column,fk.ForeignColumns)) + if (IsIn(column,fk.ForeignColumns)) sDelete+=sepd+FormatColumn("{!localcolumn}",column); - //sDelete+=sepd+FormatColumn("/*1*/{rmember}",RelatedColumn(column,fk)); + //sDelete+=sepd+FormatColumn("{rmember}",RelatedColumn(column,fk)); else sDelete+=sepd+FormatColumn("{member}",column); sepd=", "; @@ -3915,7 +4124,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get Hashtable dicAlias = new Hashtable(); foreach(IForeignKey pk in fk.ForeignTable.ForeignKeys) { - if(pk.ForeignTable == fk.ForeignTable && pk.PrimaryTable != fk.PrimaryTable && pk.PrimaryTable != pk.ForeignTable && ForeignRequired(pk)) + if (pk.ForeignTable == fk.ForeignTable && pk.PrimaryTable != fk.PrimaryTable && pk.PrimaryTable != pk.ForeignTable && ForeignRequired(pk)) { //sAlias = GetAlias(dicAlias,pk.PrimaryTable); sAlias = GetAlias(pk); @@ -3924,7 +4133,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get //} foreach(IColumn column in pk.PrimaryTable.Columns) { - if(!IsIn(column,pk.PrimaryColumns) && column.DataTypeName != "timestamp" && !column.IsInPrimaryKey) + if (!IsIn(column,pk.PrimaryColumns) && column.DataTypeName != "timestamp" && !column.IsInPrimaryKey) { sRead+=sepr+FormatColumn(dicRead,column,"\t\t\t\t",sAlias); sepr="\r\n"; @@ -4001,7 +4210,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get #region Factory Methods public static <%=_className%> <%=sMember%> = null; /// - /// Return a list of all projects. + /// Return a list of all <%=_subclassName%>. /// public static <%=_className%> Get() { @@ -4019,6 +4228,13 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get { throw new DbCslaException("Error on <%=_className%>.Get", ex); } + } + /// + /// Reset the list of all <%=_subclassName%>. + /// + public static void Reset() + { + <%=sMember%> = null; }<% // ForeignKeys - List Foreign Keys - May want to create stored procedures %> @@ -4038,9 +4254,9 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get // ArrayList lstByNames = new ArrayList(); // foreach(IForeignKey FK in _workingTable.ForeignKeys) // { -// if(FK.ForeignTable == _workingTable) +// if (FK.ForeignTable == _workingTable) // { -// if(!lstByNames.Contains(FK.PrimaryTable.Name)) +// if (!lstByNames.Contains(FK.PrimaryTable.Name)) // { // FKGet(FK); // lstByNames.Add(FK.PrimaryTable.Name); @@ -4059,7 +4275,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get //string sKeys = FormatColumns("{local}",FK.PrimaryTable.PrimaryKeys,",",""); string sBy = FormatColumns("{name}",FK.ForeignColumns,"_",""); string sBy2 = "By" + sBy; - if(FK.PrimaryTable == FK.ForeignTable)sBy2=ChildrenName(FK); + if (FK.PrimaryTable == FK.ForeignTable)sBy2=ChildrenName(FK); string sKeyTypes = FormatColumns("{ctype} {local}",FK.ForeignColumns,",",""); string sKeys = FormatColumns("{local}",FK.ForeignColumns,",",""); %> @@ -4114,9 +4330,9 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get // ArrayList lstTableNames = new ArrayList(); // foreach(IForeignKey FK in _workingTable.ForeignKeys) // { -// if(FK.ForeignTable == _workingTable) +// if (FK.ForeignTable == _workingTable) // { -// if(!lstTableNames.Contains(FK.PrimaryTable.Name)) +// if (!lstTableNames.Contains(FK.PrimaryTable.Name)) // { // FKFetch(FK); // lstTableNames.Add(FK.PrimaryTable.Name); @@ -4134,7 +4350,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get //string sKeyTypes = FormatColumns("{ctype} {local}",FK.PrimaryTable.PrimaryKeys,",",""); string sClassP = FormatColumns("{name}",FK.ForeignColumns,"_",""); string sBy = ClassesName(_workingTable) + "By" + FormatColumns("{name}",FK.ForeignColumns,"_",""); - if(FK.ForeignTable == FK.PrimaryTable)sBy = ChildName(FK) + ClassesName(_workingTable); + if (FK.ForeignTable == FK.PrimaryTable)sBy = ChildName(FK) + ClassesName(_workingTable); string sKeyTypes = FormatColumns("{ctype} {local}",FK.ForeignColumns,",",""); //string sKeys = FormatColumns("{local}",FK.ForeignColumns,",",""); %> @@ -4192,19 +4408,32 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get } private void vlnRelObjProperty(IColumn column,bool bReadOnly,bool bInfo) { - if(IsRelObj(column)) + if (IsRelObj(column)) { string sProp=RelObjProp(column); string sMember=MemberName(sProp); string sCheck=FormatColumn("\r\n\t\t\t\tif ({!member} == null && {member} != {!empty}) {!member} = {!type}" + (bInfo?"Info":"") + ".Get({!typecast}{member});",column); string sCheck2=null; - if(column.IsNullable) - sCheck2=FormatColumn("\r\n\t\t\t\t\t{member} = (value == null ? null : ({ctype}) value.{!column});",column); + string sCheck3=null; + if (column.IsNullable) + { + sCheck2=FormatColumn("\r\n\t\t\t\t\t{member} = (value == null ? null : ({ctype})value.{!column});",column); + sCheck3=FormatColumn("({!member} == null ? {member} : ({ctype}){!member}.{!column}) != (value == null ? null : ({ctype})value.{!column})",column); + } vlnProperty(RelObjType( column ) + (bInfo?"Info":"") ,sMember - ,sProp,";"+DebugLine("20070501.4"),"",bReadOnly,column.IsInPrimaryKey,false,null,sCheck,sCheck2); - if(sProp.StartsWith("My"))_refreshMine += string.Format("\t\t\t{0} = null;\r\n",sMember); + ,sProp,";"+DebugLine("20070501.4"),"",bReadOnly,column.IsInPrimaryKey,false,null,sCheck,sCheck2,sCheck3); + //if (sProp.StartsWith("My"))_refreshMine += string.Format("\t\t\t{0} = null;\r\n",sMember); + if (sProp.StartsWith("My"))AddRefreshMine(sMember); } } + private void AddRefreshMine(string sMember) + { + _refreshMine += string.Format("\t\t\tif({0} != null)\r\n",sMember); + _refreshMine += string.Format("\t\t\t{{\r\n",sMember); + _refreshMine += string.Format("\t\t\t\t{0}.Dispose();// Dispose related value\r\n",sMember); + _refreshMine += string.Format("\t\t\t\t{0} = null;// Reset related value\r\n",sMember); + _refreshMine += string.Format("\t\t\t}}\r\n",sMember); + } private void vlnBusinessMethodsInfo(IColumns columns) { _refreshMine=""; @@ -4234,24 +4463,28 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get { string sCheck=(IsRelObj(column)?FormatColumn("\r\n\t\t\t\tif ({!member} != null) {member} = {!member}.{!column};",column):null); vlnProperty(CSLAType( column ),MemberName(column) - ,PropertyName(column),InitializeValue( column ),GetDescription(column),true,column.IsInPrimaryKey,false,null,sCheck,null); + ,PropertyName(column),InitializeValue( column ),GetDescription(column),true,column.IsInPrimaryKey,false,null,sCheck,null,null); vlnRelObjProperty(column,true,true); } Hashtable dicAlias = new Hashtable(); foreach(IForeignKey FK in _workingTable.ForeignKeys) { - if(FK.PrimaryTable == _workingTable) + if (FK.PrimaryTable == _workingTable) { //string sAlias = GetAlias(dicAlias,FK.ForeignTable); string sAlias = GetAlias(FK); string sClass = FKClassName(FK); string sClasses = FKClassesName(FK); - vlnProperty("int",MemberName(sClass) + sAlias + "Count" ,sClass + sAlias + "Count", " = 0;", - "Count of " + sClasses + " for this " + ClassName(_workingTable),true,false,false,null,null,null); - if(!OneToOne(FK)) + if (!OneToOne(FK)) FKPropertyList(ClassName(FK.ForeignTable),sClasses,FK,sAlias); else + { + vlnProperty("int",MemberName(sClass) + sAlias + "Count" ,sClass + sAlias + "Count", " = 0;", + "Count of " + sClasses + " for this " + ClassName(_workingTable),true,false,false,null,null,null,null); FKPropertyInfo(ClassName(FK.ForeignTable),sClasses,FK,sAlias); + // This line was added to reset the count if the Content object was changed + _refreshMine += string.Format("\t\t\t{0} = -1;// Reset Count\r\n",MemberName(sClass) + sAlias + "Count"); + } } } @@ -4267,8 +4500,25 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get string sCountMember = MemberName(SingularName(sClasses)) + sAlias + "Count"; string sBy = FKBy(FK); string sProp = sClasses + sAlias; + string sParent = SingularName(FK.PrimaryTable.Name); + string sChild = SingularName(FK.ForeignTable.Name); //_refreshMine += string.Format("\t\t\t{0} = null;\r\n",sMember); %> + private int <%=sCountMember%> = 0; + /// + /// Count of <%=sMember.Substring(1)%> for this <%=sParent%> + /// + public int <%=sCountMember.Substring(1)%> + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] + get + { + CanReadProperty("<%=sCountMember.Substring(1)%>", true); + if (<%=sCountMember%> < 0) + <%=sCountMember%> = <%=sProp%>.Count; + return <%=sCountMember%>; + } + } private <%=sClass%>InfoList <%=sMember%> = null; [TypeConverter(typeof(<%=sClass%>InfoListConverter))] public <%=sClass%>InfoList <%=sProp%> @@ -4276,11 +4526,21 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { - CanReadProperty("<%=sProp%>",true); - if (<%=sCountMember%> > 0 && <%=sMember%> == null) + CanReadProperty("<%=sProp%>", true); + if (<%=sCountMember%> < 0 || (<%=sCountMember%> > 0 && <%=sMember%> == null)) <%=sMember%> = <%=sClass%>InfoList.Get<%=sBy%>(<%=sKeys%>); + if (<%=sCountMember%> < 0) + <%=sCountMember%> = <%=sMember%>.Count; return <%=sMember%>; } + } + public void Refresh<%=sProp%>() + {<%=DebugLine("20080430.3")%> + <%=sCountMember%> = -1; + ConvertListToDictionary(); + if (_CacheByPrimaryKey.ContainsKey(<%=sKeys%>.ToString())) + foreach (<%=_className%> tmp in _CacheByPrimaryKey[<%=sKeys%>.ToString()]) + tmp.<%=sCountMember%> = -1; // This will cause the data to be requeried }<% } private void FKPropertyInfo(string sClass,string sClasses,IForeignKey FK,string sAlias) @@ -4290,7 +4550,8 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get string sCountMember = MemberName(SingularName(sClasses)) + sAlias + "Count"; string sBy = FKBy(FK); string sProp = "My" + sClass + sAlias; - _refreshMine += string.Format("\t\t\t{0} = null;\r\n",sMember); + //_refreshMine += string.Format("\t\t\t{0} = null;// Reset related value\r\n",sMember); + AddRefreshMine(sMember); %> private <%=sClass%>Info <%=sMember%> = null; [TypeConverter(typeof(<%=sClass%>InfoConverter))] @@ -4299,9 +4560,12 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { - CanReadProperty("<%=sProp%>",true); - if (<%=sCountMember%> > 0 && <%=sMember%> == null) + CanReadProperty("<%=sProp%>", true); + if (<%=sCountMember%> != 0 && <%=sMember%> == null) + { <%=sMember%> = <%=sClass%>Info.Get(<%=sKeys%>); + <%=sCountMember%> = <%=sMember%> == null ? 0 : 1; + } return <%=sMember%>; } }<% @@ -4316,16 +4580,27 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get string sPKeys = FormatColumns("{member}",_workingTable.PrimaryKeys,", ",""); string sRefKeys = FormatColumns("{prop}.ToString()",_workingTable.PrimaryKeys," + \"_\" + ","");;//20070215 string sTmpKeys = FormatColumns("tmp.{prop}",_workingTable.PrimaryKeys,", ",""); + string sTRefKeys = FormatColumns("tmp.{prop}.ToString()",_workingTable.PrimaryKeys," + \"_\" + ","");;//20070215 %> #region Factory Methods - private <%=_className%>() + private static int _<%=_className%>Unique = 0; + private static int <%=_className%>Unique + { get { return ++_<%=_className%>Unique; } } + private int _My<%=_className%>Unique = <%=_className%>Unique; + public int My<%=_className%>Unique + { get { return _My<%=_className%>Unique; } } + protected <%=_className%>() {/* require use of factory methods */ - _AllList.Add(this); + AddToCache(this); } public void Dispose() { - _AllList.Remove(this); - _AllByPrimaryKey.Remove(<%=sRefKeys%>); + RemoveFromCache(this); + if (!_CacheByPrimaryKey.ContainsKey(<%=sRefKeys%>)) return; + List<<%=_className%>> list<%=_className%> = _CacheByPrimaryKey[<%=sRefKeys%>]; // Get the list of items + while (list<%=_className%>.Contains(this)) list<%=_className%>.Remove(this); // Remove the item from the list + if (list<%=_className%>.Count == 0) // If there are no items left in the list + _CacheByPrimaryKey.Remove(<%=sRefKeys%>); // remove the list } public virtual <%=ClassName( _workingTable )%> Get() {<%=DebugLine("20070502.1")%> @@ -4333,16 +4608,16 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get } public static void Refresh(<%=ClassName( _workingTable )%> tmp) { - <%=_className%> tmpInfo = GetExistingByPrimaryKey(<%=sTmpKeys%>); - if (tmpInfo == null) return; - tmpInfo.RefreshFields(tmp); + string key = <%=sTRefKeys%>; + ConvertListToDictionary(); + if (_CacheByPrimaryKey.ContainsKey(key)) + foreach (<%=_className%> tmpInfo in _CacheByPrimaryKey[key]) + tmpInfo.RefreshFields(tmp); } - private void RefreshFields(<%=ClassName( _workingTable )%> tmp) - {<% + protected virtual void RefreshFields(<%=ClassName( _workingTable )%> tmp) + {<%=DebugLine("20080430.1")%><% foreach(IColumn col in Updatable(_workingTable)) - { - output.write(FormatColumn("\r\n\t\t\t{member} = tmp.{prop};",col)); - } + UpdateInfoFromEdit(col); %> <%=MemberName(_className)%>Extension.Refresh(this); <%=_refreshMine%> OnChange();// raise an event @@ -4350,45 +4625,54 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get Hashtable dicAlias = new Hashtable(); // 20070216 foreach(IForeignKey fk in _workingTable.ForeignKeys) { - if(_workingTable != fk.PrimaryTable && !IsPrimaryKey(fk)) //20070220 + if (_workingTable != fk.PrimaryTable && !IsPrimaryKey(fk)) //20070220 { //string sClass=ClassName(fk.PrimaryTable)+ClassName(fk.ForeignTable)+GetAlias(dicAlias,fk.PrimaryTable); string sClass=ClassName(fk.PrimaryTable)+ClassName(fk.ForeignTable)+GetAlias(fk); // 20070326 - Need to add an object reference string sPrefix = ""; string sTmpKeys2 = sTmpKeys; - if(ForeignPrimary(fk)) + string sTmpKeyString = sTRefKeys; + if (ForeignPrimary(fk)) { string sOther = ClassName(fk.PrimaryTable); sPrefix = ClassName(fk.PrimaryTable) + " my" + ClassName(fk.PrimaryTable) + ", "; string ssep=""; + string ssepstr=""; sTmpKeys2=""; + sTmpKeyString = ""; foreach(IColumn col in _workingTable.PrimaryKeys) { //WriteLine("\r\n//!type = '{0}', sOther = '{1}', Col.Name = '{2}'", FormatColumn("{!type}",col), sOther, col.Name); - if(FormatColumn("{!type}",col)==sOther) + if (FormatColumn("{!type}",col)==sOther) + { sTmpKeys2 += ssep + FormatColumn("{!localcolumn}",col); + sTmpKeyString += ssepstr + FormatColumn("{!localcolumn}",col) + ".ToString()"; + } else + { sTmpKeys2 += ssep + FormatColumn("tmp.{prop}",col); + sTmpKeyString += ssepstr + FormatColumn("tmp.{prop}",col) + ".ToString()"; + } ssep=", "; + ssepstr=" + \"_\" + "; } } %> public static void Refresh(<%=sPrefix%><%=sClass%> tmp) { - <%=_className%> tmpInfo = GetExistingByPrimaryKey(<%=sTmpKeys2%>); - if (tmpInfo == null) return; - tmpInfo.RefreshFields(tmp); + string key = <%=sTmpKeyString%>; + ConvertListToDictionary(); + if (_CacheByPrimaryKey.ContainsKey(key)) + foreach (<%=_className%> tmpInfo in _CacheByPrimaryKey[key]) + tmpInfo.RefreshFields(tmp); } - private void RefreshFields(<%=sClass%> tmp) - {<% + protected virtual void RefreshFields(<%=sClass%> tmp) + {<%=DebugLine("20080430.2")%><% foreach(IColumn col in Updatable(_workingTable)) { - if(!IsIn(col,fk.ForeignColumns)) - { -%> - <%=FormatColumn("{member} = tmp.{prop};",col)%><% - } + if (!IsIn(col,fk.ForeignColumns)) + UpdateInfoFromEdit(col); } %> <%=MemberName(_className)%>Extension.Refresh(this); @@ -4403,15 +4687,19 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get // throw new System.Security.SecurityException("User not authorized to view a <%=ClassName(_workingTable)%>"); try { - <%=_className%> tmp = GetExistingByPrimaryKey(<%=sKeys%>); + <%=_className%> tmp = GetCachedByPrimaryKey(<%=sKeys%>); if (tmp == null) { tmp = DataPortal.Fetch<<%=_className%>>(new PKCriteria(<%=sKeys%>)); - _AllList.Add(tmp); + AddToCache(tmp); } if (tmp.ErrorMessage == "No Record Found")<% - if(!OneToOne(_workingTable)){ -%> tmp = null;<% + if (!OneToOne(_workingTable) || true){ // RHM 20080710 - Not sure why it should not return null +%> + { + tmp.Dispose(); // Clean-up <%=_className%> + tmp = null; + }<% } else { %> { @@ -4428,6 +4716,27 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get } #endregion<% } + private void UpdateInfoFromEdit(IColumn col) //20080430.4 + { + if (col.ForeignKeys.Count > 0) + { + string sProp=RelObjProp(col); + string sMember=MemberName(sProp); + IForeignKey FK = col.ForeignKeys[0]; + //string sClass = FKClassName(FK); + string sClasses = FKClassesName(FK); + string sAlias = GetAlias(FK); + output.write(FormatColumn("\r\n\t\t\tif ({member} != tmp.{prop})",col)); + output.write("\r\n\t\t\t{"); + output.write("\r\n\t\t\t\tif (" + sProp + " != null) " + sProp + ".Refresh" + sClasses + sAlias + "(); // Update List for old value"); + output.write(FormatColumn("\r\n\t\t\t\t{member} = tmp.{prop}; // Update the value",col)); + output.write("\r\n\t\t\t}"); + output.write("\r\n\t\t\t" + sMember + " = null; // Reset list so that the next line gets a new list" ); + output.write("\r\n\t\t\tif (" + sProp + " != null) " + sProp + ".Refresh" + sClasses + sAlias + "(); // Update List for new value"); + } + else + output.write(FormatColumn("\r\n\t\t\t{member} = tmp.{prop};",col)); + } private void vlnDataAccessPortalInfo(IColumns columns) { %> @@ -4496,12 +4805,12 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get public interface IVEHasBrokenRules { IVEHasBrokenRules HasBrokenRules { get; } - BrokenRulesCollection BrokenRules { get; } + BrokenRulesCollection BrokenRules { get; } }<% } public void Log4Net() { - if(_chkPartL4N) + if (_chkPartL4N) { %> #region Log4Net @@ -4516,7 +4825,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get %> public static partial class Database {<% - if(_chkPartL4N) + if (_chkPartL4N) { %> #region Log4Net @@ -4524,7 +4833,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get #endregion<% } %> - public static void LogException(string s,Exception ex) + public static void LogException(string s, Exception ex) { int i = 0; Console.WriteLine("Error - {0}", s); @@ -4540,14 +4849,14 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get set { _LoggingInfo = value; } } static System.Diagnostics.Process _CurrentProcess = System.Diagnostics.Process.GetCurrentProcess(); - public static void LogInfo(string s,int hashCode) + public static void LogInfo(string s, int hashCode) { - if (_LoggingInfo) + if (_LoggingInfo) Console.WriteLine("{0} MB {1}", _CurrentProcess.WorkingSet64 / 1000000, string.Format(s, hashCode)); } - public static void LogDebug(string s,int hashCode) + public static void LogDebug(string s, int hashCode) { - if (_LoggingInfo) + if (_LoggingInfo) Console.WriteLine("{0} MB {1}", _CurrentProcess.WorkingSet64 / 1000000, string.Format(s, hashCode)); } public static string <%=_dbConnection%>_Connection @@ -4627,7 +4936,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get } public class DbCslaException : Exception { - internal DbCslaException(string message, Exception innerException):base(message,innerException){;} + internal DbCslaException(string message, Exception innerException) : base(message, innerException) { ;} internal DbCslaException(string message) : base(message) { ;} internal DbCslaException() : base() { ;} } // Class diff --git a/PROMS/MyGeneration/csla_21/FilteredColumns.cs b/PROMS/MyGeneration/csla_21/FilteredColumns.cs index f51cf19d..6ee39abd 100644 --- a/PROMS/MyGeneration/csla_21/FilteredColumns.cs +++ b/PROMS/MyGeneration/csla_21/FilteredColumns.cs @@ -12,7 +12,7 @@ public ArrayList AutoKey(IForeignKey fk){ ArrayList l = new ArrayList(); foreach(IColumn column in fk.ForeignTable.Columns){ - if(column.IsAutoKey && !IsIn(column,fk.ForeignColumns))l.Add(column);} + if (column.IsAutoKey && !IsIn(column,fk.ForeignColumns))l.Add(column);} return l;} // Used in CSLA Stored Procedures private ArrayList AutoKey(ITable tbl){ @@ -180,7 +180,7 @@ string sPrefixType=""; string sPrefix=""; string sPrefixSet=""; - string sCheckSep = "if( "; + string sCheckSep = "if ("; sMakeListParamTypes = ""; sMakeListParams = ""; sSetTmp = ""; @@ -195,7 +195,7 @@ sepSet="\r\n"; if(IsRelObj(col)) // If item is null, don't look it up { - sParentCheck += sCheckSep + LocalName(RelObjProp(col)) + " != null "; + sParentCheck += "/*0*/" + sCheckSep + LocalName(RelObjProp(col)) + " != null "; sCheckSep = "|| "; } } @@ -511,6 +511,17 @@ } return null; } + public string ColumnListToString(IList lst) + { + string retval = ""; + string sep = ""; + foreach(IColumn col in lst) + { + retval += sep + col.Name; + sep=", "; + } + return retval; + } //public ArrayList zzFilteredColumnsAny(IColumns columns,Filter [] fs){ // ArrayList l = new ArrayList(); // foreach(IColumn column in columns) diff --git a/PROMS/MyGeneration/csla_21/FormatColumns.cs b/PROMS/MyGeneration/csla_21/FormatColumns.cs index 332b6037..86ecf92f 100644 --- a/PROMS/MyGeneration/csla_21/FormatColumns.cs +++ b/PROMS/MyGeneration/csla_21/FormatColumns.cs @@ -359,7 +359,7 @@ break; default: if(column.IsNullable && IsRelObj(column) && s.Contains("{ifLogicL")) - ifLogic="if({name} != null)"; + ifLogic="if ({name} != null) "; break; } s=s.Replace("{ifLogicL}",ifLogic.Replace("{name}",FormatColumnNew("{!local}{?dbtype}",column,sAlias))); diff --git a/PROMS/MyGeneration/csla_21/NamingConvention.cs b/PROMS/MyGeneration/csla_21/NamingConvention.cs index 56e7db7b..db189c3d 100644 --- a/PROMS/MyGeneration/csla_21/NamingConvention.cs +++ b/PROMS/MyGeneration/csla_21/NamingConvention.cs @@ -367,8 +367,14 @@ s="Environment.UserName"; break; default: - if(IsNumeric(s))s="" + s; - else s=""; + if(IsNumeric(s)) + s = "" + s; + else + { + if(s.StartsWith("N'")) + s = "\"" + s.Substring(2,s.Length-3) + "\""; + } + //else s=""; break; } return s; diff --git a/PROMS/MyGeneration/csla_21/vlnCSLA_SQL.csgen b/PROMS/MyGeneration/csla_21/vlnCSLA_SQL.csgen index f866434c..548570c9 100644 --- a/PROMS/MyGeneration/csla_21/vlnCSLA_SQL.csgen +++ b/PROMS/MyGeneration/csla_21/vlnCSLA_SQL.csgen @@ -255,7 +255,9 @@ public class GeneratedTemplate : DotNetScriptTemplate { StartProc("purgeData"); %> -AS<% +AS +BEGIN TRY -- Try Block + BEGIN TRANSACTION<% ArrayList toProcess = new ArrayList(); ArrayList processed = new ArrayList(); foreach(string sTable in _selectedTables) @@ -307,7 +309,7 @@ AS<% } if(processed.Count ==pCount)return; } - EndProc("purgeData"); + EndProcTran("purgeData"); } private void InitializeMembers() { @@ -387,6 +389,8 @@ AS <%=FormatColumns("{@} {dtype}{?null}",tbl.Columns,",\r\n","\t")%><%=FormatColumns("{@new} {dtype} output",Computed(tbl),"",",\r\n\t")%> ) AS +BEGIN TRY -- Try Block + BEGIN TRANSACTION UPDATE [<%=tbl.Name%>] SET <%=FormatColumns("[{name}]={@}",Updatable(tbl),",\r\n","\t\t\t")%> @@ -405,7 +409,7 @@ AS FROM [<%=tbl.Name%>] WHERE <%=FormatColumns("[{name}]={@}",tbl.PrimaryKeys," AND ","")%> <% } - EndProc(sproc); + EndProcTran(sproc); } //---------------------------------------------------------------------- // Insert @@ -419,6 +423,8 @@ AS <%=FormatColumns("{@} {dtype}{?null}",Insertable(tbl),",\r\n","\t")%><%=FormatColumns("{@new} {dtype} output",NotInsertable(tbl),"",",\r\n\t")%> ) AS +BEGIN TRY -- Try Block + BEGIN TRANSACTION INSERT INTO [<%=tbl.Name%>] ( <%=FormatColumns("[{name}]",Insertable(tbl),",\r\n","\t\t")%> @@ -435,7 +441,7 @@ AS SELECT <%=FormatColumns("{@new}=[{name}]",cmp,"\r\n","\t\t")%> FROM [<%=tbl.Name%>] WHERE <%=FormatColumns("[{name}]={@key}",tbl.PrimaryKeys," AND ","")%><% } - EndProc(sproc); + EndProcTran(sproc); } //---------------------------------------------------------------------- // Delete @@ -448,7 +454,9 @@ AS ( <%=FormatColumns("{@} {dtype}",tbl.PrimaryKeys,",\r\n","\t")%> ) -AS<% +AS +BEGIN TRY -- Try Block + BEGIN TRANSACTION<% foreach(IForeignKey fk in tbl.ForeignKeys) { if(tbl != fk.ForeignTable) @@ -467,7 +475,7 @@ AS<% %> DELETE [<%=tbl.Name%>] WHERE <%=FormatColumns("[{name}] = {@}",tbl.PrimaryKeys," AND ","")%><% - EndProc(sproc); + EndProcTran(sproc); } //---------------------------------------------------------------------- // SelectPK @@ -638,6 +646,24 @@ GO IF (@@Error = 0) PRINT 'Procedure Creation: <%=sproc%> Succeeded' ELSE PRINT 'Procedure Creation: <%=sproc%> Error on Creation' GO +<% + SaveFile(sproc); + } + private void EndProcTran(string sproc) + { +%> + IF( @@TRANCOUNT > 0 ) COMMIT +END TRY +BEGIN CATCH -- Catch Block + IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level + ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit. Top level will rollback + EXEC vlnErrorHandler +END CATCH +GO +-- Display the status of Proc creation +IF (@@Error = 0) PRINT 'Procedure Creation: <%=sproc%> Succeeded' +ELSE PRINT 'Procedure Creation: <%=sproc%> Error on Creation' +GO <% SaveFile(sproc); } diff --git a/PROMS/MyGeneration/csla_21/vlnSQL_Debug.csgen b/PROMS/MyGeneration/csla_21/vlnSQL_Debug.csgen index 0ffab1d1..b06becf9 100644 --- a/PROMS/MyGeneration/csla_21/vlnSQL_Debug.csgen +++ b/PROMS/MyGeneration/csla_21/vlnSQL_Debug.csgen @@ -64,27 +64,29 @@ public class GeneratedGui : DotNetScriptGui GuiCheckBox chkDetail = MakeGuiCheckBox( "chkDetail", "MakeList & FK", true, "Show MakeList and FK",100 ); chkDetail.Checked = false; - GuiCheckBox chkColumns = MakeGuiCheckBox( "chkColumns", "Columns", true, "Show Columns" ,150,chkDetail,200,0); + GuiCheckBox chkColumns = MakeGuiCheckBox( "chkColumns", "Columns", true, "Show Columns" ,150,chkDetail,150,0); chkColumns.Checked = false; - GuiCheckBox chkFKCalc1 = MakeGuiCheckBox( "chkFKCalc1", "FK Calc 1", true, "FK Calc 1" ,150,chkDetail,400,0); + GuiCheckBox chkFKCalc1 = MakeGuiCheckBox( "chkFKCalc1", "FK Calc 1", true, "FK Calc 1" ,150,chkDetail,300,0); chkFKCalc1.Checked = false; + GuiCheckBox chkProc = MakeGuiCheckBox( "chkProc", "Procedures", true, "Procedures" ,150,chkDetail,450,0); + chkProc.Checked = false; GuiCheckBox chkUnique = MakeGuiCheckBox( "chkUnique", "Unique", true, "Unique Indexes" ,150,chkDetail,0, -1); chkUnique.Checked = false; - GuiCheckBox chkFKCalc2 = MakeGuiCheckBox( "chkFKCalc2", "FK Calc 2", true, "FK Calc 2" ,150,chkDetail,200, -1); + GuiCheckBox chkFKCalc2 = MakeGuiCheckBox( "chkFKCalc2", "FK Calc 2", true, "FK Calc 2" ,150,chkDetail,150, -1); chkFKCalc2.Checked = false; - GuiCheckBox chkColumns2 = MakeGuiCheckBox("chkColumns2","PrimFK",true,"Primary Foreign Key",150,chkDetail,400, -1); + GuiCheckBox chkColumns2 = MakeGuiCheckBox("chkColumns2","PrimFK",true,"Primary Foreign Key",150,chkDetail,300, -1); chkColumns2.Checked = false; GuiCheckBox chkRelated = MakeGuiCheckBox("chkRelated","Related",true,"Related",150,chkDetail,0,-2); chkRelated.Checked = false; - GuiCheckBox chkOne2One = MakeGuiCheckBox("chkOne2One","One to One",true,"One to Many and One to One",150,chkDetail,200, -2); + GuiCheckBox chkOne2One = MakeGuiCheckBox("chkOne2One","One to One",true,"One to Many and One to One",150,chkDetail,150, -2); chkOne2One.Checked = false; - GuiCheckBox chkIndexes = MakeGuiCheckBox("chkIndexes","Indexes",true,"Compare Foreign Keys to Indexes",150,chkDetail,400, -2); + GuiCheckBox chkIndexes = MakeGuiCheckBox("chkIndexes","Indexes",true,"Compare Foreign Keys to Indexes",150,chkDetail,300, -2); chkIndexes.Checked = false; GuiCheckBox chkInternal = MakeGuiCheckBox("chkInternal","Internal",true,"Internal Relationships",150,chkDetail, 0, -3); chkInternal.Checked = false; - GuiCheckBox chkAlias = MakeGuiCheckBox("chkAlias","Alias",true,"Aliases",150,chkDetail, 200, -3); + GuiCheckBox chkAlias = MakeGuiCheckBox("chkAlias","Alias",true,"Aliases",150,chkDetail, 150, -3); chkAlias.Checked = false; - GuiCheckBox chkNames = MakeGuiCheckBox("chkNames","Names",true,"Names",150,chkDetail, 400, -3); + GuiCheckBox chkNames = MakeGuiCheckBox("chkNames","Names",true,"Names",150,chkDetail, 300, -3); chkNames.Checked = false; // Setup Tables selection multi-select listbox. GuiLabel label7 = ui.AddLabel( "label7", "Select tables:", "Select tables from the listbox below." ); @@ -113,6 +115,7 @@ public class GeneratedGui : DotNetScriptGui chkInternal.AttachEvent( "onclick", "checkbox_onclick" ); chkAlias.AttachEvent( "onclick", "checkbox_onclick" ); chkNames.AttachEvent( "onclick", "checkbox_onclick" ); + chkProc.AttachEvent( "onclick", "checkbox_onclick" ); chooseTables.AttachEvent( "onchange", "chooseTable_onclick" ); ui.ShowGui = true; GuiButton btnOK = ui.AddButton( "OK", "OK", "Generate Code" ); @@ -226,6 +229,7 @@ public class GeneratedGui : DotNetScriptGui GuiCheckBox chkInternal= ui["chkInternal"] as GuiCheckBox; GuiCheckBox chkAlias= ui["chkAlias"] as GuiCheckBox; GuiCheckBox chkNames= ui["chkNames"] as GuiCheckBox; + GuiCheckBox chkProc = ui["chkProc"] as GuiCheckBox; GuiLabel labelTest = ui["labelTest"] as GuiLabel; string status = ""; if(chkDetail.Checked)status+=", " + chkDetail.Text; @@ -240,6 +244,7 @@ public class GeneratedGui : DotNetScriptGui if(chkInternal.Checked)status+=", " + chkInternal.Text; if(chkAlias.Checked)status+=", " + chkAlias.Text; if(chkNames.Checked)status+=", " + chkNames.Text; + if(chkProc.Checked)status+=", " + chkProc.Text; if(status == "") { btnOK.Enabled = false; @@ -326,21 +331,28 @@ public class GeneratedTemplate : DotNetScriptTemplate _selectedTables = input["chooseTables"] as ArrayList; dicIndexes = new Hashtable(); dicDrop = new Hashtable(); - foreach( string _newTable in _selectedTables ) + if((bool)input["chkProc"]) { - _workingTable = MyMeta.Databases[_dbName].Tables[_newTable]; - if((bool)input["chkDetail"])ShowTable1( _workingTable ); - if((bool)input["chkColumns"])ShowTable2( _workingTable ); - if((bool)input["chkFKCalc1"])ShowTable3( _workingTable ); - if((bool)input["chkUnique"])ShowTable4( _workingTable ); - if((bool)input["chkFKCalc2"])ShowTable5( _workingTable ); - if((bool)input["chkColumns2"])ShowTable6( _workingTable ); - if((bool)input["chkRelated"])ShowTable7( _workingTable ); - if((bool)input["chkOne2One"])ShowTable8( _workingTable ); - if((bool)input["chkIndexes"])ShowTable9( _workingTable ); - if((bool)input["chkInternal"])ShowInternalRelated( _workingTable ); - if((bool)input["chkAlias"])ShowAlias( _workingTable ); - if((bool)input["chkNames"])ShowNames( _workingTable ); + ShowProcs(db); + } + else + { + foreach( string _newTable in _selectedTables ) + { + _workingTable = MyMeta.Databases[_dbName].Tables[_newTable]; + if((bool)input["chkDetail"])ShowTable1( _workingTable ); + if((bool)input["chkColumns"])ShowTable2( _workingTable ); + if((bool)input["chkFKCalc1"])ShowTable3( _workingTable ); + if((bool)input["chkUnique"])ShowTable4( _workingTable ); + if((bool)input["chkFKCalc2"])ShowTable5( _workingTable ); + if((bool)input["chkColumns2"])ShowTable6( _workingTable ); + if((bool)input["chkRelated"])ShowTable7( _workingTable ); + if((bool)input["chkOne2One"])ShowTable8( _workingTable ); + if((bool)input["chkIndexes"])ShowTable9( _workingTable ); + if((bool)input["chkInternal"])ShowInternalRelated( _workingTable ); + if((bool)input["chkAlias"])ShowAlias( _workingTable ); + if((bool)input["chkNames"])ShowNames( _workingTable ); + } } //foreach(ITable tbl in db.Tables) //{ @@ -355,6 +367,22 @@ public class GeneratedTemplate : DotNetScriptTemplate //} //SaveFile(); } + private void ShowProcs(IDatabase db) + { + foreach(IProcedure ip in db.Procedures) + { + //if(ip.Schema != "sys") + if(ip.Name=="purgeData" || ip.Name=="ve_GetPath") + { +%> +/****** Object: StoredProcedure [<%=ip.Name%>] Schema <%=ip.Schema%> Type <%=ip.Type.ToString()%> ******/ +<% + bool isFunction=ip.ProcedureText.Contains("CREATE FUNCTION"); + output.writeln(string.Format("IsFunction = {0}",isFunction)); + } + } + } + private string ForeignKeyCheck(IColumn col) { if(col.IsInForeignKey) diff --git a/PROMS/MyGeneration/csla_21/vlnSQL_List.csgen b/PROMS/MyGeneration/csla_21/vlnSQL_List.csgen index 461bf143..6e30035a 100644 --- a/PROMS/MyGeneration/csla_21/vlnSQL_List.csgen +++ b/PROMS/MyGeneration/csla_21/vlnSQL_List.csgen @@ -70,6 +70,7 @@ public class GeneratedGui : DotNetScriptGui GuiCheckBox chkDrop = MakeGuiCheckBox( "chkDrop", "Drop", true, "Drop Procedures" ,150,chkDelete,200,0); GuiCheckBox chkSelectPK = MakeGuiCheckBox( "chkSelectPK", "Select One", true, "Select One Record" ,150,chkInsert,0,-1); GuiCheckBox chkExists = MakeGuiCheckBox("chkExists","Exists",true,"Check Record Exists",150,chkSelectPK,150,0); + GuiCheckBox chkVolian = MakeGuiCheckBox( "chkVolian", "Volian SPs", true, "Include Volian SPs" ,150,chkExists,200,0); GuiCheckBox chkPurge = MakeGuiCheckBox("chkPurge","Purge",true,"Purge All Data",150,chkSelectPK,0,-1); GuiCheckBox chkSelectFKs = MakeGuiCheckBox("chkSelectFKs","Select Group",true,"Select by Foreign Key",150,chkPurge,150,0); @@ -223,22 +224,44 @@ public class GeneratedTemplate : DotNetScriptTemplate SaveProcs(db); //SaveTables(db); } + private bool IncludeVolian(string sName) + { + return (!sName.StartsWith("ve") || (bool)input["chkVolian"]); + } + private void SaveProcsTesting(IDatabase db) + { + foreach(IProcedure ip in db.Procedures) + { + if(ip.Name == "vefn_SplitROSearch" || ip.Name == "ve_GetPath" || ip.Name == "getItemAndChildren") + { + output.writeln(string.Format("Name = '{0}' ",ip.Name)); + output.writeln(string.Format("Schema = '{0}' ",ip.Schema)); + foreach(IParameter param in ip.Parameters) + { + output.writeln(string.Format(" Parameter - {0} = {1}",param.Name,param.ParameterType)); + } + } + } + } private void SaveProcs(IDatabase db) { foreach(IProcedure ip in db.Procedures) { if(ip.Schema != "sys"){ + bool isProc = IsProcedure(ip); + string sType = isProc ? "PROCEDURE" : "FUNCTION"; + string sIsType = isProc ? "Procedure" : (IsTableFunction(ip) ? "TableFunction" : "ScalarFunction"); string sName = ip.Name; if((bool)input["chkDrop"]){ - if(sName.Contains("sp_")==false && sName.Contains("fn_")==false) - output.writeln("Drop procedure [" + sName + "]"); + if(sName.StartsWith("sp_")==false && sName.StartsWith("fn_")==false && IncludeVolian(sName)) + output.writeln("DROP " + sType + " [" + sName + "]"); } else { - if(sName.Contains("sp_")==false && sName.Contains("fn_")==false) + if(sName.StartsWith("sp_")==false && sName.StartsWith("fn_")==false && IncludeVolian(sName)) { %> /****** Object: StoredProcedure [<%=sName%>] ******/ -IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[<%=sName%>]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1) - DROP PROCEDURE [<%=sName%>]; +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[<%=sName%>]') AND OBJECTPROPERTY(id,N'Is<%=sIsType%>') = 1) + DROP <%=sType%> [<%=sName%>]; GO <% @@ -246,8 +269,8 @@ GO %> GO -- Display the status of Proc creation -IF (@@Error = 0) PRINT 'Procedure Creation: <%=sName%> Succeeded' -ELSE PRINT 'Procedure Creation: <%=sName%> Error on Creation' +IF (@@Error = 0) PRINT '<%=sIsType%> Creation: <%=sName%> Succeeded' +ELSE PRINT '<%=sIsType%> Creation: <%=sName%> Error on Creation' GO <% SaveFile(ip.Name); @@ -256,6 +279,14 @@ GO } } } + private bool IsProcedure(IProcedure ip) + { + return ip.ProcedureText.Contains("CREATE PROCEDURE"); + } + private bool IsTableFunction(IProcedure ip) + { + return ip.Parameters[0].Name == "@TABLE_RETURN_VALUE"; + } private void ShowColumns(IColumns cols,int indent,string title) { output.writeln(string.Format("{0}{1}","".PadRight(indent),title)); diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/ItemExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/ItemExt.cs index f3ec03d3..421dd5e5 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/ItemExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/ItemExt.cs @@ -1311,147 +1311,6 @@ namespace VEPROMS.CSLA.Library { _MyContent = new ContentInfo(dr, true); } - #region Insert New Items - public ItemInfo InsertSiblingBefore(string text) - { - return InsertSiblingBefore(text, null); - } - public ItemInfo InsertSiblingBefore(string text, string number) - { - ItemInfo prevItemInfo = MyPrevious; - ItemInfo newItemInfo = null; - PartInfoList partInfoList = null; - if(MyParent != null && MyParent.MyContent != null) - { - MyParent.MyContent.RefreshContentParts(); - partInfoList = MyParent.MyContent.ContentParts; - } - using (Item prevItem = prevItemInfo == null ? null : prevItemInfo.Get()) // Get the previous Item - { - using (Item newItem = Item.MakeItem(prevItem, Content.MakeContent(number, "", MyContent.Type, null, null))) // Create the new Item - { - using (Item thisItem = Get()) // Get the next item in the list - { - thisItem.MyPrevious = newItem; // Point to the new item - thisItem.Save(); // Save Changes - if (prevItem == null) - { - PartInfo partInfo = partInfoList.Find(this); - using (Part part = partInfo.Get()) - { - part.MyItem = newItem; - part.Save(); - } - } - } - // ToDo: Need change PartInfo in PartInfoList - newItemInfo = ItemInfo.Get(newItem.ItemID); - newItemInfo.ResetOrdinal(); - } - } - return newItemInfo; - } - public ItemInfo InsertSiblingAfter(string text) - { - return InsertSiblingAfter(text, null); - } - public ItemInfo InsertSiblingAfter(string text, string number) - { - return InsertSiblingAfter(text, number, MyContent.Type); - } - public ItemInfo InsertSiblingAfter(string text, string number, int? type) - { - ItemInfo nextItemInfo = (NextItemCount > 0) ? NextItems[0] : null; - ItemInfo newItemInfo = null; - using (Item thisItem = Get()) // Get the Current Item - { - using (Item newItem = Item.MakeItem(thisItem, Content.MakeContent(number, text, type, null, null))) // Create the new Item - { - if (nextItemInfo != null) // Simple case, adding to end of list: - using (Item nextItem = nextItemInfo.Get()) // Get the next item in the list - { - nextItem.MyPrevious = newItem; // Point to the new item - nextItem.Save(); // Save Changes - } - // ToDo: Need change PartInfo in PartInfoList - newItemInfo = ItemInfo.Get(newItem.ItemID); - newItemInfo.ResetOrdinal(); - } - } - return newItemInfo; - } - public ItemInfo InsertChild(E_FromType fromType,int type,string text) - { - return InsertChild(fromType,type,text, null); - } - public ItemInfo InsertChild(E_FromType fromType,int type, string text, string number) - { - ItemInfo newItemInfo = null; - using (Item thisItem = Get()) // Get the Current Item - { - using (Item newItem = Item.MakeItem(null, Content.MakeContent(number, text, type, null, null))) // Create the new Item - { - PartInfo partInfo = MyContent.ContentParts == null ? null : MyContent.ContentParts.Find(fromType); - if (partInfo != null) - { - //this could be equivalent to adding a sibling with a specific type - using (Part part = partInfo.Get()) - { - part.MyItem.MyPrevious = newItem; - part.MyItem.Save(); - part.MyItem = newItem; - part.Save(); - } - } - else - { - // This means that a part needs to be added to point to the new item - //using (Part part = Part.MakePart(thisItem.MyContent, )) - //{ ;} - thisItem.MyContent.ContentParts.Add((int)fromType, newItem); - thisItem.Save(); - } - newItemInfo = ItemInfo.Get(newItem.ItemID); - } - } - ResetParts(); - return newItemInfo; - } - public ItemInfo NextItem - { - get - { - if (NextItemCount > 0 && NextItems.Count > 0) - return NextItems[0]; - return null; - } - } - private static void ResetOrdinal(int itemID) - { - bool first = true; - ConvertListToDictionary(); - string key = itemID.ToString(); - if (_CacheByPrimaryKey.ContainsKey(key)) - { - foreach (ItemInfo itm in _CacheByPrimaryKey[key]) - { - itm._Ordinal = null; - //Console.WriteLine("Ordinal {0},{1}",key,itm.MyPrevious == null ? 0 : itm.MyPrevious._Ordinal); - if (first && itm.NextItem != null) - { - ResetOrdinal(itm.NextItem.ItemID); - first = false; - } - } - } - } - private void ResetOrdinal() - { - //_Ordinal = null; - //Console.WriteLine("Ordinal {0},{1}",ItemID,MyPrevious == null ? 0 : MyPrevious.Ordinal); - ResetOrdinal(ItemID); - } - #endregion } #endregion ItemInfo #region ItemInfoList