MyGeneration Templates

This commit is contained in:
Rich 2007-12-06 15:46:56 +00:00
parent df079734df
commit 66dc9ab796
12 changed files with 9172 additions and 0 deletions

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,219 @@
private void ColumnInfoHeader()
{
Write("Container, ");
Write("Name, ");
Write("Alias, ");
Write("AutoKeyIncrement, ");
Write("AutoKeySeed, ");
Write("CharacterMaxLength, ");
Write("CharacterOctetLength, ");
//Write("CharacterSetCatalog, ");
//Write("CharacterSetSchema, ");
Write("CompFlags, ");
Write("DataType, ");
Write("DataTypeName, ");
Write("DataTypeNameComplete, ");
Write("DateTimePrecision, ");
Write("DbTargetType, ");
Write("Default, ");
Write("Description, ");
//Write("Domain, ");
//Write("DomainCatalog, ");
//Write("DomainName, ");
//Write("DomainSchema, ");
Write("Flags, ");
Write("ForeignKeys, ");
//Write("GlobalProperties, ");
//Write("Guid, ");
Write("HasDefault, ");
Write("HasDomain, ");
Write("IsAutoKey, ");
Write("IsComputed, ");
Write("IsInForeignKey, ");
Write("IsInPrimaryKey, ");
Write("IsNullable, ");
Write("LanguageType, ");
Write("LCID, ");
Write("NumericPrecision, ");
Write("NumericScale, ");
Write("Ordinal, ");
//Write("Properties, ");
Write("PropID, ");
Write("SortID, ");
Write("Table, ");
//Write("TDSCollation, ");
//Write("TypeGuid, ");
//Write("UserDataXPath, ");
Write("View\r\n");
}
private void ColumnProps(IColumn column)
{
WriteProp("",(column.Table==null?"view: " + column.View.Name:column.Table.Name),"");
WriteProp(column.Name);
WriteProp(column.Alias);
WriteProp(column.AutoKeyIncrement);
WriteProp(column.AutoKeySeed);
WriteProp(column.CharacterMaxLength);
WriteProp(column.CharacterOctetLength);
//WriteProp(column.CharacterSetCatalog);
//WriteProp(column.CharacterSetSchema);
WriteProp(column.CompFlags);
WriteProp(column.DataType);
WriteProp(column.DataTypeName);
WriteProp(column.DataTypeNameComplete);
WriteProp(column.DateTimePrecision);
WriteProp(column.DbTargetType);
WriteProp(column.Default);
WriteProp(column.Description);
//WriteProp(column.Domain);
//WriteProp(column.DomainCatalog);
//WriteProp(column.DomainName);
//WriteProp(column.DomainSchema);
WriteProp(column.Flags);
WriteProp(column.ForeignKeys.Count);
//WriteProp(column.GlobalProperties);
//WriteProp(column.Guid);
WriteProp(column.HasDefault);
WriteProp(column.HasDomain);
WriteProp(column.IsAutoKey);
WriteProp(column.IsComputed);
WriteProp(column.IsInForeignKey);
WriteProp(column.IsInPrimaryKey);
WriteProp(column.IsNullable);
WriteProp(column.LanguageType);
WriteProp(column.LCID);
WriteProp(column.NumericPrecision);
WriteProp(column.NumericScale);
WriteProp(column.Ordinal);
//WriteProp(column.Properties);
WriteProp(column.PropID);
WriteProp(column.SortID);
WriteProp(column.Table);
//WriteProp(column.TDSCollation);
//WriteProp(column.TypeGuid);
//WriteProp(column.UserDataXPath);
WriteProp("",column.View,"\r\n");
}
private void ColumnInfo(IColumn column)
{
WriteLine("\t\tContainer {0}",(column.Table==null?"view: " + column.View.Name:column.Table.Name));
WriteLine("\t\tName {0}",column.Name);
WriteLine("\t\tAlias {0}",column.Alias);
WriteLine("\t\tAutoKeyIncrement {0}",column.AutoKeyIncrement);
WriteLine("\t\tAutoKeySeed {0}",column.AutoKeySeed);
WriteLine("\t\tCharacterMaxLength {0}",column.CharacterMaxLength);
WriteLine("\t\tCharacterOctetLength {0}",column.CharacterOctetLength);
//WriteLine("\t\tCharacterSetCatalog {0}",column.CharacterSetCatalog);
//WriteLine("\t\tCharacterSetSchema {0}",column.CharacterSetSchema);
WriteLine("\t\tCompFlags {0}",column.CompFlags);
WriteLine("\t\tDataType {0}",column.DataType);
WriteLine("\t\tDataTypeName {0}",column.DataTypeName);
WriteLine("\t\tDataTypeNameComplete {0}",column.DataTypeNameComplete);
WriteLine("\t\tDateTimePrecision {0}",column.DateTimePrecision);
WriteLine("\t\tDbTargetType {0}",column.DbTargetType);
WriteLine("\t\tDefault {0}",column.Default);
WriteLine("\t\tDescription {0}",column.Description);
//WriteLine("\t\tDomain {0}",column.Domain);
//WriteLine("\t\tDomainCatalog {0}",column.DomainCatalog);
//WriteLine("\t\tDomainName {0}",column.DomainName);
//WriteLine("\t\tDomainSchema {0}",column.DomainSchema);
WriteLine("\t\tFlags {0}",column.Flags);
WriteLine("\t\tForeignKeys {0}",column.ForeignKeys);
//WriteLine("\t\tGlobalProperties {0}",column.GlobalProperties);
//WriteLine("\t\tGuid {0}",column.Guid);
WriteLine("\t\tHasDefault {0}",column.HasDefault);
WriteLine("\t\tHasDomain {0}",column.HasDomain);
WriteLine("\t\tIsAutoKey {0}",column.IsAutoKey);
WriteLine("\t\tIsComputed {0}",column.IsComputed);
WriteLine("\t\tIsInForeignKey {0}",column.IsInForeignKey);
WriteLine("\t\tIsInPrimaryKey {0}",column.IsInPrimaryKey);
WriteLine("\t\tIsNullable {0}",column.IsNullable);
WriteLine("\t\tLanguageType {0}",column.LanguageType);
WriteLine("\t\tLCID {0}",column.LCID);
WriteLine("\t\tNumericPrecision {0}",column.NumericPrecision);
WriteLine("\t\tNumericScale {0}",column.NumericScale);
WriteLine("\t\tOrdinal {0}",column.Ordinal);
//WriteLine("\t\tProperties {0}",column.Properties);
WriteLine("\t\tPropID {0}",column.PropID);
WriteLine("\t\tSortID {0}",column.SortID);
WriteLine("\t\tTable {0}",column.Table);
//WriteLine("\t\tTDSCollation {0}",column.TDSCollation);
//WriteLine("\t\tTypeGuid {0}",column.TypeGuid);
//WriteLine("\t\tUserDataXPath {0}",column.UserDataXPath);
WriteLine("\t\tView {0}",column.View);
}
private void ColumnFormatHeader()
{
Write("member,");
Write("fmember,");
Write("pmember,");
Write("local,");
Write("prop,");
Write("memberprop,");
Write("@,");
Write("@new,");
Write("ctype,");
Write("rmember,");
Write("rtype,");
// Write("dbtype,");
Write("name,");
Write("class,");
Write("fname,");
Write("sqltype,");
Write("?ref,");
Write("?dbtype,");
Write("?dbprefix,");
Write("?dbsuffix,");
Write("?dbsuff,");
Write("default\r\n");
}
private void ColumnFormat(IColumn column)
{
Write(FormatColumn("\"{member}\",",column));
Write(FormatColumn("\"{fmember}\",",column));
Write(FormatColumn("\"{pmember}\",",column));
Write(FormatColumn("\"{local}\",",column));
Write(FormatColumn("\"{prop}\",",column));
Write(FormatColumn("\"{memberprop}\",",column));
Write(FormatColumn("\"{@}\",",column));
Write(FormatColumn("\"{@new}\",",column));
Write(FormatColumn("\"{ctype}\",",column));
Write(FormatColumn("\"{rmember}\",",column));
Write(FormatColumn("\"{rtype}\",",column));
// Write(FormatColumn("\"{dbtype}\",",column));
Write(FormatColumn("\"{name}\",",column));
Write(FormatColumn("\"{class}\",",column));
Write(FormatColumn("\"{fname}\",",column));
Write(FormatColumn("\"{sqltype}\",",column));
Write(FormatColumn("\"{?ref}\",",column));
Write(FormatColumn("\"{?dbtype}\",",column));
Write(FormatColumn("\"{?dbprefix}\",",column));
Write(FormatColumn("\"{?dbsuffix}\",",column));
Write(FormatColumn("\"{?dbsuff}\",",column));
Write(FormatColumn("\"{default}\"\r\n",column));
}
private void ColumnFormatNew(IColumn column)
{
Write(FormatColumnNew("\"{member}\",",column));
Write(FormatColumnNew("\"{fmember}\",",column));
Write(FormatColumnNew("\"{pmember}\",",column));
Write(FormatColumnNew("\"{local}\",",column));
Write(FormatColumnNew("\"{prop}\",",column));
Write(FormatColumnNew("\"{memberprop}\",",column));
Write(FormatColumnNew("\"{@}\",",column));
Write(FormatColumnNew("\"{@new}\",",column));
Write(FormatColumnNew("\"{ctype}\",",column));
Write(FormatColumnNew("\"{rmember}\",",column));
Write(FormatColumnNew("\"{rtype}\",",column));
// Write(FormatColumnNew("\"{dbtype}\",",column));
Write(FormatColumnNew("\"{name}\",",column));
Write(FormatColumnNew("\"{class}\",",column));
Write(FormatColumnNew("\"{fname}\",",column));
Write(FormatColumnNew("\"{sqltype}\",",column));
Write(FormatColumnNew("\"{?ref}\",",column));
Write(FormatColumnNew("\"{?dbtype}\",",column));
Write(FormatColumnNew("\"{?dbprefix}\",",column));
Write(FormatColumnNew("\"{?dbsuffix}\",",column));
Write(FormatColumnNew("\"{?dbsuff}\",",column));
Write(FormatColumnNew("\"{default}\"\r\n",column));
}

View File

@ -0,0 +1,534 @@
#region FilteredColumns
// Used by CSLA Objects Guid
public bool IsGuid(IColumn column){
return(column.LanguageType=="timestamp");}
public ArrayList Guid(IColumns columns){
return FilteredColumns(columns,new Filter(IsGuid));}
// Used in CSLA Business Objects AutoKey
public bool AutoKey(IColumn column){
return(column.IsAutoKey);}
public ArrayList AutoKey(IColumns columns){
return FilteredColumns(columns,new Filter(AutoKey));}
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);}
return l;}
// Used in CSLA Stored Procedures
private ArrayList AutoKey(ITable tbl){
return FilteredColumns(tbl.Columns,new Filter(AutoKey));}
// Used in CSLA Stored Procedures Updatable
public bool Updatable(IColumn column){
return(!NotUpdatable(column));}
private ArrayList Updatable(ITable tbl){
return FilteredColumns(tbl.Columns,new Filter(Updatable));}
// Used in CSLA Stored Procedures Not Updatable
public bool NotUpdatable(IColumn column){
return(column.IsInPrimaryKey || column.IsAutoKey || column.IsComputed);}
private ArrayList NotUpdatable(ITable tbl){
return FilteredColumns(tbl.Columns,new Filter(NotUpdatable));}
// Used in CSLA Stored Procedures PrimaryKey
public bool PrimaryKey(IColumn column){
return(column.IsInPrimaryKey);}
private ArrayList PrimaryKey(ITable tbl){
return FilteredColumns(tbl.Columns,new Filter(PrimaryKey));}
// Used in CSLA Stored Procedures Insertable
public bool Insertable(IColumn column){
return(!NotInsertable(column));}
private ArrayList Insertable(ITable tbl){
return FilteredColumns(tbl.Columns,new Filter(Insertable));}
// Used in CSLA Stored Procedures Not Insertable
public bool NotInsertable(IColumn column){
return(column.IsAutoKey || column.IsComputed);}
private ArrayList NotInsertable(ITable tbl){
return FilteredColumns(tbl.Columns,new Filter(NotInsertable));}
// Used in CSLA Stored Procedures & CSLA Business Objects Computed
public bool Computed(IColumn column){
return(column.IsComputed);}
private ArrayList Computed(ITable tbl){
return FilteredColumns(tbl.Columns,new Filter(Computed)); }
// Used in CSLA Stored Procedures Not TimeStamp
public bool NotTimestamp(IColumn column){
return(!Timestamp(column));}
private ArrayList NotTimestamp(ITable tbl){
return FilteredColumns(tbl.Columns,new Filter(NotTimestamp));}
private ArrayList NotTimestamp(IColumns cols){
return FilteredColumns(cols,new Filter(NotTimestamp));}
// Used in CSLA Business Objects
public bool IsRequired(IColumn column)
{
if(column.IsNullable) return false;
if(!column.HasDefault) return true;
// If it is the parent column it is required
return IsParentColumn(column);
// return false;
}
// public bool ForeignKey(IColumn column)
// {
// return(column.IsInForeignKey);
// }
// Used in CSLA Business Objects Automatic
public bool IsAutomatic(IColumn column)
{
bool retval=column.Description.IndexOf("{auto}") >= 0;
return retval;
}
// Used in CSLA Business Objects TimeStamp
public bool Timestamp(IColumn column){
return(column.DataTypeName=="timestamp");}
public ArrayList IsTimestamp(IColumns columns){
return FilteredColumns(columns,new Filter(Timestamp));}
// Used in CSLA Stored Procedures and Business Objects
public ArrayList FilteredColumns(IColumns columns,Filter f){
ArrayList l = new ArrayList();
foreach(IColumn column in columns)
{
if(f(column))l.Add(column);
}
return l;
}
// Used in CSLA Business Objects
public ArrayList ExcludedColumns(IColumns columns,Filter f){
ArrayList l = new ArrayList();
foreach(IColumn column in columns)
{
if(!f(column))l.Add(column);
}
return l;
}
private int CountRequiredFields( IColumns Columns ){
return Columns.Count - CountNullableFields( Columns );}
private int CountNullableFields( IColumns Columns )
{
int i = 0;
foreach( IColumn c in Columns )
{
if( c.IsNullable )
{
i++;
}
}
return i;
}
private int CountUniqueFields( IColumns Columns )
{
int i = 0;
foreach( IColumn c in Columns )
{
if( !c.IsNullable && c.IsInPrimaryKey )
{
i++;
}
}
return i;
}
public ArrayList MakeList(IColumns columns)
{
ArrayList l = new ArrayList();
foreach(IColumn column in columns)
if(!column.IsAutoKey && !IsAutomatic(column) && !column.IsComputed)
l.Add(column);
return l;
}
public ArrayList MakeList4(IColumns columns)
{
ArrayList l = new ArrayList();
foreach(IColumn column in columns)
if((!column.IsAutoKey && !IsAutomatic(column) && !column.IsComputed ) &&
(column.HasDefault==false || column.ForeignKeys.Count != 0))
l.Add(column);
return l;
}
public ArrayList ReqList(IColumns columns)
{
ArrayList l = new ArrayList();
foreach(IColumn column in columns)
if(IsRequired(column) && !column.IsComputed && !column.IsAutoKey)
l.Add(column);
return l;
}
public ArrayList ReqListNoDefault(IColumns columns)
{
ArrayList l = new ArrayList();
foreach(IColumn column in columns)
if(IsRequired(column) && !column.IsComputed && !column.IsAutoKey && column.HasDefault)
l.Add(column);
return l;
}
public ArrayList MakeList2(IColumns columns)
{
ArrayList l = new ArrayList();
foreach(IColumn column in columns)
if(!column.IsAutoKey && !column.IsComputed)
l.Add(column);
return l;
}
public ArrayList MakeList3(IColumns columns)
{
ArrayList l = new ArrayList();
foreach(IColumn column in columns)
if(IsAutomatic(column))
l.Add(column);
return l;
}
public void BuildLists(IList cols,ref string sMakeListParamTypes, ref string sMakeListParams,
ref string sSetTmp, ref string sParentCheck)
{
string sep = "";
string sepSet = "";
string sPrefixType="";
string sPrefix="";
string sPrefixSet="";
string sCheckSep = "if( ";
sMakeListParamTypes = "";
sMakeListParams = "";
sSetTmp = "";
sParentCheck="";
// ArrayList parentCols = new ArrayList();
foreach(IColumn col in cols)
{
sMakeListParamTypes += sep + FormatColumn("{!rtype} {!local}",col);
sMakeListParams += sep + FormatColumn("{!local}",col);
sSetTmp += sepSet + FormatColumn("\t\t\ttmp.{!memberprop} = {!local};",col);
sep=", ";
sepSet="\r\n";
if(IsRelObj(col)) // If item is null, don't look it up
{
sParentCheck += sCheckSep + LocalName(RelObjProp(col)) + " != null ";
sCheckSep = "|| ";
}
}
if(sParentCheck != "")sParentCheck += ") ";
sMakeListParamTypes = sPrefixType + sMakeListParamTypes;
sMakeListParams = sPrefix + sMakeListParams;
sSetTmp = sPrefixSet + sSetTmp;
//sParentCheck=FormatColumns("{!rtype} {!local} = {autoseed};\r\n\t\t\tif (parent != null)\r\n\t\t\t{\r\n\t\t\t\t{!local} = parent;\r\n\t\t\t}\r\n\t\t\t",parentCols,"\r\n","");
//sParentCheck="";
}
public bool SameList(IList lst1, IList lst2)
{
ArrayList l = new ArrayList();
foreach(IColumn col in lst1)l.Add(col.Name);
foreach(IColumn col in lst2)
if(l.Contains(col.Name))l.Remove(col.Name);
else return false;
return l.Count ==0;
}
public string SameList2(IList lst1, IList lst2)
{
ArrayList l = new ArrayList();
foreach(IColumn col in lst1)l.Add(col.Name);
foreach(IColumn col in lst2)l.Remove(col.Name);
string sList="";
string sep="Difference: ";
foreach(string ss in l){
sList+=sep+ss;
sep=", ";
}
return sList;
}
public bool SameTypes(IList lst1, IList lst2)
{
if(lst1.Count != lst2.Count) return false;
for(int i=0;i<lst1.Count;i++)
{
IColumn col1 = (IColumn)(lst1[i]);
IColumn col2 = (IColumn)(lst2[i]);
if(CSLAType(col1)!=CSLAType(col2))
return false;
}
return true;
}
public string FieldName(IColumn col)
{
return col.Table.Name + "." + col.Name;
}
public bool SameFields(IList lst1, IList lst2)
{
if(lst1.Count != lst2.Count) return false;
for(int i=0;i<lst1.Count;i++)
{
IColumn col1 = (IColumn)(lst1[i]);
IColumn col2 = (IColumn)(lst2[i]);
if(FieldName(col1)!=FieldName(col2))
return false;
}
return true;
}
// public ArrayList IsNotAutoKey(IColumns columns)
// {
// return ExcludedColumns(columns,new Filter(AutoKey));
// }
// public bool TypeString(IColumn column)
// {
// return(CSLAType(column)=="string");
// }
public bool HasDefault(IColumn column)
{
return column.HasDefault;
}
public ArrayList HasDefaults(IColumns columns)
{
return FilteredColumns(columns,new Filter(HasDefault));
}
public ArrayList HasDefaults(IForeignKey fk)
{
ArrayList l = new ArrayList();
foreach(IColumn column in fk.ForeignTable.Columns)
{
if(column.HasDefault && !IsIn(column,fk.ForeignColumns))l.Add(column);
}
return l;
}
private string RelatedObject(IForeignKey fk, IColumn column){
if(column.ForeignKeys.Count == 1){
IForeignKey pk = column.ForeignKeys[0];
string sObj = _nameSpace + "." + ClassName( pk.PrimaryTable );
return FormatColumn(sObj + ".Get" + "({local})",column);
}
else
{
return FormatColumn("{local}",column);
}
}
private string RelatedObjectType(IColumn column){
if(column.ForeignKeys.Count == 1){
IForeignKey pk = column.ForeignKeys[0];
string sObj = ClassName( pk.PrimaryTable );
return sObj + " " + LocalName(sObj);
}
else
{
return FormatColumn("{ctype} {local}",column);
}
}
public string GetNewAlias2(IForeignKey fk,IForeignKey pk)
{
// First determine if there are more than one key linking two tables
int iCount = 0;
foreach(IForeignKey tk in fk.ForeignTable.ForeignKeys)
{
// WriteLine("fk {0} pk {1} pk.PrimaryTable.Name {2} pk.ForeignTable.Name {3} fk.ForeignTable.Name {4}",
// fk.Name,pk.Name,pk.PrimaryTable.Name,pk.ForeignTable.Name,fk.ForeignTable.Name);
if(tk.PrimaryTable == pk.PrimaryTable)iCount++;
}
if(iCount==0)return "";
return pk.ForeignColumns[0].Name;
}
public string GetNewAlias(IForeignKey fk,IForeignKey pk)
{
// First determine if there are more than one key linking two tables
int iCount = 0;
// WriteLine("fk {0} fk.Primary {1} fk.Foreign {2}",fk.Name,fk.PrimaryTable.Name,fk.ForeignTable.Name);
// WriteLine(" pk {0} pk.Primary {1} pk.Foreign {2}",pk.Name,pk.PrimaryTable.Name,pk.ForeignTable.Name);
foreach(IForeignKey tk in fk.ForeignTable.ForeignKeys)
{
if(tk.ForeignTable == pk.ForeignTable && tk.PrimaryTable == pk.PrimaryTable){
// WriteLine(" tk {0} tk.Primary {1} tk.Foreign {2}",tk.Name,tk.PrimaryTable.Name,tk.ForeignTable.Name);
iCount++;
}
}
if(iCount==1)return "";
// WriteLine("iCount {0}",iCount);
return pk.ForeignColumns[0].Name;
}
private string RelatedObjectType2(IForeignKey fk,IColumn column){
if(column.ForeignKeys.Count == 1){
IForeignKey pk = column.ForeignKeys[0];
string sObj = ClassName( pk.PrimaryTable );
//return sObj + " " + LocalName(sObj) + column.Name;
return sObj + " " + LocalName(sObj) + GetNewAlias(fk,pk);
}
else
{
return FormatColumn("{ctype} {local}",column);
}
}
private bool IsPrimaryKey(IColumn col)
{
return (col.IsInPrimaryKey && col.Table.PrimaryKeys.Count == 1);
}
private IForeignKey RelObjFK(IColumn col)
{
//if(!col.IsComputed && !col.IsAutoKey && !IsPrimaryKey(col) && col.ForeignKeys.Count==1)
if(!col.IsComputed && !col.IsAutoKey && col.ForeignKeys.Count==1) // 20071023 - And One To One
{
IForeignKey fk = col.ForeignKeys[0];
// if(fk.PrimaryTable.Name != fk.ForeignTable.Name)
// {
// return (col.Name=="RangeID"?fk:null);
return fk;
// }
}
return null;
}
private bool IsRelObj(IColumn col)
{
if(col.Table.Name != _workingTable.Name && col.IsInPrimaryKey && col.Table.PrimaryKeys.Count ==1)
return true;
IForeignKey fk = RelObjFK(col);
if(fk != null)
return true;
else
return false;
}
private string RelObjType(IColumn col)
{
if(col.Table.Name != _workingTable.Name && col.IsInPrimaryKey && col.Table.PrimaryKeys.Count ==1)
return ClassName( col.Table );
IForeignKey fk = RelObjFK(col);
if(fk != null)
return ClassName( fk.PrimaryTable );
else
return CSLAType(col);
}
private string RelObjProp(IColumn col)
{
if(col.Table.Name != _workingTable.Name && col.IsInPrimaryKey && col.Table.PrimaryKeys.Count ==1)
return "My" + ClassName( col.Table );
IForeignKey fk = RelObjFK(col);
if(fk != null)
if(fk.PrimaryTable.Name == fk.ForeignTable.Name)
return "My" + ParentName(fk) + GetNewAlias(fk,fk);
else
return "My" + ClassName( fk.PrimaryTable ) + GetNewAlias(fk,fk);
else
return PropertyName(col);
}
private string RelObjCol(IColumn col)
{
IForeignKey fk = RelObjFK(col);
if(fk != null)
return PropertyName(fk.PrimaryColumns[0]);
else
return PropertyName(col);
}
private IColumn RelObjCol2(IColumn col)
{
IForeignKey fk = RelObjFK(col);
if(fk != null)
return fk.PrimaryColumns[0];
else
return col;
}
private string RelObjEmpty(IColumn col)
{
IForeignKey fk = RelObjFK(col);
if(col.IsNullable)return "null";
if(fk != null && fk.PrimaryTable.Name == fk.ForeignTable.Name)
return MemberName(fk.PrimaryColumns[0]);
if(CSLAType(col)=="string")return "null";
return "0";
}
private string RelObjTypeCast(IColumn col)
{
IForeignKey fk = RelObjFK(col);
if(col.IsNullable)return "(" + CSLAType(col,"") + ")";
return "";
}
private ArrayList _TableStack = new ArrayList();
private void PushTable(ITable tbl)
{
_TableStack.Add(_workingTable);
_workingTable=tbl;
}
private void PopTable()
{
if(_TableStack.Count > 0)
{
_workingTable=(ITable) _TableStack[_TableStack.Count-1];
_TableStack.RemoveAt(_TableStack.Count-1);
}
}
private bool ForeignRequired(IForeignKey pk)
{
bool bRequired=true;
foreach(IColumn col in pk.ForeignColumns)
bRequired &= !col.IsNullable;
return bRequired;
}
private bool ForeignPrimary(IForeignKey fk)
{
bool bPrimary=true;
foreach(IColumn col in fk.ForeignColumns)
{
bPrimary &= col.IsInPrimaryKey;
}
return bPrimary;
}
public int FindColumn(IList cols, IColumn col)
{
for(int i=0;i<cols.Count;i++)
if(((IColumn) cols[i]).Name==col.Name)
return i;
return -1;
}
public ArrayList FindUniqueChildren(IForeignKey fk){
ArrayList retval = new ArrayList();
foreach(IIndex ind in fk.ForeignTable.Indexes)
{
if(ind.Unique)
{
ArrayList uniqueColumns = new ArrayList();
foreach(IColumn col in ind.Columns)
{
uniqueColumns.Add(col);
}
foreach(IColumn col in fk.ForeignColumns)
{
int ii = FindColumn(uniqueColumns,col);
if(ii >= 0)
{
uniqueColumns.RemoveAt(ii);
}
else
{
uniqueColumns.Clear();
}
}
if(uniqueColumns.Count > 0)// This is a uniqueIndex which includes the parent columns
{
//ShowColumns(uniqueColumns,4,"Unique Index " + ind.Name);
retval.Add(uniqueColumns);
}
}
}
return retval;
}
public bool ContainsList(IList lst1, IList lst2)
{
foreach(IColumn col in lst2)
if(FindColumn(lst1,col)<0)return false;
return true;
}
public IList FindUnique(ArrayList lst, IList cols)
{
foreach(IList lstcols in lst)
{
if(ContainsList(cols,lstcols))return lstcols;
}
return null;
}
//public ArrayList zzFilteredColumnsAny(IColumns columns,Filter [] fs){
// ArrayList l = new ArrayList();
// foreach(IColumn column in columns)
// {
// bool check = false;
// foreach(Filter f in fs)check |= f(column);
// if(check)l.Add(column);
// }
// return l;
//}
//public ArrayList zzExcludedColumnsAny(IColumns columns,Filter [] fs){
// ArrayList l = new ArrayList();
// foreach(IColumn column in columns)
// {
// bool check = false;
// foreach(Filter f in fs)check |= f(column);
// if(!check)l.Add(column);
// }
// return l;
//}
#endregion

View File

@ -0,0 +1,206 @@
// Foreign Key Processing
public delegate void ProcessFK(IForeignKey fk,string alias);
public string ParentName(IForeignKey fk)
{
if(fk == null)return "Parent";
string sKey = fk.ForeignColumns[0].Name;
if(sKey.StartsWith("Prev") || sKey.StartsWith("Prv"))return "Previous";
if(sKey.StartsWith("Next") || sKey.StartsWith("Nxt"))return "Next";
return "Parent";
}
public string ChildName(IForeignKey fk)
{
string sKey = fk.ForeignColumns[0].Name;
if(sKey.StartsWith("Prev") || sKey.StartsWith("Prv"))return "Next";
if(sKey.StartsWith("Next") || sKey.StartsWith("Nxt"))return "Previous";
return "Child";
}
public string ChildrenName(IForeignKey fk)
{
string sKey = fk.ForeignColumns[0].Name;
if(sKey.StartsWith("Prev") || sKey.StartsWith("Prv"))return "Next";
if(sKey.StartsWith("Next") || sKey.StartsWith("Nxt"))return "Previous";
return "Children";
}
public string GetAlias(Hashtable hTbl,ITable tbl)
{
string sAlias = tbl.Alias;
if(!hTbl.Contains(sAlias))
{
hTbl[sAlias]=0;
return "";
}
// WriteLine("-- Hashtable count = {0}, TableName = [{1}]",hTbl.Count,tbl.Name);
int iAlias = 1+ (int)hTbl[sAlias];
hTbl[sAlias]=iAlias;
// return "_" + iAlias.ToString();
return "_" + "ABCDEFGHIJKLMNOP".Substring(iAlias,1);
}
public string GetAlias(IForeignKey fk)
{
if(fk.PrimaryTable.Name == fk.ForeignTable.Name)return "";
// First I need to check to see if there are more than one Foreign Keys pointing to the same Primary Table
int count=0;
foreach(IForeignKey fk1 in fk.ForeignTable.ForeignKeys)
{
if(fk1.PrimaryTable.Name == fk.PrimaryTable.Name) count++;
}
if(count > 1)
return FormatColumns("_{prop}",fk.ForeignColumns,"","");
return "";
}
public void ProcessFKAlias(ITable tbl,ProcessFK pfk)
{
Hashtable dicByNames = new Hashtable();
foreach(ForeignKey fk in tbl.ForeignKeys)
{
if(fk.ForeignTable == tbl)
{
pfk(fk,GetAlias(dicByNames,fk.PrimaryTable));
}
}
}
private bool IsPrimaryKey(IForeignKey fk)
{
// bool retval=true;
// foreach(IColumn c in fk.ForeignColumns)retval &= c.IsInPrimaryKey;
return SameList(fk.ForeignTable.PrimaryKeys,fk.ForeignColumns);
// return retval;
// return IsPrimaryKey(fk.ForeignColumns);
}
private bool IsPrimaryKey1(IForeignKey fk)
{
// bool retval=true;
// foreach(IColumn c in fk.ForeignColumns)retval &= c.IsInPrimaryKey;
return SameList(fk.PrimaryTable.PrimaryKeys,fk.PrimaryColumns);
// return retval;
// return IsPrimaryKey(fk.ForeignColumns);
}
private string ColumnList(IColumns cols)
{
string retval="";
string sep = "";
foreach(IColumn col in cols)
{
retval += sep + col.Name;
sep = ", ";
}
return retval;
}
private bool IsPrimaryKey(IColumns cols)
{
ITable tbl = cols[0].Table;
int match = tbl.PrimaryKeys.Count;
foreach(IColumn col in cols)
{
if(col.Table.Name != tbl.Name)
{
// WriteLine("Table Mismatch - {0},{1}",col.Table.Name,tbl.Name);
return false; // If it points to multiple tables, it is not a primary key
}
if(col.IsInPrimaryKey)match --;
else
{
// WriteLine("Not In Primary Key {0} in {1} ({2})",col.Name, tbl.Name, ColumnList(tbl.PrimaryKeys));
return false;
}
}
// WriteLine("Match = {0}",match);
return match==0;
}
private bool IsPrimaryKey(IColumns cols1,IColumns cols2)
{
ITable tbl = cols1[0].Table;
int match = tbl.PrimaryKeys.Count;
foreach(IColumn col in cols1)
{
if(col.Table.Name != tbl.Name)
{
// WriteLine("Table Mismatch - {0},{1}",col.Table.Name,tbl.Name);
return false; // If it points to multiple tables, it is not a primary key
}
if(col.IsInPrimaryKey)match --;
else
{
// WriteLine("Not In Primary Key {0} in {1} ({2})",col.Name, tbl.Name, ColumnList(tbl.PrimaryKeys));
return false;
}
}
// WriteLine("Match = {0}",match);
foreach(IColumn col in cols2)
{
if(col.Table.Name != tbl.Name)
{
// WriteLine("Table Mismatch - {0},{1}",col.Table.Name,tbl.Name);
return false; // If it points to multiple tables, it is not a primary key
}
if(col.IsInPrimaryKey)match --;
else
{
// WriteLine("Not In Primary Key {0} in {1} ({2})",col.Name, tbl.Name, ColumnList(tbl.PrimaryKeys));
return false;
}
}
// WriteLine("Match = {0}",match);
return match==0;
}
private bool ManyToMany(ITable tbl,IForeignKey fk,IForeignKey pk)
{
if(tbl != fk.PrimaryTable)return false;// It should be the Primary Table
if(tbl == pk.PrimaryTable)return false;// It should not loop back to the Primary Table
if(fk.PrimaryTable == fk.ForeignTable)return false;// Ignore Parent/Child relationships
if(pk.PrimaryTable == pk.ForeignTable)return false;// Ignore Parent/Child relationships
// Now for the detail check - the primary columns in each foreign key should be the primary key in the primary table
// WriteLine("Checking Primary Keys - {0}",tbl.Name);
if(!IsPrimaryKey(fk.PrimaryColumns))return false;
if(!IsPrimaryKey(pk.PrimaryColumns))return false;
// And the foreign columns from both foreign keys should be the primary key in the foreigntable
// WriteLine("Checking Foreign Keys - {0}",tbl.Name);
if(!IsPrimaryKey(fk.ForeignColumns,pk.ForeignColumns))return false;
return true;
}
private bool OneToOne(ITable tbl)
{
// Check to see if the Primary Key is also the Foreign Part of a Foreign Key
foreach(IColumn col in tbl.PrimaryKeys)
{
if(IsPrimaryKey(col))
{
foreach(IForeignKey fk in col.ForeignKeys)
{
//WriteLine("{0} {1} {2} {3} {4}",fk.Name,fk.PrimaryTable.Name,fk.ForeignTable.Name,
//fk.ForeignTable.Name == tbl.Name, fk.PrimaryTable.Name != tbl.Name);
if(fk.ForeignTable.Name == tbl.Name && fk.PrimaryTable.Name != tbl.Name )
return true;
}
}
}
return false;
}
private bool AnyNotOneToOne(ITable tbl)
{
bool retval = true;
foreach(IForeignKey fk in tbl.ForeignKeys)
{
if(fk.ForeignTable == tbl)
{
if(!OneToOne(fk))return true;
//WriteLine("{0} {1} {2} {3} {4}",fk.Name,fk.PrimaryTable.Name,fk.ForeignTable.Name,
// fk.ForeignTable.Name == tbl.Name, fk.PrimaryTable.Name != tbl.Name);
retval = false;
}
}
return retval;
}
private bool OneToOne(IForeignKey fk1)
{
ITable tbl=fk1.ForeignTable; // Check to see if the Primary Key is also the Foreign Part of a Foreign Key
// WriteLine("{0} {1} {2} {3} {4}",fk1.Name,fk1.PrimaryTable.Name,fk1.ForeignTable.Name,
// fk1.ForeignTable.Name == tbl.Name, fk1.PrimaryTable.Name != tbl.Name);
foreach(IColumn col in fk1.ForeignColumns)
{
// WriteLine("Column {0} Primary {1}",col.Name,IsPrimaryKey(col));
if(!IsPrimaryKey(col))return false;
}
return true;
}

View File

@ -0,0 +1,519 @@
//// FormatColumns
// private string FormatColumnOld(string sFormat,IColumn column,string sAlias)
// {
// string s=sFormat;
// s=s.Replace("{member}",ColumnToMemberVariable(column));//m - Member _firstname
// s=s.Replace("{fmember}",(column.Table.Name==_workingTable.Name?"":"_" + ToClassName(column.Table.Name).ToLower() + sAlias)+ColumnToMemberVariable(column));//m - Member _firstname
// s=s.Replace("{pmember}",(column.Table.Name==_workingTable.Name?"":ToClassName(column.Table.Name).ToLower() + sAlias)+"."+ColumnToPropertyName(column));//m - Member _firstname
// s=s.Replace("{local}",ColumnToMemberVariable(column).Substring(1));//l Local firstname
// s=s.Replace("{prop}",ColumnToPropertyName(column));
// s=s.Replace("{memberprop}",(column.IsInPrimaryKey ? ColumnToMemberVariable(column) : ColumnToPropertyName(column)));
// s=s.Replace("{@}",ColumnToParameterName(column));
// s=s.Replace("{@new}",ColumnToNewParameterName(column));
// string cType = ColumnToCSLAType(column);
// s=s.Replace("{ctype}",cType);
// s=s.Replace("{rmember}",vlnReturnMember(cType));
// s=s.Replace("{rtype}",vlnReturnType(cType));
//// s=s.Replace("{dbtype}",ColumnToMemberVariable(column).Substring(1));
// s=s.Replace("{name}",column.Name);
// s=s.Replace("{class}",ToClassName(column.Table.Alias.Replace( " ", "" )));
// s=s.Replace("{fname}",(column.Table.Name==_workingTable.Name?"":column.Table.Name.Replace(" ","")+sAlias+"_")+column.Name);
// s=s.Replace("{sqltype}",ColumnToSQLDbType(column));
// s=s.Replace("{?ref}",(column.IsComputed || column.IsAutoKey ? "ref " : ""));
// s=s.Replace("{?dbtype}",(ColumnToCSLAType( column )=="SmartDate" ? ".DBValue" : ""));
// s=s.Replace("{?dbprefix}",(ColumnToCSLAType( column )=="SmartDate" ? "new SmartDate(" : ""));
// s=s.Replace("{?dbsuffix}",(ColumnToCSLAType( column )=="SmartDate" ? ").DBValue" : ""));
// s=s.Replace("{?dbsuff}",(ColumnToCSLAType( column )=="SmartDate" ? ")" : ""));
// s=s.Replace("{default}",ColumnDefault(column));
// //s=s.Replace("{xxx}","");
// return s;
// }
// private string FormatColumnOld(string sFormat,IColumn column)
// {
// return FormatColumn(sFormat,column,"");
// }
// private string ColumnToSQLDbType(IColumn column)
// {
// switch(column.DataTypeName)
// {
// case "timestamp":
// return "SqlDbType.Timestamp";
// case "int":
// return "SqlDbType.Int";
// default:
// //return "//TODO: Need to fix ColumnToSQLDbType" + " " + column.DataType + " " + column.DataTypeName + " " + column.DataTypeNameComplete + " " + column.DbTargetType;
// return "SqlDBType./* " + column.DataTypeNameComplete + " " + column.DbTargetType + "*/";
// }
// }
// private string vlnReturnType(string sType)
// {
// string sReturnType=sType;
// if(sType=="SmartDate")sReturnType="string";
// return sReturnType;
// }
// private string vlnReturnMember(string sType)
// {
// string sReturnMember="";
// return sReturnMember;
// }
// private string FormatColumns(string sFormat,IColumns columns)
// {
// return FormatColumns(sFormat,columns,"");
// }
// private string FormatColumns(string sFormat,IList columns,string sep)
// {
// string s="";
// string ssep="";
// foreach(IColumn column in columns)
// {
// s+=ssep+FormatColumn(sFormat,column);
// ssep=sep;
// }
// return s;
// }
// private string ColumnToMemberVariable( IColumn Column )
// {
// return _prefix + UniqueColumn( Column ).ToLower();
// }
//
// private string ColumnToPropertyName( IColumn Column )
// {
// return ToPascalCase( UniqueColumn( Column ) );
// }
//
// private string ColumnFKToClassName( IColumn c )
// {
// return ToPascalCase( c.ForeignKeys[0].PrimaryTable.Alias.Replace( " ", "" ) );
// }
// private string ColumnToParameterName(IColumn col)
// {
// return "@" + ToLeadingLower(col.Name).Replace(" ","");
// }
// private string ColumnToNewParameterName(IColumn col)
// {
// return "@new" + col.Name.Replace(" ","");
// }
// private string ColumnToArgumentName( IColumn Column )
// {
// return UniqueColumn( Column ).ToLower();
// }
//
// private string ColumnToNHibernateProperty( IColumn Column )
// {
// return _prefix + UniqueColumn( Column );
// }
//
// private string UniqueColumn( IColumn Column )
// {
// string c = Column.Alias.Replace( " ", "" );
// if( Column.Table != null && Column.Table.Alias.Replace( " ", "" ) == c )
// {
// c += "Name";
// }
// if( Column.View != null && Column.View.Alias.Replace( " ", "" ) == c )
// {
// c += "Name";
// }
// return c;
// }
//
// // nhibernate doesn't have these, so use the existing types
// private string ColumnToCSLAType( IColumn Column )
// {
// string retVal = Column.LanguageType;
//
// switch( Column.LanguageType )
// {
// case "DateTime":
// if(Column.Description.IndexOf("{datetime}")>=0)
// retVal="DateTime";
// else
// retVal = "SmartDate";
// break;
// // case "uint":
// // retVal = "int";
// // break;
// // case "ulong":
// // retVal = "long";
// // break;
// // case "ushort":
// // retVal = "short";
// // break;
// }
// return retVal;
// }
// private string ColumnToDefault( IColumn Column )
// {
// string retVal=";";
// if(Column.DataTypeName=="timestamp")
// {
// retVal = " = new byte[8];//timestamp";
// }
// else
// {
// //if(Column.Default != ""){
// // retVal = ConvertDefault(Column) + ";// TODO: Default from DB " + RemoveParens(Column.Default) + " ";
// //}
// //else
// //{
// switch( ColumnToCSLAType(Column ) )
// {
// case "string":
// retVal = " = string.Empty;";
// break;
// case "DateTime":
// retVal = " = new DateTime();";
// break;
// case "SmartDate":
// retVal = " = string.Empty;";
// break;
// //case "Guid":
// // retVal = "=new Guid();";
// // break;
// default:
// // nothing to do here
// break;
// }
// //}
// }
// return retVal;
// }
// string ConvertDefault(IColumn column)
// {
// string s = RemoveParens(column.Default);
// switch(s)
// {
// case "getdate()":
// if(ColumnToCSLAType(column)=="DateTime")
// s="=DateTime.Now";
// else
// s="=DateTime.Now.ToShortDateString()";
// break;
// case "upper(suser_sname())":
// s= "=Environment.UserName.ToUpper()";
// break;
// case "suser_sname()":
// s="=Environment.UserName";
// break;
// default:
// if(IsNumeric(s))s="=" + s;
// else s="";
// break;
// }
// return s;
// }
// string ColumnDefault(IColumn column)
// {
// string s = RemoveParens(column.Default);
// switch(s)
// {
// case "getdate()":
// if(ColumnToCSLAType(column)=="DateTime")
// s="DateTime.Now";
// else
// s="DateTime.Now.ToShortDateString()";
// break;
// case "upper(suser_sname())":
// s= "Environment.UserName.ToUpper()";
// break;
// case "suser_sname()":
// s="Environment.UserName";
// break;
// default:
// if(IsNumeric(s))s="" + s;
// else s="";
// break;
// }
// return s;
// }
// private string ToLeadingCaps( string name )
// {
// char[] chars = name.ToLower().ToCharArray();
// chars[0] = Char.ToUpper( chars[0] );
// return new string( chars );
// }
//
//
// private string ToPascalCase( string name )
// {
// string notStartingAlpha = Regex.Replace( name, "^[^a-zA-Z]+", "" );
// string workingString = ToLowerExceptCamelCase( notStartingAlpha );
// workingString = RemoveSeparatorAndCapNext( workingString );
// return workingString;
// }
// private string ToClassName(string name)
// {
// return Regex.Replace(ToPascalCase(name),"s$","");
// }
// private string RemoveSeparatorAndCapNext( string input )
// {
// string dashUnderscore = "-_";
// string workingString = input;
// char[] chars = workingString.ToCharArray();
// int under = workingString.IndexOfAny( dashUnderscore.ToCharArray() );
// while( under > -1 )
// {
// chars[ under + 1 ] = Char.ToUpper( chars[ under + 1 ], CultureInfo.InvariantCulture );
// workingString = new String( chars );
// under = workingString.IndexOfAny( dashUnderscore.ToCharArray(), under + 1 );
// }
// chars[ 0 ] = Char.ToUpper( chars[ 0 ], CultureInfo.InvariantCulture );
// workingString = new string( chars );
// return Regex.Replace( workingString, "[-_]", "" );
// }
// private string ToLowerExceptCamelCase( string input )
// {
// char[] chars = input.ToCharArray();
// for( int i = 0; i < chars.Length; i++ )
// {
// int left = ( i > 0 ? i - 1 : i );
// int right = ( i < chars.Length - 1 ? i + 1 : i );
// if( i != left && i != right )
// {
// if( Char.IsUpper( chars[i] ) && Char.IsLetter( chars[ left ] ) && Char.IsUpper( chars[ left ] ) )
// {
// chars[i] = Char.ToLower( chars[i], CultureInfo.InvariantCulture );
// }
// else if( Char.IsUpper( chars[i] ) && Char.IsLetter( chars[ right ] ) && Char.IsUpper( chars[ right ] ) )
// {
// chars[i] = Char.ToLower( chars[i], CultureInfo.InvariantCulture );
// }
// else if( Char.IsUpper( chars[i] ) && !Char.IsLetter( chars[ right ] ) )
// {
// chars[i] = Char.ToLower( chars[i], CultureInfo.InvariantCulture );
// }
// }
// }
// chars[ chars.Length - 1 ] = Char.ToLower( chars[ chars.Length - 1 ], CultureInfo.InvariantCulture );
// return new string( chars );
// }
private string FormatColumnNew(string sFormat,IColumn column)
{
return FormatColumnNew(sFormat,column,"");
}
private string FormatColumnNew(string sFormat,IColumn col,string sAlias)
{
string s=sFormat;
IColumn column = col.Table.Columns[col.Name];
// IForeignKey fkkk = RelObjFK(column);
string relProp=RelObjProp(column);
string relType=RelObjType(column);
string suffix = "";//(PropertyName(column)==ClassName(column.Table)?"Fld":"");
s=s.Replace("{member}",MemberName(column)+suffix);//m - Member _firstname
s=s.Replace("{fmember}",(column.Table.Alias==_tableName?"":_prefix + ClassName(column.Table)+sAlias)+MemberName(column)+suffix);//m - Member _firstname
s=s.Replace("{pmember}",(column.Table.Alias==_tableName?_prefix:LocalName(ClassName(column.Table))+".")+PropertyName(column)+suffix);//m - Member _firstname
s=s.Replace("{rmember}",LocalName(ClassName(column.Table))+"."+PropertyName(column));//m - Member _firstname
s=s.Replace("{!prop}",relProp);
s=s.Replace("{!member}",MemberName(relProp));
// s=s.Replace("{!membercolumn}",MemberName(relProp) + (IsRelObj(column)?"." + RelObjCol(column):""));
s=s.Replace("{!membercolumn}",MemberName(relProp) + (IsRelObj(column)?"." + RelObjProp(RelObjCol2(column)):""));
s=s.Replace("{!local}",LocalName(relProp));
s=s.Replace("{!localcolumn}",LocalName(relProp) + (IsRelObj(column)?"." + RelObjCol(column):""));
s=s.Replace("{!type}",relType);
s=s.Replace("{!rtype}",ReturnType(relType));
s=s.Replace("{!memberprop}",(column.IsInPrimaryKey ? MemberName(relProp) : relProp)+suffix);
s=s.Replace("{!propmember}",(IsRelObj(column) ? relProp : MemberName(relProp))+suffix);
s=s.Replace("{!column}",RelObjCol(column));
s=s.Replace("{!empty}",RelObjEmpty(column));
s=s.Replace("{!typecast}",RelObjTypeCast(column));
s=s.Replace("{local}",LocalName(column)+suffix);//l Local firstname
s=s.Replace("{prop}",PropertyName(column)+suffix);
s=s.Replace("{memberprop}",(column.IsInPrimaryKey ? MemberName(column) : PropertyName(column))+suffix);
s=s.Replace("{@}",ParameterName(column));
s=s.Replace("{@new}",NewParameterName(column));
string cType = CSLAType(column);
s=s.Replace("{ctype}",cType);
s=s.Replace("{ctype1}",cType.Replace("?",""));
s=s.Replace("{rmember}",ReturnMember(cType));
s=s.Replace("{rtype}",ReturnType(cType));
// s=s.Replace("{dbtype}",LocalName(column));
s=s.Replace("{dtype}",DBType(column));
s=s.Replace("{name}",column.Name);
s=s.Replace("{class}",ClassName(column.Table));
s=s.Replace("{fname}",(column.Table.Alias==_tableName?"":ClassName(column.Table)+sAlias+"_")+column.Name);
s=s.Replace("{sqltype}",column.DbTargetType);
s=s.Replace("{?ref}",(column.IsComputed || column.IsAutoKey ? "ref " : ""));
s=s.Replace("{?dbtype}",(CSLAType( column )=="SmartDate" ? ".DBValue" : ""));
s=s.Replace("{?dbprefix}",(CSLAType( column )=="SmartDate" ? "new SmartDate(" : ""));
s=s.Replace("{?dbsuffix}",(CSLAType( column )=="SmartDate" ? ").DBValue" : ""));
s=s.Replace("{?dbsuff}",(CSLAType( column )=="SmartDate" ? ")" : ""));
s=s.Replace("{default}",DefaultValue(column));
s=s.Replace("{?output}",(column.IsComputed || column.IsAutoKey ? " output" : ""));
s=s.Replace("{@key}",ParamKeyName(column));
s=s.Replace("{tbl}",column.Table.Name + sAlias);
s=s.Replace("{?null}",(column.IsNullable?"=null":""));
s=s.Replace("{parent}",parentName(column));
s=s.Replace("{Parent}",ParentName(column));
s=s.Replace("{ParentType}",ParentTypeName(column));
s=s.Replace("{autoseed}",AutoSeed(column));
if(s.Contains("{ifLogic"))
{
string ifLogic="";
switch (CSLAType(column))
{
case("DateTime"):
ifLogic = "if ({name}.Year >= 1753 && {name}.Year <= 9999) ";
break;
case("DateTime?"):
ifLogic = "if ({name} != null && ((DateTime){name}).Year >= 1753 && ((DateTime){name}).Year <= 9999) ";
break;
default:
if(column.IsNullable && IsRelObj(column) && s.Contains("{ifLogicL"))
ifLogic="if({name} != null)";
break;
}
s=s.Replace("{ifLogicL}",ifLogic.Replace("{name}",FormatColumnNew("{!local}{?dbtype}",column,sAlias)));
s=s.Replace("{ifLogicP}",ifLogic.Replace("{name}",FormatColumnNew("{?dbprefix}{member}{?dbsuffix}",column,sAlias)));
s=s.Replace("{ifLogic@}",ifLogic.Replace("{name}",FormatColumnNew("criteria.{prop}{?dbtype}",column,sAlias)));
//string name = FormatColumnNew("{local}{?dbtype}",column,sAlias);
//s=s.Replace("{ifLogicL}",(CSLAType(column)=="DateTime"?"if (" + name + ".Year >= 1753 && " + name + ".Year <= 9999) ":"" ));
//name = FormatColumnNew("{?dbprefix}{member}{?dbsuffix}",column,sAlias);
//s=s.Replace("{ifLogicP}",(CSLAType(column)=="DateTime"?"if (" + name + ".Year >= 1753 && " + name + ".Year <= 9999) ":"" ));
//name = FormatColumnNew("criteria.{prop}{?dbtype}",column,sAlias);
//s=s.Replace("{ifLogic@}",(CSLAType(column)=="DateTime"?"if (" + name + ".Year >= 1753 && " + name + ".Year <= 9999) ":"" ));
}
return s;
}
private string FormatColumnFKNew(string sFormat,IColumn column)
{
string s=sFormat;
s=s.Replace("{fkname}",column.Name);
s=s.Replace("{fktable}",column.Table.Name);
return s;
}
private string FormatPKColumns(string sFormat,IForeignKey pk,string sep,string sPrefix,ref string ssep,string sAlias)
{
string s="";
foreach(IColumn column in pk.PrimaryTable.Columns)
{
if(!IsIn(column,pk.PrimaryColumns) && column.DataTypeName != "timestamp")
{
s+=ssep+sPrefix+FormatColumn(sFormat,column,sAlias);
ssep=sep;
}
}
return s;
}
private string FormatFKColumns(string sFormat,IForeignKey fk,string sep,string sPrefix,ref string ssep)
{
string s="";
foreach(IColumn column in fk.ForeignTable.Columns)
{
//if(!IsIn(column,fk.ForeignColumns))
//{
s+=ssep+sPrefix+FormatColumn(sFormat,column);
ssep=sep;
//}
}
return s;
}
private bool IsIn(IColumn column,IColumns columns)
{
foreach(IColumn col in columns)
if(col.Name==column.Name && col.Table.Name == column.Table.Name)
return true;
return false;
}
private string FormatColumns(string sFormat,IList columns,ref string sep,string sPrefix,ref string ssep)
{
string s="";
foreach(IColumn column in columns)
{
s+=ssep+sPrefix+FormatColumn(sFormat,column);
ssep=sep;
}
return s;
}
private string FormatColumns(string sFormat,IList columns,string sep)
{
return FormatColumns(sFormat,columns,sep,"");
}
private string FormatColumns(string sFormat,IList columns,string sep,string sPrefix)
{
string s="";
string ssep="";
foreach(IColumn column in columns)
{
s+=ssep+sPrefix+FormatColumn(sFormat,column);
ssep=sep;
}
return s;
}
private string FormatColumn(string sFormat,IColumn column)
{
return FormatColumn(sFormat,column,"");
}
private string FormatColumn(string sFormat,IColumn column,string sAlias)
{
return FormatColumnNew(sFormat,column,sAlias);
}
private string FormatColumns(string sFormat,IForeignKey FK,string sep,string sPrefix)
{
string s="";
string ssep="";
for(int i = 0;i<FK.PrimaryColumns.Count;i++)
{
s+=ssep+sPrefix+FormatColumnFK(FormatColumn(sFormat,FK.PrimaryColumns[i]),FK.ForeignColumns[i]);
ssep=sep;
}
return s;
}
private string FormatColumnFK(string sFormat,IColumn fcolumn)
{
return FormatColumnFKNew(sFormat,fcolumn);
}
private string FormatColumns2(string sFormat,IForeignKey FK,string sep,string sPrefix)
{
string s="";
string ssep="";
for(int i = 0;i<FK.PrimaryColumns.Count;i++)
{
s+=ssep+sPrefix+FormatColumnFK(FormatColumn(sFormat,FK.ForeignColumns[i]),FK.ForeignColumns[i]);
ssep=sep;
}
return s;
}
private string FormatColumns(Hashtable dicFormat,IList columns,string sep,string sPrefix)
{
string s="";
string ssep="";
foreach(IColumn column in columns)
{
string sFmt = GetFormat(dicFormat,column);
if(sFmt != null)
{
s+=ssep+sPrefix+FormatColumn(sFmt,column);
ssep=sep;
}
}
return s;
}
private string GetFormat(Hashtable dicFormat,IColumn column){
string stype1=CSLAType(column);
if(dicFormat.Contains(stype1))
return (string)dicFormat[stype1];
string stype2=column.DataTypeName;
if(dicFormat.Contains(stype2))
return (string)dicFormat[stype2];
return string.Format("**** MyGeneration Error **** {0} of type {1},{2} not defined in Hashtable *",column.Name,stype1,stype2);
//return null;
}
private string FormatColumn(Hashtable dicFormat,IColumn column,string sPrefix,string sAlias)
{
string sFmt = GetFormat(dicFormat,column);
if(sFmt!=null)
{
return sPrefix + FormatColumn(sFmt,column,sAlias);
}
return "";
}
public string GetDescription(IColumn column)
{
string sDesc=column.Description;
sDesc=sDesc.Replace("{datetime}","");
sDesc=sDesc.Replace("{auto}","");
sDesc=sDesc.Replace("{info}","");
return sDesc;
}

View File

@ -0,0 +1,302 @@
##|TYPE Template
##|UNIQUEID 9fcabf5d-31fd-4546-8750-b6c1f7b89087
##|TITLE Learning Example
##|NAMESPACE
##|SOURCE_TYPE Source
##|OUTPUT_LANGUAGE C#
##|GUI_ENGINE .Net Script
##|GUI_LANGUAGE C#
##|GUI_BEGIN
public class GeneratedGui : DotNetScriptGui
{
public GeneratedGui(ZeusContext context) : base(context) {}
//-----------------------------------------
// The User Interface Entry Point
//-----------------------------------------
public override void Setup()
{
if ( !input.Contains( "chooseTables" ) || !input.Contains( "txtPath" ) ||
( !input.Contains( "chkClass" ) && !input.Contains( "chkNaming" ) ) )
{
if(context.Objects.ContainsKey("DnpUtils"))DnpUtils.ReadInputFromCache(context);
// UI Form Layout
ui.Title = "CSLA Object Mapping";
ui.Width = 600;
ui.Height = 450;
// Output Path Label, TextBox and Button
GuiLabel label1 = ui.AddLabel( "label1", "Select the output path:", "Select the output path in the field below." );
// label1.Width = 200;
GuiTextBox outputPath = ui.AddTextBox( "outputPath", GetDefault("defaultOutputPath"), "Select the Output Path." );
outputPath.Width = 450;
GuiFilePicker selectPath = ui.AddFilePicker( "selectPath", "Select Path", "Select the Output Path.", "outputPath", true );
selectPath.Top = outputPath.Top;
selectPath.Width = 100;
selectPath.Left = outputPath.Left + outputPath.Width + 20;
// Namespace Label and TextBox
GuiLabel label2 = ui.AddLabel( "label2", "Namespace: ", "Provide your objects namespace." );
label2.Width = 280;
GuiTextBox classNamespace = ui.AddTextBox( "classNamespace", "Volian.Object.Library", "Provide your objects namespace." );
classNamespace.Width = 280;
// Member Prefix Label and TextBox
GuiLabel label3 = ui.AddLabel( "label3", "Member prefix: ", "Provide your member prefix." );
label3.Width = 100;
label3.Top = label2.Top;
label3.Left = label2.Width + 20;
GuiTextBox memberPrefix = ui.AddTextBox( "memberPrefix", "_", "Provide your member prefix." );
memberPrefix.Width = 100;
memberPrefix.Top = classNamespace.Top;
memberPrefix.Left = classNamespace.Width + 20;
// Database Connection Name Label and TextBox
GuiLabel label3A = ui.AddLabel( "label3A", "dbConnection: ", "Provide a Connection Name." );
label3A.Width = 150;
label3A.Top = label3.Top;
label3A.Left = label3.Left+label3.Width + 10;
GuiTextBox dbConnection = ui.AddTextBox( "dbConnection", "VEPROMS", "Provide a Connection Name." );
dbConnection.Width = 150;
dbConnection.Top = memberPrefix.Top;
dbConnection.Left = memberPrefix.Left + memberPrefix.Width + 10;
// Setup Database selection combobox.
GuiLabel label4 = ui.AddLabel( "label4", "Select a database:", "Select a database in the dropdown below." );
label4.Width = 280;
GuiComboBox chooseDatabase = ui.AddComboBox( "chooseDatabase", "Select a database." );
chooseDatabase.Width = 280;
GuiCheckBox chkPrimary = MakeGuiCheckBox( "chkPrimary", "Primary Keys", true, "Show Primary Keys",100 );
chkPrimary.Checked = false;
GuiCheckBox chkColumns = MakeGuiCheckBox( "chkColumns", "Columns", true, "Show Columns" ,150,chkPrimary,200,0);
chkColumns.Checked = false;
GuiCheckBox chkFK = MakeGuiCheckBox( "chkFK", "Foreign Keys", true, "Show Foreign Keys" ,150,chkPrimary,400,0);
chkFK.Checked = false;
// Setup Tables selection multi-select listbox.
GuiLabel label7 = ui.AddLabel( "label7", "Select tables:", "Select tables from the listbox below." );
//label7.Top = chkInternal.Top + 20;
GuiListBox chooseTables = ui.AddListBox( "chooseTables", "Select tables." );
chooseTables.Height = 120;
// Setup Views selection multi-select listbox.
//GuiLabel label8 = ui.AddLabel( "label8", "Select views:", "Select views from the listbox below." );
//GuiListBox chooseViews = ui.AddListBox( "chooseViews", "Select views." );
//chooseViews.Height = 80;
// Attach the onchange event to the cmbDatabases control.
setupDatabaseDropdown( chooseDatabase );
GuiLabel labelTest = ui.AddLabel( "labelTest", "Status: Select CheckBox to Run", "Checkbox must be selected first" );
chooseDatabase.AttachEvent( "onchange", "chooseDatabase_onchange" );
chkPrimary.AttachEvent( "onclick", "checkbox_onclick" );
chkColumns.AttachEvent( "onclick", "checkbox_onclick" );
chkFK.AttachEvent( "onclick", "checkbox_onclick" );
chooseTables.AttachEvent( "onchange", "chooseTable_onclick" );
ui.ShowGui = true;
GuiButton btnOK = ui.AddButton( "OK", "OK", "Generate Code" );
btnOK.ClosesForm = true;
btnOK.Enabled = false;
}
else
{
ui.ShowGui = false;
}
}
public void setupDatabaseDropdown( GuiComboBox Databases )
{
try
{
if( MyMeta.IsConnected )
{
Databases.BindData( MyMeta.Databases );
if( MyMeta.DefaultDatabase != null )
{
Databases.SelectedValue = MyMeta.DefaultDatabase.Alias;
bindTables( Databases.SelectedValue );
bindViews( Databases.SelectedValue );
}
}
}
catch
{
}
}
public void bindTables( string sDatabase )
{
//int count = 0;
GuiListBox lstTables = ui["chooseTables"] as GuiListBox;
try
{
IDatabase db = MyMeta.Databases[sDatabase];
lstTables.BindData(db.Tables);
}
catch
{
}
}
public void bindViews( string sDatabase )
{
//int count = 0;
GuiListBox lstViews = ui["chooseViews"] as GuiListBox;
try
{
IDatabase db = MyMeta.Databases[sDatabase];
lstViews.BindData( db.Views );
}
catch
{
}
}
public void chooseDatabase_onchange( GuiComboBox control )
{
//int count = 0;
GuiComboBox cmbDatabases = ui["chooseDatabase"] as GuiComboBox;
bindTables( cmbDatabases.SelectedText );
bindViews( cmbDatabases.SelectedText );
GuiTextBox dbConnection = ui["dbConnection"] as GuiTextBox;
dbConnection.Text=cmbDatabases.SelectedText;
GuiTextBox classNamespace = ui["classNamespace"] as GuiTextBox;
classNamespace.Text=cmbDatabases.SelectedText + ".Object.Library";
Status = string.Format("chooseDatabase_onchange");
}
private string Status
{
set
{
GuiLabel labelTest = ui["labelTest"] as GuiLabel;
labelTest.Text = value;
}
}
private GuiButton btnOK
{
get
{
foreach(IGuiControl ctrl in ui)
{
if(ctrl.GetType().Name == "GuiButton"){
return ctrl as GuiButton;
}
}
return null;
}
}
public void SetupOkButton()
{
Status = string.Format("checkBox_onchange");
GuiCheckBox chkPrimary= ui["chkPrimary"] as GuiCheckBox;
GuiCheckBox chkColumns= ui["chkColumns"] as GuiCheckBox;
GuiCheckBox chkFK= ui["chkFK"] as GuiCheckBox;
GuiLabel labelTest = ui["labelTest"] as GuiLabel;
string status = "";
if(chkPrimary.Checked)status+=", " + chkPrimary.Text;
if(chkColumns.Checked)status+=", " + chkColumns.Text;
if(chkFK.Checked)status+=", " + chkFK.Text;
if(status == "")
{
btnOK.Enabled = false;
Status="Status: Select CheckBox to Run";
}
else
{
GuiListBox lb = ui["chooseTables"] as GuiListBox;
if(lb.SelectedItems.Count > 0)
{
btnOK.Enabled = true;
Status = string.Format("Will process: {0} {1}",status.Substring(2),lb.SelectedItems.Count);
}
else
{
Status = "Select one or more tables to process.";
btnOK.Enabled = false;
}
}
}
public void checkbox_onclick( GuiCheckBox control )
{
SetupOkButton();
}
public void chooseTable_onclick( GuiListBox control )
{
SetupOkButton();
}
private string GetDefault(string sName)
{
if( input.Contains( sName ) )
{
return input[sName].ToString();
}
return "";
}
<%#FILE MakeGuiCheckBox.cs %>
}
##|GUI_END
##|BODY_MODE Markup
##|BODY_ENGINE .Net Script
##|BODY_LANGUAGE C#
##|BODY_TAG_START <%
##|BODY_TAG_END %>
##|BODY_BEGIN
<%
public class GeneratedTemplate : DotNetScriptTemplate
{
public GeneratedTemplate(ZeusContext context) : base(context) {}
//---------------------------------------------------
// Render() is where you want to write your logic
//---------------------------------------------------
public override void Render()
{
string dbName = input["chooseDatabase"].ToString();
ArrayList selectedTables = input["chooseTables"] as ArrayList;
foreach(string tblName in selectedTables)
{
ITable tbl = MyMeta.Databases[dbName].Tables[tblName];
if((bool)input["chkPrimary"])PrimaryKeys(tbl);
if((bool)input["chkColumns"])Details(tbl);
if((bool)input["chkFK"])ForeignKeys(tbl);
}
}
private void PrimaryKeys(ITable tbl)
{
output.writeln("Table - " + tbl.Name);
foreach(IColumn col in tbl.PrimaryKeys)
{
output.writeln(" Column - " + col.Name);
}
}
private void Details(ITable tbl)
{
Details(tbl,0);
}
private void Details(ITable tbl, int indent)
{
string sPad = "".PadRight(indent * 2);
%> <%=sPad%> Table - <%=tbl.Name%><%
foreach(IColumn col in tbl.Columns)
{
%>
<%=sPad%> Column - <%=col.Name%> <%=col.DataTypeNameComplete%><%
}
}
private void ForeignKeys(ITable tbl)
{
output.writeln("Table - " + tbl.Name);
foreach(IForeignKey fk in tbl.ForeignKeys)
{
%>
ForeignKey - <%=fk.Name%>
Primary
<%Details(fk.PrimaryTable,6);%>
Foreign
<%Details(fk.ForeignTable,6);%><%
}
}
}
%>
##|BODY_END

View File

@ -0,0 +1,14 @@
public GuiCheckBox MakeGuiCheckBox(string name,string caption,bool def, string helptext,int width,GuiCheckBox related,int offX, int offY)
{
GuiCheckBox tmp = ui.AddCheckBox( name, caption, def, helptext );
tmp.Width=width;
tmp.Top=related.Top+(offY<0?-offY * related.Height:offY);
tmp.Left=related.Left+(offX<0?-offX * related.Width:offX);
return tmp;
}
public GuiCheckBox MakeGuiCheckBox(string name,string caption,bool def, string helptext,int width)
{
GuiCheckBox tmp = ui.AddCheckBox( name, caption, def, helptext );
tmp.Width=width;
return tmp;
}

View File

@ -0,0 +1,468 @@
private string FKSelectName(ITable tbl,IForeignKey FK,string sAlias)
{
if(tbl.Name == FK.PrimaryTable.Name)return ChildName(FK) + ClassesName(tbl.Name);
//return ClassesName(tbl.Name) + "By" + ClassName(FK.PrimaryTable) + sAlias;
return ClassesName(tbl.Name) + "By" + ForeignKeyName(FK) + sAlias;
}
private string ForeignKeyName(IForeignKey FK)
{
string retval="";
string sep = "";
foreach(IColumn col in FK.ForeignColumns)
{
retval = retval + sep + ClassName(col.Name);
sep = "_And_";
}
return retval;
}
private string FKFieldName(IForeignKey fk)
{
string cName = ClassName( fk.ForeignTable );
string className=ClassName( fk.PrimaryTable );
if(className==cName)return ChildName(fk);
return ClassName( fk.ForeignTable );
}
private string FKFieldsName(IForeignKey fk)
{
string cName = ClassesName( fk.ForeignTable );
string className=ClassesName( fk.PrimaryTable );
if(className==cName)return ChildrenName(fk);
return cName;
}
private string FKClassesName(IForeignKey fk)
{
string cName = ClassesName( fk.ForeignTable );
string className=ClassesName( fk.PrimaryTable );
if(className==cName)return ChildName(fk) + ClassesName( fk.PrimaryTable );
return ClassName( fk.PrimaryTable ) + cName;
}
private string FKClassName(string className,IForeignKey fk)
{
string cName = ClassName( fk.ForeignTable );
if(className==cName)return ChildName(fk) + cName;
return className + cName;
}
private string FKClassName(IForeignKey fk)
{
string className=ClassName(fk.PrimaryTable);
return FKClassName(className,fk);
}
private string FKClassName1(string className,IForeignKey fk)
{
string cName = ClassName( fk.ForeignTable);
if(className==cName)return ChildName(fk) + cName;
return className + cName + GetAlias(fk);
}
private string FKClassName1(IForeignKey fk)
{
string className=ClassName(fk.PrimaryTable);
return FKClassName1(className,fk);
}
private string FKBy(IForeignKey fk)
{
if(fk.PrimaryTable.Name==fk.ForeignTable.Name)return ChildrenName(fk);
return "By" +FormatColumns("{prop}",fk.ForeignColumns,"_","");
}
private string FKAndString(string className,IForeignKey fk,string str)
{
string cName = ClassName( fk.ForeignTable );
if(className==cName)return str;
return "";
}
private string FKCountName(ITable tbl,IForeignKey FK,string sAlias)
{
if(tbl.Name == FK.ForeignTable.Name)return ChildName(FK);
return ClassName(FK.ForeignTable) + sAlias;
}
private bool FKParent(ITable tbl)
{
foreach(IForeignKey fk in tbl.ForeignKeys)
{
if(fk.PrimaryTable == fk.ForeignTable)return true;
}
return false;
}
private IForeignKey FKParentFK(ITable tbl)
{
foreach(IForeignKey fk in tbl.ForeignKeys)
{
if(fk.PrimaryTable == fk.ForeignTable)return fk;
}
return null;
}
private bool IsParentCol(IColumn col)
{
IForeignKey fk = FKParentFK(col.Table);
if(fk==null)return false;
foreach(IColumn col1 in fk.ForeignColumns)
{
if(col.Name==col1.Name)return true;
}
return false;
}
private string parentName(IColumn col)
{
IColumn colp = ParentCol(col);
if (colp == null)
{
if(IsRelObj(col))return LocalName(RelObjProp(col)) + "." + RelObjCol(col);
return LocalName(RelObjProp(col));
}
return "my" + ParentName(col.ForeignKeys[0]) + "." + PropertyName(colp.Name);
}
private string ParentName(IColumn col)
{
IColumn colp = ParentCol(col);
if (colp == null)
{
if(IsRelObj(col))return PropertyName(col);
return MemberName(RelObjProp(col));
}
return PropertyName(col.Name);
}
private string ParentRef(IColumn col)
{
IColumn colp = ParentCol(col);
if (colp != null) return ClassName(col.Table) + ".Get(" + RelObjTypeCast(col) + MemberName(col) + ")";
return null;
}
private string ParentTypeName(IColumn col)
{
IColumn colp = ParentCol(col);
if (colp != null) return ClassName(col.Table) + " myParent";
return null;
}
private IColumn ParentCol(IColumn col)
{
IForeignKey fk = FKParentFK(col.Table);
if(fk==null)return null;
return RelatedColumnF(col,fk);
}
private bool IsParentColumn(IColumn col)
{
IForeignKey fk = FKParentFK(col.Table);
if(fk==null)return false;
foreach(IColumn colf in fk.ForeignColumns)
if(colf.Name == col.Name)return true;
return false;
}
private string AutoSeed(IColumn col)
{
IForeignKey fk = FKParentFK(col.Table);
if(fk==null)return null;
IColumn colp = RelatedColumnF(col,fk);
if(colp==null)return "";
return (colp.IsAutoKey?colp.AutoKeySeed.ToString():"");
}
private IColumn RelatedColumn(IColumn column,IForeignKey fk){
if(column.Table.Name == fk.PrimaryTable.Name && fk.ForeignColumns.Count == 1){
return fk.ForeignColumns[0];
}
if(column.Table.Name == fk.ForeignTable.Name && fk.PrimaryColumns.Count == 1){
return fk.PrimaryColumns[0];
}
return null;
}
private IColumn RelatedColumnF(IColumn col,IForeignKey fk){
for(int i =0; i < fk.PrimaryColumns.Count;i++) // Loop through the related columns
{
IColumn pcol=fk.PrimaryColumns[i]; // This is the primary column
IColumn fcol=fk.ForeignColumns[i]; // This is the foreign column
//if(pcol.Name == col.Name && pcol.Table.Name == col.Table.Name)return fcol;
if(fcol.Name == col.Name && fcol.Table.Name == col.Table.Name)return pcol;
}
return null;
}
private IColumn RelatedColumnP(IColumn col,IForeignKey fk){
for(int i =0; i < fk.PrimaryColumns.Count;i++) // Loop through the related columns
{
IColumn pcol=fk.PrimaryColumns[i]; // This is the primary column
IColumn fcol=fk.ForeignColumns[i]; // This is the foreign column
if(pcol.Name == col.Name && pcol.Table.Name == col.Table.Name)return fcol;
//if(fcol.Name == col.Name && fcol.Table.Name == col.Table.Name)return pcol;
}
return null;
}
private IColumn RelatedColumnB(IColumn col,IForeignKey fk){
for(int i =0; i < fk.PrimaryColumns.Count;i++) // Loop through the related columns
{
IColumn pcol=fk.PrimaryColumns[i]; // This is the primary column
IColumn fcol=fk.ForeignColumns[i]; // This is the foreign column
if(pcol.Name == col.Name && pcol.Table.Name == col.Table.Name)return fcol;
if(fcol.Name == col.Name && fcol.Table.Name == col.Table.Name)return pcol;
}
return null;
}
private string ProcessName(Match m)
{
return m.Value.TrimStart("-_ ".ToCharArray()).ToUpper();
}
private string Suffix(IColumn col)
{
//return (PropertyName(col.Name)==_className?"Fld":"");
return (PropertyName(col.Name)==ClassName(col.Table.Name)?"Fld":"");
}
private string PropertyName(IColumn col)
{
return PropertyName(col.Name)+Suffix(col);
}
private string PropertyName(string name)
{
return Regex.Replace(name, "^[a-z]|[-_ ][a-zA-Z0-9]",new MatchEvaluator(ProcessName));
}
private bool MixedCase(string s)
{
bool hasUpper = false;
bool hasLower = false;
foreach (char c in s.ToCharArray())
{
hasUpper |= Char.IsUpper(c);
hasLower |= char.IsLower(c);
if (hasLower && hasUpper) return true;
}
return false;
}
private string MemberName(string name)
{
return _prefix + name;
}
private string MemberName(IColumn c)
{
return MemberName(PropertyName(c));
}
private string LocalName(IColumn col)
{
return LocalName(col.Name)+Suffix(col);
}
private string LocalName(string s)
{
s=PropertyName(s);
if(MixedCase(s))return ToLeadingLower(s);
else return s.ToLower();
}
private string ClassName(string name)
{
return SingularName(PropertyName(name));
}
private string ClassName(ITable table)
{
return ClassName(table.Alias);
}
private string ClassName(IView view)
{
return ClassName(view.Alias);
}
private string ClassName(IColumn column)
{
if(column.Table != null)return ClassName(column.Table);
if(column.View != null)return ClassName(column.View);
return null;
}
private string ClassesName(string name)
{
return PluralName(PropertyName(name));
}
private string ClassesName(ITable table)
{
return ClassesName(table.Alias);
}
private string ClassesName(IView view)
{
return ClassesName(view.Name);
}
private string ClassesName(IColumn column)
{
if(column.Table != null)return ClassesName(column.Table);
if(column.View != null)return ClassesName(column.View);
return null;
}
private string SingularName(string s)
{
if(Regex.IsMatch(s,"crises$"))return Regex.Replace(s,"crises$","crisis");
if(Regex.IsMatch(s,"uses$"))return Regex.Replace(s,"uses$","us");
if(Regex.IsMatch(s,"is$"))return s;
if(Regex.IsMatch(s,"us$"))return s;
if(Regex.IsMatch(s,"sses$"))return Regex.Replace(s,"sses$","ss");
if(Regex.IsMatch(s,"ches$"))return Regex.Replace(s,"ches$","ch");
if(Regex.IsMatch(s,"ies$"))return Regex.Replace(s,"ies$","y");
if(Regex.IsMatch(s,"ss$"))return s;
return Regex.Replace(s,"s$","");
}
private string PluralName(string s)
{
s=SingularName(s);
if(Regex.IsMatch(s,"crisis$"))return Regex.Replace(s,"crisis$","crises");
if(Regex.IsMatch(s,"us$"))return Regex.Replace(s,"us$","uses");
if(Regex.IsMatch(s,"ises$"))return s;
if(Regex.IsMatch(s,"uses$"))return s;
if(Regex.IsMatch(s,"ss$"))return Regex.Replace(s,"ss$","sses");
if(Regex.IsMatch(s,"ch$"))return Regex.Replace(s,"ch$","ches");
if(Regex.IsMatch(s,"y$"))return Regex.Replace(s,"y$","ies");
return s + "s";
}
private string ReturnType(string type)
{
if(type=="SmartDate")type="string";
return type;
}
private string ReturnMember(string type)
{
string member="";
return member;
}
private string CSLAType(IColumn column)
{
return CSLAType(column,(column.IsNullable? "?":""));
}
private string CSLAType(IColumn column,string suffix)
{
string type = column.LanguageType;
switch( column.LanguageType )
{
case "DateTime":
if(column.Description.IndexOf("{datetime}")>=0)
type="DateTime" + suffix;
else
type = "SmartDate";
break;
case "short":
type="Int16" + suffix;
break;
case "string":
break;
case "byte[]":
break; default:
type += suffix;
break;
// case "uint":
// retVal = "int";
// break;
// case "ulong":
// retVal = "long";
// break;
// case "ushort":
// retVal = "short";
// break;
}
return type;
}
string DefaultValue(IColumn column)
{
string s = RemoveParens(column.Default);
switch(s)
{
case "getdate()":
if(CSLAType(column)=="DateTime")
s="DateTime.Now";
else
s="DateTime.Now.ToShortDateString()";
break;
case "upper(suser_sname())":
s= "Environment.UserName.ToUpper()";
break;
case "suser_sname()":
s="Environment.UserName";
break;
default:
if(IsNumeric(s))s="" + s;
else s="";
break;
}
return s;
}
private string InitializeValue( IColumn Column )
{
string retVal=";";
if(Column.DataTypeName=="timestamp")
{
retVal = " = new byte[8];//timestamp";
}
else
{
//if(Column.Default != ""){
// retVal = ConvertDefault(Column) + ";// TODO: Default from DB " + RemoveParens(Column.Default) + " ";
//}
//else
//{
switch( CSLAType(Column ) )
{
case "string":
retVal = " = string.Empty;";
break;
case "DateTime":
retVal = " = new DateTime();";
break;
case "SmartDate":
retVal = " = string.Empty;";
break;
//case "Guid":
// retVal = "=new Guid();";
// break;
default:
// nothing to do here
break;
}
//}
}
return retVal;
}
public static bool IsNumeric(string stringToTest)
{
double newVal;
return double.TryParse(stringToTest, NumberStyles.Any, NumberFormatInfo.InvariantInfo, out newVal);
}
private string RemoveParens(string s)
{
while(s.StartsWith("(") && s.EndsWith(")"))
s=s.Substring(1,s.Length-2);
return s;
}
private string ParameterName(IColumn column)
{
return "@" + PropertyName(column.Name);
}
private string NewParameterName(IColumn column)
{
return "@new" + PropertyName(column.Name);
}
private string ParamKeyName(IColumn column)
{
if(column.IsAutoKey)return NewParameterName(column);
return ParameterName(column);
}
private string ToLeadingLower( string name )
{
char[] chars = name.ToCharArray();
chars[0] = Char.ToLower( chars[0] );
return new string( chars );
}
private string DBType(IColumn column)
{
string s=column.DataTypeNameComplete;
switch(s){
case "text":
s="varchar(MAX)";
break;
case "ntext":
s="nvarchar(MAX)";
break;
}
return s;
}
// Old ----------------------------------------------
// private string ToClassName(string name)
// {
// return Regex.Replace(ToPascalCase(name),"s$","");
// }
// private string ColumnToMemberVariable( IColumn Column )
// {
// return _prefix + UniqueColumn( Column ).ToLower();
// }
//
// private string ColumnToPropertyName( IColumn Column )
// {
// return ToPascalCase( UniqueColumn( Column ) );
// }

View File

@ -0,0 +1,27 @@
private void WriteLine(string format,params object [] args)
{
output.writeln(string.Format(format,args));
}
private void Write(string format,params object [] args)
{
output.write(string.Format(format,args));
}
private void WriteProp(object arg)
{
WriteProp(",",arg,"");
}
private void WriteProp(string prefix,object arg,string suffix)
{
try
{
if(arg.GetType()==typeof(string))Write("{0}\"{1}\"{2}",prefix,arg,suffix);
else if(arg.GetType().IsPrimitive)Write("{0}{1}{2}",prefix,arg,suffix);
else Write("{0}\"{1}\"{2}",prefix,arg,suffix);
}
catch(Exception)
{
Write("{0}{2}",prefix,arg,suffix);
}
}

View File

@ -0,0 +1,722 @@
##|TYPE Template
##|UNIQUEID d6b504d5-d9c6-42fe-8819-07780ea72506
##|TITLE CSLA Stored Procedures - Volian
##|NAMESPACE CSLA_21
##|SOURCE_TYPE Source
##|OUTPUT_LANGUAGE Transact-SQL
##|GUI_ENGINE .Net Script
##|GUI_LANGUAGE C#
##|GUI_BEGIN
public class GeneratedGui : DotNetScriptGui
{
public GeneratedGui(ZeusContext context) : base(context) {}
//-----------------------------------------
// The User Interface Entry Point
//-----------------------------------------
public override void Setup()
{
if ( !input.Contains( "chooseTables" ) || !input.Contains( "txtPath" ) ||
( !input.Contains( "chkClass" ) && !input.Contains( "chkNaming" ) ) )
{
if(context.Objects.ContainsKey("DnpUtils"))DnpUtils.ReadInputFromCache(context);
ui.Title = "CSLA Object Mapping";
ui.Width = 600;
ui.Height = 660;
GuiLabel label1 = ui.AddLabel( "label1", "Select the output path:", "Select the output path in the field below." );
//label1.Width = 200;
GuiTextBox outputPath = ui.AddTextBox( "outputPath", GetDefault("defaultOutputPath"), "Select the Output Path." );
outputPath.Width = 450;
GuiFilePicker selectPath = ui.AddFilePicker( "selectPath", "Select Path", "Select the Output Path.", "outputPath", true );
selectPath.Top = outputPath.Top;
selectPath.Width = 100;
selectPath.Left = outputPath.Left + outputPath.Width + 20;
GuiLabel label2 = ui.AddLabel( "label2", "Namespace: ", "Provide your objects namespace." );
label2.Width = 280;
GuiTextBox classNamespace = ui.AddTextBox( "classNamespace", "Volian.Object.Library", "Provide your objects namespace." );
classNamespace.Width = 280;
GuiLabel label3 = ui.AddLabel( "label3", "Member prefix: ", "Provide your member prefix." );
label3.Width = 100;
label3.Top = label2.Top;
label3.Left = label2.Width + 20;
GuiTextBox memberPrefix = ui.AddTextBox( "memberPrefix", "_", "Provide your member prefix." );
memberPrefix.Width = 100;
memberPrefix.Top = classNamespace.Top;
memberPrefix.Left = classNamespace.Width + 20;
GuiLabel label3A = ui.AddLabel( "label3A", "dbConnection: ", "Provide a Connection Name." );
label3A.Width = 150;
label3A.Top = label3.Top;
label3A.Left = label3.Left+label3.Width + 10;
GuiTextBox dbConnection = ui.AddTextBox( "dbConnection", "VEPROMS", "Provide a Connection Name." );
dbConnection.Width = 150;
dbConnection.Top = memberPrefix.Top;
dbConnection.Left = memberPrefix.Left + memberPrefix.Width + 10;
// Setup Database selection combobox.
GuiLabel label4 = ui.AddLabel( "label4", "Select a database:", "Select a database in the dropdown below." );
label4.Width = 280;
GuiComboBox chooseDatabase = ui.AddComboBox( "chooseDatabase", "Select a database." );
chooseDatabase.Width = 280;
GuiCheckBox chkSelect = MakeGuiCheckBox( "chkSelect", "Select All", true, "Select All Records",100 );
GuiCheckBox chkUpdate = MakeGuiCheckBox( "chkUpdate", "Update One", true, "Update One Record" ,150,chkSelect,150,0);
GuiCheckBox chkFiles = MakeGuiCheckBox( "chkFiles", "Files", true, "Create Files" ,150,chkUpdate,200,0);
GuiCheckBox chkInsert = MakeGuiCheckBox( "chkInsert", "Insert One", true, "Insert One Record" ,150,chkSelect,0,-1);
GuiCheckBox chkDelete = MakeGuiCheckBox( "chkDelete", "Delete One", true, "Delete One Record" ,150,chkInsert,150,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 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);
// Setup Tables selection multi-select listbox.
GuiLabel label7 = ui.AddLabel( "label7", "Select tables:", "Select tables from the listbox below." );
//label7.Top = chkEqualsHashCode.Top + 20;
GuiListBox chooseTables = ui.AddListBox( "chooseTables", "Select tables." );
chooseTables.Height = 120;
// Setup Views selection multi-select listbox.
GuiLabel label8 = ui.AddLabel( "label8", "Select views:", "Select views from the listbox below." );
GuiListBox chooseViews = ui.AddListBox( "chooseViews", "Select views." );
chooseViews.Height = 120;
// Attach the onchange event to the cmbDatabases control.
setupDatabaseDropdown( chooseDatabase );
chooseDatabase.AttachEvent( "onchange", "chooseDatabase_onchange" );
ui.ShowGui = true;
}
else
{
ui.ShowGui = false;
}
}
public void setupDatabaseDropdown( GuiComboBox Databases )
{
try
{
if( MyMeta.IsConnected )
{
Databases.BindData( MyMeta.Databases );
if( MyMeta.DefaultDatabase != null )
{
Databases.SelectedValue = MyMeta.DefaultDatabase.Alias;
bindTables( Databases.SelectedValue );
bindViews( Databases.SelectedValue );
}
}
}
catch
{
}
}
public void bindTables( string sDatabase )
{
//int count = 0;
GuiListBox lstTables = ui["chooseTables"] as GuiListBox;
try
{
IDatabase db = MyMeta.Databases[sDatabase];
lstTables.BindData(db.Tables);
}
catch
{
}
}
public void bindViews( string sDatabase )
{
//int count = 0;
GuiListBox lstViews = ui["chooseViews"] as GuiListBox;
try
{
IDatabase db = MyMeta.Databases[sDatabase];
lstViews.BindData( db.Views );
}
catch
{
}
}
public void chooseDatabase_onchange( GuiComboBox control )
{
//int count = 0;
GuiComboBox cmbDatabases = ui["chooseDatabase"] as GuiComboBox;
bindTables( cmbDatabases.SelectedText );
bindViews( cmbDatabases.SelectedText );
GuiTextBox dbConnection = ui["dbConnection"] as GuiTextBox;
dbConnection.Text=cmbDatabases.SelectedText;
GuiTextBox classNamespace = ui["classNamespace"] as GuiTextBox;
classNamespace.Text=cmbDatabases.SelectedText + ".Object.Library";
}
private string GetDefault(string sName)
{
if( input.Contains( sName ) )
{
return input[sName].ToString();
}
return "";
}
<%#FILE MakeGuiCheckBox.cs %>
}
##|GUI_END
##|BODY_MODE Markup
##|BODY_ENGINE .Net Script
##|BODY_LANGUAGE C#
##|BODY_TAG_START <%
##|BODY_TAG_END %>
##|BODY_BEGIN
<%#NAMESPACE System.IO, System.Text, System.Text.RegularExpressions, System.Globalization %><%
public class GeneratedTemplate : DotNetScriptTemplate
{
public GeneratedTemplate(ZeusContext context) : base(context) {}
// Members
private string _dbName;
private ArrayList _selectedTables;
private ArrayList _selectedViews;
private string _exportPath;
private string _nameSpace;
private string _prefix;
private string _dbConnection;
private string _tableName;
private string _className="";
private ITable _workingTable;
//private Hashtable dicRead;
//private Hashtable dicReadI;
public void SaveFile(string sProc)
{
if((bool)input["chkFiles"]){
output.save( Path.Combine( _exportPath, sProc + ".SQL" ), false );
//output.writeln("--" + Path.Combine( _exportPath, "CSLA.SQL" ));
output.clear();
}
}
public delegate bool Filter(IColumn column);
//---------------------------------------------------
// Render() is where you want to write your logic
//---------------------------------------------------
public override void Render()
{
if(context.Objects.ContainsKey("DnpUtils"))DnpUtils.SaveInputToCache(context);
InitializeMembers();
if((bool)input["chkPurge"])SQLPurge();
foreach(string sTable in _selectedTables)
{
ITable tbl = MyMeta.Databases[_dbName].Tables[sTable];
_workingTable=tbl;
if((bool)input["chkSelect"])SQLSelect(tbl);// Load all records
if((bool)input["chkUpdate"])SQLUpdate(tbl);// Update single record based upon Primary Key
if((bool)input["chkInsert"])SQLInsert(tbl);// Insert single record
if((bool)input["chkDelete"])SQLDelete(tbl);// Delete single record based upon Primary Key
if((bool)input["chkSelectPK"])SQLSelectPK(tbl);// Load one record by Primary Key
if((bool)input["chkSelectPK"])SQLSelectUnique(tbl);// Load one record by Primary Key
if((bool)input["chkSelectPK"])SQLSelectParent(tbl);// Load one record by Primary Key
if((bool)input["chkExists"])SQLExists(tbl);// Check for existance by Primary Key
if((bool)input["chkSelectFKs"])SQLSelectFKs(tbl);// Load all records by Foreign Keys
//SQLIndexes(tbl);
}
_exportPath = input["outputPath"].ToString();
//SaveFile();
}
private void SQLIndexes(ITable tbl)
{
foreach(IIndex ind in tbl.Indexes)
{
if(!ind.Name.StartsWith("PK_"))
{
output.writeln(ind.Name);
foreach(IColumn col in ind.Columns)
{
output.writeln(" " + col.Name);
}
}
}
}
private IColumn IntegerIdentity(ITable tbl)
{
if(tbl.PrimaryKeys.Count == 1){
IColumn c = tbl.PrimaryKeys[0];
if(c.IsAutoKey && c.DataTypeName != "Guid")return c;
}
return null;
}
private void SQLPurge()
{
StartProc("purgeData");
%>
AS<%
ArrayList toProcess = new ArrayList();
ArrayList processed = new ArrayList();
foreach(string sTable in _selectedTables)
{
toProcess.Add(MyMeta.Databases[_dbName].Tables[sTable]);
}
while(toProcess.Count > processed.Count)
{
int pCount = processed.Count;
foreach(ITable tbl in toProcess)
{
if(!processed.Contains(tbl))
{
int count=0;
IColumn colid = IntegerIdentity(tbl);
string sSeed = (colid==null?"0":(colid.AutoKeySeed - colid.AutoKeyIncrement).ToString());
// output.writeln(string.Format("111 - {0} - {1},{2}",colid.Name,colid.AutoKeySeed,colid.AutoKeyIncrement));
string sWhere = "";
foreach(ForeignKey fk in tbl.ForeignKeys)
{
if(fk.PrimaryTable.Name == tbl.Name)
{
if(fk.ForeignTable.Name != tbl.Name)
{
if(toProcess.Contains(fk.ForeignTable) && !processed.Contains(fk.ForeignTable))
count++;
}
else
{
// sWhere = string.Format(" WHERE {0} <> {1}",colid.Name,colid.AutoKeySeed);
// sSeed = (colid==null?"0":(colid.AutoKeySeed + colid.AutoKeyIncrement).ToString());
// // output.writeln(string.Format("222 - {0} - {1},{2}",colid.Name,colid.AutoKeySeed,colid.AutoKeyIncrement));
}
}
}
if(count == 0)
{
%>
delete from [<%=tbl.Name%>]<%=sWhere%><%
// Need logic to only do this for identity columns
if(colid != null)
{
%>
dbcc checkident([<%=tbl.Name%>],reseed,<%=sSeed%>)<%
}
processed.Add(tbl);
}
}
}
if(processed.Count ==pCount)return;
}
EndProc("purgeData");
}
private void InitializeMembers()
{
_dbName = input["chooseDatabase"].ToString();
_selectedTables = input["chooseTables"] as ArrayList;
_selectedViews = input["chooseViews"] as ArrayList;
_exportPath = input["outputPath"].ToString();
_nameSpace = input["classNamespace"].ToString();
_prefix = input["memberPrefix"].ToString();
_dbConnection = input["dbConnection"].ToString();
}
//----------------------------------------------------------------------
// Select
//----------------------------------------------------------------------
private void SQLSelect(ITable tbl)
{
string sproc = "get" + ClassesName(tbl);
StartProc(sproc);
%>
AS
SELECT
<%=FormatColumns("[{name}]",tbl.Columns,",\r\n","\t\t")%><%=FKCounts(tbl)%>
FROM [<%=tbl.Name%>]<%
EndProc(sproc);
}
private string FKCounts(ITable tbl)
{
string retval="";
Hashtable dicAlias = new Hashtable();
foreach(ForeignKey FK in tbl.ForeignKeys)
{
if(FK.PrimaryTable == tbl)
{
//string sAlias = GetAlias(dicAlias,FK.ForeignTable);
string sAlias = GetAlias(FK);
string sep="";
string sAliasFK = FK.ForeignTable.Name;
string sAliasFK2 = "";
if(FK.PrimaryTable == FK.ForeignTable)
{
sAliasFK=ChildrenName(FK);
sAliasFK2=" [" + sAliasFK + "]";
}
retval += ",\r\n\t\t(SELECT COUNT(*) FROM [" + FK.ForeignTable.Name + "]" + sAliasFK2 + " WHERE ";
for(int i=0;i<FK.PrimaryColumns.Count;i++)
{
retval += sep + "[" + sAliasFK + "].[" + FK.ForeignColumns[i].Name + "]=[" +
FK.PrimaryTable.Name + "].[" + FK.PrimaryColumns[i].Name + "]";
sep = " AND ";
}
//retval += ") [" + ClassName(FK.ForeignTable)+ sAlias + "Count]";
retval += ") [" + FKCountName(tbl,FK,sAlias) + "Count]";
}
}
return retval;
}
//----------------------------------------------------------------------
// Update
//----------------------------------------------------------------------
private void SQLUpdate(ITable tbl)
{
if(tbl.PrimaryKeys.Count == tbl.Columns.Count)
{
// No Columns other than Primary Key Columns - Nothing to Update
// Instead of Update - Do a Delete followed by an Insert
%>
-- Update cannot be performed on <%=tbl.Name%> since it doesn't contain
-- any columns that are not part of the Primary Key
<%
return;
}
string sproc = "update" + ClassName(tbl);
StartProc(sproc);
%>
(
<%=FormatColumns("{@} {dtype}{?null}",tbl.Columns,",\r\n","\t")%><%=FormatColumns("{@new} {dtype} output",Computed(tbl),"",",\r\n\t")%>
)
AS
UPDATE [<%=tbl.Name%>]
SET
<%=FormatColumns("[{name}]={@}",Updatable(tbl),",\r\n","\t\t\t")%>
WHERE <%=FormatColumns("[{name}]={@}",NotUpdatable(tbl)," AND ","")%>
IF @@ROWCOUNT = 0
BEGIN
IF NOT exists(select * from [<%=tbl.Name%>] WHERE <%=FormatColumns("[{name}]={@}",PrimaryKey(tbl)," AND ","")%>)
RAISERROR('<%=ClassName(tbl)%> record has been deleted by another user', 16, 1)
ELSE
RAISERROR('<%=ClassName(tbl)%> has been edited by another user', 16, 1)
END
<%
if(Computed(tbl).Count > 0){
%>
SELECT <%=FormatColumns("{@new}=[{name}]",Computed(tbl),",\r\n","\t\t")%>
FROM [<%=tbl.Name%>] WHERE <%=FormatColumns("[{name}]={@}",tbl.PrimaryKeys," AND ","")%>
<%
}
EndProc(sproc);
}
//----------------------------------------------------------------------
// Insert
//----------------------------------------------------------------------
private void SQLInsert(ITable tbl)
{
string sproc = "add" + ClassName(tbl);
StartProc(sproc);
%>
(
<%=FormatColumns("{@} {dtype}{?null}",Insertable(tbl),",\r\n","\t")%><%=FormatColumns("{@new} {dtype} output",NotInsertable(tbl),"",",\r\n\t")%>
)
AS
INSERT INTO [<%=tbl.Name%>]
(
<%=FormatColumns("[{name}]",Insertable(tbl),",\r\n","\t\t")%>
)
VALUES
(
<%=FormatColumns("{@}",Insertable(tbl),",\r\n","\t\t")%>
)
<%=FormatColumns("SELECT {@new}= SCOPE_IDENTITY()",AutoKey(tbl),"\r\n","\t")%><%
// Update Output Values
ArrayList cmp = Computed(tbl);
if(cmp.Count > 0){
%>
SELECT <%=FormatColumns("{@new}=[{name}]",cmp,"\r\n","\t\t")%>
FROM [<%=tbl.Name%>] WHERE <%=FormatColumns("[{name}]={@key}",tbl.PrimaryKeys," AND ","")%><%
}
EndProc(sproc);
}
//----------------------------------------------------------------------
// Delete
//----------------------------------------------------------------------
private void SQLDelete(ITable tbl)
{
string sproc = "delete" + ClassName(tbl);
StartProc(sproc);
%>
(
<%=FormatColumns("{@} {dtype}",tbl.PrimaryKeys,",\r\n","\t")%>
)
AS<%
foreach(IForeignKey fk in tbl.ForeignKeys)
{
if(tbl != fk.ForeignTable)
{
%>
DELETE [<%=fk.ForeignTable.Name%>]
WHERE<%
string sep = " ";
for(int j=0;j<fk.ForeignColumns.Count;j++)
{
output.write(sep + "[" + fk.ForeignColumns[j].Name + "]=" + ParameterName(fk.PrimaryColumns[j]));
sep = ", ";
}
}
}
%>
DELETE [<%=tbl.Name%>]
WHERE <%=FormatColumns("[{name}] = {@}",tbl.PrimaryKeys," AND ","")%><%
EndProc(sproc);
}
//----------------------------------------------------------------------
// SelectPK
//----------------------------------------------------------------------
private void SQLSelectPK(ITable tbl)
{
string sproc = "get" + ClassName(tbl);
StartProc(sproc);
%>
(
<%=FormatColumns("{@} {dtype}",tbl.PrimaryKeys,",\r\n","\t")%>
)
AS
SELECT
<%=FormatColumns("[{name}]",tbl.Columns,",\r\n","\t\t")%><%=FKCounts(tbl)%>
FROM [<%=tbl.Name%>]
WHERE <%=FormatColumns("[{name}]={@}",tbl.PrimaryKeys," AND ","")%><%
// Need to loop through foreign keys and select related records
FKSelects(tbl);
EndProc(sproc);
}
private bool IsPrimaryKey(IIndex ind)
{
IColumns colsi = ind.Columns;
IColumns colsp = ind.Table.PrimaryKeys;
if(colsi.Count != colsp.Count)return false;
for(int i=0;i<colsi.Count;i++)
{
if(colsi[i]!=colsp[i])
return false;
}
return true;
}
//----------------------------------------------------------------------
// SelectUnique
//----------------------------------------------------------------------
private void SQLSelectUnique(ITable tbl)
{
foreach(IIndex ind in tbl.Indexes)
{
if(!IsPrimaryKey(ind) && ind.Unique)
{
string sproc = "get" + ClassName(tbl) + "By" + FormatColumns("{name}",ind.Columns,"_","");
StartProc(sproc);
%>(
<%=FormatColumns("{@} {dtype}",ind.Columns,",\r\n","\t")%>
)
AS
SELECT
<%=FormatColumns("[{name}]",tbl.Columns,",\r\n","\t\t")%><%=FKCounts(tbl)%>
FROM [<%=tbl.Name%>]
WHERE <%=FormatColumns("[{name}]={@}",ind.Columns," AND ","")%><%
// Need to loop through foreign keys and select related records
EndProc(sproc);
}
}
}
//----------------------------------------------------------------------
// SelectParent
//----------------------------------------------------------------------
private void SQLSelectParent(ITable tbl)
{
if(!FKParent(tbl))return;
IForeignKey fk = FKParentFK(tbl);
string sproc = "get" + ParentName(fk) + ClassName(tbl);
StartProc(sproc);
%>(
<%=FormatColumns("{@} {dtype}",fk.ForeignColumns,",\r\n","\t")%>
)
AS
SELECT
<%=FormatColumns("[{name}]",tbl.Columns,",\r\n","\t\t")%><%=FKCounts(tbl)%>
FROM [<%=tbl.Name%>]
WHERE<%
string sep="";
for(int i = 0; i<fk.ForeignColumns.Count; i++)
{
%>
<%=FormatColumn("[{name}]=",fk.PrimaryColumns[i])%><%=FormatColumn("{@}",fk.ForeignColumns[i])%><%=sep%><%
sep=" AND";
}
EndProc(sproc);
}
//----------------------------------------------------------------------
// Exists
//----------------------------------------------------------------------
private void SQLExists(ITable tbl)
{
string sproc = "exists" + ClassName(tbl);
StartProc(sproc);
%>
(
<%=FormatColumns("{@} {dtype}",tbl.PrimaryKeys,",\r\n","\t")%>
)
AS
SELECT COUNT(*)
FROM [<%=tbl.Name%>] WHERE <%=FormatColumns("[{name}]={@}",tbl.PrimaryKeys," AND ","")%><%
EndProc(sproc);
}
//----------------------------------------------------------------------
// SelectFKs
//----------------------------------------------------------------------
private void SQLSelectFKs(ITable tbl)
{
Hashtable dicAlias = new Hashtable();
foreach(IForeignKey FK in tbl.ForeignKeys)
{
if(tbl == FK.ForeignTable)
{
//string sAlias = GetAlias(dicAlias,FK.PrimaryTable);
string sAlias = GetAlias(FK);
SQLSelectFK(tbl,FK,sAlias);
}
}
}
private void SQLSelectFKChild(ITable tbl, IForeignKey FK,string sAlias)
{
string sproc = "get" + FKSelectName(tbl,FK,sAlias);
StartProc(sproc);
%>
(
<%=FormatColumns2("{@} {dtype}",FK,",\r\n","\t")%>
)
AS
SELECT
<%=FormatColumns("[{name}]",tbl.Columns,",\r\n","\t\t")%><%=FKCounts(tbl)%>
FROM [<%=tbl.Name%>] WHERE <%=FormatColumns2("[{fkname}]={@}",FK," AND ","")%> AND <%=FormatColumns2("[{!column}]<>{@}",FK," AND ","")%><%
EndProc(sproc);
}
private void SQLSelectFK(ITable tbl, IForeignKey FK,string sAlias)
{
if(FK.PrimaryTable == FK.ForeignTable){
SQLSelectFKChild(tbl,FK,sAlias);
}
else
{
//string sproc = "get" + FKSelectName(tbl,FK,sAlias);
string sproc = "get" + FKSelectName(tbl,FK,"");
StartProc(sproc);
%>
(
<%=FormatColumns2("{@} {dtype}",FK,",\r\n","\t")%>
)
AS<%
string sWhere = "\r\n\tWHERE\r\n\t\t" + FormatColumns2("[{fktable}].[{fkname}]={@}",FK," AND ","");
FKSelect(FK,(FK.PrimaryTable==tbl?FK.ForeignTable:FK.PrimaryTable),FKCounts(tbl),sWhere);
EndProc(sproc);
}
}
private void StartProc(string sproc)
{
// Drop and recreate
%>
/****** Object: StoredProcedure [<%=sproc%>] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[<%=sproc%>]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE [<%=sproc%>];
GO
CREATE PROCEDURE [dbo].[<%=sproc%>]
<%
}
private void EndProc(string sproc)
{
%>
RETURN
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);
}
private void FKSelects(ITable tbl)
{
foreach(ForeignKey fk in tbl.ForeignKeys)
{
// WriteLine("\r\n--ForeignKey - {0} - {1}\r\n",fk.Name,IsPrimaryKey(fk));
if(tbl != fk.ForeignTable)
//if(!IsPrimaryKey(fk)) - This was removed so that one to one relationships would return records.
FKSelect(fk,tbl,"",BuildWhere(fk));
}
}
private void FKSelect(IForeignKey fk, ITable tbl, string sCounts,string sWhere)
{
string sjoin="";
string ssep="";
Hashtable dicAlias = new Hashtable();
%>
SELECT
<%=FormatFKColumns("[{tbl}].[{name}]",fk,",\r\n","\t\t",ref ssep)%><%
foreach(ForeignKey pk in fk.ForeignTable.ForeignKeys)
{
// if(ManyToMany(tbl,fk,pk))
if(tbl != pk.PrimaryTable && fk.ForeignTable == pk.ForeignTable && pk.PrimaryTable != pk.ForeignTable && ForeignRequired(pk))
{
//string sAlias=GetAlias(dicAlias,pk.PrimaryTable);
string sAlias=GetAlias(pk);
string sJoinAdd = BuildJoin(pk,sAlias);
if(sJoinAdd != null) // Only add related tables that are associated with a required field
{
sjoin += sJoinAdd;
%><%=FormatPKColumns("[{tbl}].[{name}] [{fname}]",pk,",\r\n","\t\t",ref ssep,sAlias)%><%
}
}
}
%><%=sCounts%>
FROM [<%=fk.ForeignTable.Name%>]<%=sjoin%><%=sWhere%>
<%
}
/*
private string DefineAlias(IForeignKey pk,Hashtable dicAlias)
{
if(((int)dicAlias[pk.PrimaryTable.Name])==0)return "";
return "[" + pk.PrimaryTable.Name + "_" + dicAlias[pk.PrimaryTable.Name].ToString() + "]";
}
private string UseAlias(string tblname,Hashtable dicAlias)
{
if(((int)dicAlias[tblname])==0)return tblname;
return tblname + "_" + dicAlias[tblname].ToString();
}
*/
private string BuildJoin(IForeignKey pk,string sAlias)
{
string sjoin="\r\n\t\tJOIN [" + pk.PrimaryTable.Name + "] " + (sAlias==""?"":"[" + pk.PrimaryTable.Name + sAlias + "]") + " ON";
for(int j=0;j<pk.PrimaryColumns.Count;j++)
{
sjoin += "\r\n\t\t\t[" + pk.PrimaryTable.Name + sAlias + "].[" + pk.PrimaryColumns[j].Name + "]="
+ "[" + pk.ForeignTable.Name + "].[" + pk.ForeignColumns[j].Name + "]";
}
return sjoin;
}
private string BuildWhere(IForeignKey fk)
{
string swhere="\r\n\tWHERE";
for(int j=0;j<fk.PrimaryColumns.Count;j++)
{
swhere += "\r\n\t\t[" + fk.ForeignTable.Name + "].[" + fk.ForeignColumns[j].Name
+ "]=" + ParameterName(fk.PrimaryColumns[j]);
}
return swhere;
}
%><%#FILE NamingConvention.cs%><%
%><%#FILE ForeignKeyProcessing.cs%><%
%><%#FILE FilteredColumns.cs%><%
%><%#FILE FormatColumns.cs%><%
%><%#FILE WriteLine.cs%><%
}
%>
##|BODY_END

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,331 @@
##|TYPE Template
##|UNIQUEID ad80d306-3f72-4b18-a21e-3e543240152a
##|TITLE List Stored Procedures - Volian
##|NAMESPACE CSLA_21
##|SOURCE_TYPE Source
##|OUTPUT_LANGUAGE Transact-SQL
##|GUI_ENGINE .Net Script
##|GUI_LANGUAGE C#
##|GUI_BEGIN
public class GeneratedGui : DotNetScriptGui
{
public GeneratedGui(ZeusContext context) : base(context) {}
//-----------------------------------------
// The User Interface Entry Point
//-----------------------------------------
public override void Setup()
{
if ( !input.Contains( "chooseTables" ) || !input.Contains( "txtPath" ) ||
( !input.Contains( "chkClass" ) && !input.Contains( "chkNaming" ) ) )
{
if(context.Objects.ContainsKey("DnpUtils"))DnpUtils.ReadInputFromCache(context);
ui.Title = "CSLA Object Mapping";
ui.Width = 600;
ui.Height = 660;
GuiLabel label1 = ui.AddLabel( "label1", "Select the output path:", "Select the output path in the field below." );
//label1.Width = 200;
GuiTextBox outputPath = ui.AddTextBox( "outputPath", GetDefault("defaultOutputPath"), "Select the Output Path." );
outputPath.Width = 450;
GuiFilePicker selectPath = ui.AddFilePicker( "selectPath", "Select Path", "Select the Output Path.", "outputPath", true );
selectPath.Top = outputPath.Top;
selectPath.Width = 100;
selectPath.Left = outputPath.Left + outputPath.Width + 20;
GuiLabel label2 = ui.AddLabel( "label2", "Namespace: ", "Provide your objects namespace." );
label2.Width = 280;
GuiTextBox classNamespace = ui.AddTextBox( "classNamespace", "Volian.Object.Library", "Provide your objects namespace." );
classNamespace.Width = 280;
GuiLabel label3 = ui.AddLabel( "label3", "Member prefix: ", "Provide your member prefix." );
label3.Width = 100;
label3.Top = label2.Top;
label3.Left = label2.Width + 20;
GuiTextBox memberPrefix = ui.AddTextBox( "memberPrefix", "_", "Provide your member prefix." );
memberPrefix.Width = 100;
memberPrefix.Top = classNamespace.Top;
memberPrefix.Left = classNamespace.Width + 20;
GuiLabel label3A = ui.AddLabel( "label3A", "dbConnection: ", "Provide a Connection Name." );
label3A.Width = 150;
label3A.Top = label3.Top;
label3A.Left = label3.Left+label3.Width + 10;
GuiTextBox dbConnection = ui.AddTextBox( "dbConnection", "VEPROMS", "Provide a Connection Name." );
dbConnection.Width = 150;
dbConnection.Top = memberPrefix.Top;
dbConnection.Left = memberPrefix.Left + memberPrefix.Width + 10;
// Setup Database selection combobox.
GuiLabel label4 = ui.AddLabel( "label4", "Select a database:", "Select a database in the dropdown below." );
label4.Width = 280;
GuiComboBox chooseDatabase = ui.AddComboBox( "chooseDatabase", "Select a database." );
chooseDatabase.Width = 280;
GuiCheckBox chkSelect = MakeGuiCheckBox( "chkSelect", "Select All", true, "Select All Records",100 );
GuiCheckBox chkUpdate = MakeGuiCheckBox( "chkUpdate", "Update One", true, "Update One Record" ,150,chkSelect,150,0);
GuiCheckBox chkFiles = MakeGuiCheckBox( "chkFiles", "Files", true, "Create Files" ,150,chkUpdate,200,0);
GuiCheckBox chkInsert = MakeGuiCheckBox( "chkInsert", "Insert One", true, "Insert One Record" ,150,chkSelect,0,-1);
GuiCheckBox chkDelete = MakeGuiCheckBox( "chkDelete", "Delete One", true, "Delete One Record" ,150,chkInsert,150,0);
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 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);
// Setup Tables selection multi-select listbox.
GuiLabel label7 = ui.AddLabel( "label7", "Select tables:", "Select tables from the listbox below." );
//label7.Top = chkEqualsHashCode.Top + 20;
GuiListBox chooseTables = ui.AddListBox( "chooseTables", "Select tables." );
chooseTables.Height = 120;
// Setup Views selection multi-select listbox.
GuiLabel label8 = ui.AddLabel( "label8", "Select views:", "Select views from the listbox below." );
GuiListBox chooseViews = ui.AddListBox( "chooseViews", "Select views." );
chooseViews.Height = 120;
// Attach the onchange event to the cmbDatabases control.
setupDatabaseDropdown( chooseDatabase );
chooseDatabase.AttachEvent( "onchange", "chooseDatabase_onchange" );
ui.ShowGui = true;
}
else
{
ui.ShowGui = false;
}
}
public void setupDatabaseDropdown( GuiComboBox Databases )
{
try
{
if( MyMeta.IsConnected )
{
Databases.BindData( MyMeta.Databases );
if( MyMeta.DefaultDatabase != null )
{
Databases.SelectedValue = MyMeta.DefaultDatabase.Alias;
bindTables( Databases.SelectedValue );
bindViews( Databases.SelectedValue );
}
}
}
catch
{
}
}
public void bindTables( string sDatabase )
{
//int count = 0;
GuiListBox lstTables = ui["chooseTables"] as GuiListBox;
try
{
IDatabase db = MyMeta.Databases[sDatabase];
lstTables.BindData(db.Tables);
}
catch
{
}
}
public void bindViews( string sDatabase )
{
//int count = 0;
GuiListBox lstViews = ui["chooseViews"] as GuiListBox;
try
{
IDatabase db = MyMeta.Databases[sDatabase];
lstViews.BindData( db.Views );
}
catch
{
}
}
public void chooseDatabase_onchange( GuiComboBox control )
{
//int count = 0;
GuiComboBox cmbDatabases = ui["chooseDatabase"] as GuiComboBox;
bindTables( cmbDatabases.SelectedText );
bindViews( cmbDatabases.SelectedText );
GuiTextBox dbConnection = ui["dbConnection"] as GuiTextBox;
dbConnection.Text=cmbDatabases.SelectedText;
GuiTextBox classNamespace = ui["classNamespace"] as GuiTextBox;
classNamespace.Text=cmbDatabases.SelectedText + ".Object.Library";
}
private string GetDefault(string sName)
{
if( input.Contains( sName ) )
{
return input[sName].ToString();
}
return "";
}
<%#FILE MakeGuiCheckBox.cs %>
}
##|GUI_END
##|BODY_MODE Markup
##|BODY_ENGINE .Net Script
##|BODY_LANGUAGE C#
##|BODY_TAG_START <%
##|BODY_TAG_END %>
##|BODY_BEGIN
<%#NAMESPACE System.IO, System.Text, System.Text.RegularExpressions, System.Globalization %><%
public class GeneratedTemplate : DotNetScriptTemplate
{
public GeneratedTemplate(ZeusContext context) : base(context) {}
// Members
private string _dbName;
private ArrayList _selectedTables;
private ArrayList _selectedViews;
private string _exportPath;
private string _nameSpace;
private string _prefix;
private string _dbConnection;
private string _tableName;
private string _className="";
private ITable _workingTable;
//private Hashtable dicRead;
//private Hashtable dicReadI;
public void SaveFile(string sFile)
{
if((bool)input["chkFiles"]){
output.save( Path.Combine( _exportPath, sFile + ".SQL" ), false );
//output.writeln("--" + Path.Combine( _exportPath, "CSLA.SQL" ));
output.clear();
}
}
//private bool IsPrimaryKey(IForeignKey fk)
//{
// bool retval=true;
// foreach(IColumn c in fk.ForeignColumns)retval &= c.IsInPrimaryKey;
// return retval;
//}
public delegate bool Filter(IColumn column);
//---------------------------------------------------
// Render() is where you want to write your logic
//---------------------------------------------------
public override void Render()
{
if(context.Objects.ContainsKey("DnpUtils"))DnpUtils.SaveInputToCache(context);
//InitializeMembers();
_exportPath = input["outputPath"].ToString();
_dbName = input["chooseDatabase"].ToString();
IDatabase db = MyMeta.Databases[_dbName];
SaveProcs(db);
//SaveTables(db);
}
private void SaveProcs(IDatabase db)
{
foreach(IProcedure ip in db.Procedures)
{
if(ip.Schema != "sys"){
string sName = ip.Name;
if((bool)input["chkDrop"]){
if(sName.Contains("sp_")==false && sName.Contains("fn_")==false)
output.writeln("Drop procedure [" + sName + "]");
} else {
if(sName.Contains("sp_")==false && sName.Contains("fn_")==false)
{
%>
/****** Object: StoredProcedure [<%=sName%>] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[<%=sName%>]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE [<%=sName%>];
GO
<%
output.write(ip.ProcedureText.TrimEnd("\r\n".ToCharArray()).Replace(" \r\n","\r\n"));
%>
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: <%=sName%> Succeeded'
ELSE PRINT 'Procedure Creation: <%=sName%> Error on Creation'
GO
<%
SaveFile(ip.Name);
}
}
}
}
}
private void ShowColumns(IColumns cols,int indent,string title)
{
output.writeln(string.Format("{0}{1}","".PadRight(indent),title));
foreach(IColumn col in cols)
{
output.writeln(string.Format("{0}{1} {2}{3}{4}","".PadRight(indent+2),col.Name,col.DataTypeNameComplete,
(col.IsInPrimaryKey?" PK":""),(col.IsInForeignKey?" FK":"")));
ShowProperties(col.AllProperties,indent+2);
}
}
private void ShowProperties(IPropertyCollection prps, int indent)
{
if(prps.Count == 0)return;
output.writeln(string.Format("{0}Properties:","".PadRight(indent)));
foreach(IProperty prp in prps)
{
output.writeln(string.Format("{0}{1}={2}","".PadRight(indent+2),prp.Key,prp.Value));
}
}
private bool IsPrimaryKey(IIndex ind)
{
IColumns colsi = ind.Columns;
IColumns colsp = ind.Table.PrimaryKeys;
if(colsi.Count != colsp.Count)return false;
for(int i=0;i<colsi.Count;i++)
{
if(colsi[i]!=colsp[i])
return false;
}
return true;
}
private void SaveTables(IDatabase db)
{
foreach(ITable tbl in db.Tables)
{
ShowTable(tbl);
SaveFile("Table_" + tbl.Name);
}
}
private void ShowTable(ITable tbl)
{
output.writeln(string.Format("Table {0}",tbl.Name));
ShowProperties(tbl.AllProperties,2);
ShowColumns(tbl.Columns,2,"Columns:");
ShowColumns(tbl.PrimaryKeys,2,"Primary Key:");
output.writeln(" Foreign Keys:");
foreach(IForeignKey fk in tbl.ForeignKeys)
{
output.writeln(string.Format(" Name: {0} Primary Table: {1}.{2} Foreign Table: {3}"
,fk.Name,fk.PrimaryTable.Name,fk.PrimaryKeyName,fk.ForeignTable.Name));
ShowColumns(fk.PrimaryColumns,6,"Primary Columns:");
ShowColumns(fk.ForeignColumns,6,"Foreign Columns:");
//ShowRequiredColumns(fk.ForeignTable.Columns,6,"Required Foreign Columns:");
}
output.writeln(" Indexes:");
foreach(IIndex ind in tbl.Indexes)
{
if(!IsPrimaryKey(ind))
{
output.writeln(string.Format(" Name: {0} ",ind.Name,(ind.Unique?" Unique":"")));
ShowProperties(ind.AllProperties,6);
ShowColumns(ind.Columns,6,"Columns:");
}
}
}
%><%#FILE NamingConvention.cs%><%
%><%#FILE ForeignKeyProcessing.cs%><%
%><%#FILE FilteredColumns.cs%><%
%><%#FILE FormatColumns.cs%><%
%><%#FILE WriteLine.cs%><%
}
%>
##|BODY_END