Various updates to MyGeneration

Moved ItemInsert code to ItemInsertExt.cs
This commit is contained in:
Rich 2009-04-22 13:04:26 +00:00
parent 518c79216a
commit 7f0eb11f47
8 changed files with 871 additions and 601 deletions

View File

@ -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." );
@ -272,6 +272,7 @@ public class GeneratedTemplate : DotNetScriptTemplate
public override void Render()
{
DateTime tStart = DateTime.Now;
if (context.Objects.ContainsKey("DnpUtils"))DnpUtils.SaveInputToCache(context);
try{
InitializeDictionaries();
@ -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}\");";
@ -451,7 +455,7 @@ public class GeneratedTemplate : DotNetScriptTemplate
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)
{
@ -476,7 +480,7 @@ public class GeneratedTemplate : DotNetScriptTemplate
_PropDescList.Add(_className);
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)
{
@ -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<string, <%=_className%>> _AllByPrimaryKey = new Dictionary<string, <%=_className%>>();<%
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<string, List<<%=_className%>>> _CacheByPrimaryKey = new Dictionary<string, List<<%=_className%>>>();<%
//ArrayList uniqueIndexes=UniqueIndexes(tbl);
foreach(IIndex ind in uniqueIndexes)
{
string sBy = FormatColumns("{name}",ind.Columns,"_","");
%>
private static Dictionary<string, <%=_className%>> _AllBy<%=sBy%> = new Dictionary<string, <%=_className%>>();<%
private static Dictionary<string, List<<%=_className%>>> _CacheBy<%=sBy%> = new Dictionary<string, List<<%=_className%>>>();<%
}
%>
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
{
%>
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;
}<%
}
@ -796,7 +820,7 @@ namespace <%=_nameSpace%>
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);
,PropertyName(col),InitializeValue( col ),GetDescription(col),bReadOnly || IsRelObj(col),col.IsInPrimaryKey,false,null,sParentCheck,null,null);
// if (bRelatedObject)
vlnRelObjProperty(col,bReadOnly,false);
}
@ -822,26 +846,26 @@ namespace <%=_nameSpace%>
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);
"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));
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);
//" = 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));
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));
}
}
@ -852,33 +876,83 @@ namespace <%=_nameSpace%>
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));
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 (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<object> list)
{
return base.IsDirty;
}<%
}
else
{
%>
public override bool IsDirty
{
get
{
if ( base.IsDirty )
return true;
return IsDirtyList(new List<object>());
}
}
public bool IsDirtyList(List<object> 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<object> list)
{
return (IsNew && !IsDirty) ? true : base.IsValid;
}<%
}
else
{
%>
public override bool IsValid
{
get { return IsValidList(new List<object>()); }
}
public bool IsValidList(List<object> 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)
@ -902,12 +976,29 @@ namespace <%=_nameSpace%>
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":"");
%>
@ -973,8 +1064,17 @@ namespace <%=_nameSpace%>
%>
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);%><%
}
}
@ -1044,7 +1144,8 @@ namespace <%=_nameSpace%>
private bool _CheckingBrokenRules = false;
public IVEHasBrokenRules HasBrokenRules
{<%=Debug("20070509.vlnValidationRules")%>
get {
get
{
if (_CheckingBrokenRules) return null;
if ((IsDirty || !IsNew) && BrokenRulesCollection.Count > 0) return this;
try
@ -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;
%>
_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 = "";
@ -1351,6 +1484,8 @@ namespace <%=_nameSpace%>
{
BuildLists(reqList,ref sMakeListParamTypes, ref sMakeListParams, ref sSetTmp, ref 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 );
@ -1368,8 +1503,9 @@ namespace <%=_nameSpace%>
{<%=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= "";
@ -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)
@ -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);
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)
@ -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)%>;
}
@ -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();
@ -2173,7 +2326,7 @@ namespace <%=_nameSpace%>
{
//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=", ";
@ -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%>]
@ -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
@ -2949,7 +3101,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get
%>
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%>);
@ -2970,6 +3122,8 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get
}<%
}
}
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<object> 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<object>()); }
}
public bool IsValidList(List<object> 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(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<%
}
@ -3402,7 +3610,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get
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){
sKey+=sep+MemberName(column);
@ -3426,7 +3634,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get
{
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);
}
}
}
@ -3458,12 +3666,13 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get
{
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));
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<%
}
@ -3815,7 +4024,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get
{
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();
}<%
@ -3901,7 +4110,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get
{
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=", ";
@ -4001,7 +4210,7 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get
#region Factory Methods
public static <%=_className%> <%=sMember%> = null;
/// <summary>
/// Return a list of all projects.
/// Return a list of all <%=_subclassName%>.
/// </summary>
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);
}
}
/// <summary>
/// Reset the list of all <%=_subclassName%>.
/// </summary>
public static void Reset()
{
<%=sMember%> = null;
}<%
// ForeignKeys - List Foreign Keys - May want to create stored procedures
%>
@ -4198,12 +4414,25 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get
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;
string sCheck3=null;
if (column.IsNullable)
{
sCheck2=FormatColumn("\r\n\t\t\t\t\t{member} = (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);
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,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)
{
@ -4234,7 +4463,7 @@ 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();
@ -4246,12 +4475,16 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get
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))
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;
/// <summary>
/// Count of <%=sMember.Substring(1)%> for this <%=sParent%>
/// </summary>
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%>
@ -4277,10 +4527,20 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get
get
{
CanReadProperty("<%=sProp%>", true);
if (<%=sCountMember%> > 0 && <%=sMember%> == null)
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))]
@ -4300,8 +4561,11 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get
get
{
CanReadProperty("<%=sProp%>", true);
if (<%=sCountMember%> > 0 && <%=sMember%> == null)
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;
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
@ -4357,38 +4632,47 @@ private void vlnDataPortalFetch(string sPrefix,IColumns cols,string sql,bool get
// 20070326 - Need to add an object reference
string sPrefix = "";
string sTmpKeys2 = sTmpKeys;
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)
{
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;
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)%><%
}
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)
{
%>

View File

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

View File

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

View File

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

View File

@ -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,6 +331,12 @@ public class GeneratedTemplate : DotNetScriptTemplate
_selectedTables = input["chooseTables"] as ArrayList;
dicIndexes = new Hashtable();
dicDrop = new Hashtable();
if((bool)input["chkProc"])
{
ShowProcs(db);
}
else
{
foreach( string _newTable in _selectedTables )
{
_workingTable = MyMeta.Databases[_dbName].Tables[_newTable];
@ -342,6 +353,7 @@ public class GeneratedTemplate : DotNetScriptTemplate
if((bool)input["chkAlias"])ShowAlias( _workingTable );
if((bool)input["chkNames"])ShowNames( _workingTable );
}
}
//foreach(ITable tbl in db.Tables)
//{
// ShowTable3(tbl);
@ -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)

View File

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

View File

@ -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