/// <summary> /// Gets HTML output for lookup entity. /// </summary> /// <param name="info">The info.</param> /// <param name="relation">The relation.</param> /// <param name="entityName">Name of the entity.</param> /// <param name="namespaceName">Name of the namespace.</param> /// <param name="listOutput">The list output.</param> /// <param name="controlId">The control id.</param> /// <param name="controlType">Type of the control.</param> /// <param name="markupOutput">The markup output.</param> private void GetOutputHtmlLookoupByType(DatabaseColumn info, ChildTableRelation relation, string entityName, string namespaceName, ref List <string> listOutput, out string controlId, out string controlType, out string markupOutput) { controlId = "dropDownList" + info.Name; controlType = "DropDownList"; markupOutput = "<asp:DropDownList runat='server' DataTextField='A' DataValueField='" + relation.ForeignKeyName + "' DataSourceID='objectDataSource" + relation.RelatedTableName + "' id='dropDownList" + info.Name + "' ></asp:DropDownList>"; listOutput.Add("<asp:ObjectDataSource ID='objectDataSource" + relation.RelatedTableName + "' runat='server' TypeName='" + namespaceName + ".Presenters." + entityName + "EditPresenter" + "' SelectMethod='Get" + relation.RelatedTableName + "'></asp:ObjectDataSource>"); }
/// <summary> /// Determines whether [is lookup column] [the specified info]. /// </summary> /// <param name="info">The info.</param> /// <param name="relations">The relations.</param> /// <returns> /// <c>true</c> if [is lookup column] [the specified info]; otherwise, <c>false</c>. /// </returns> private bool IsLookupColumn(DatabaseColumn info, List <TableRelation> relations, out ChildTableRelation selectedRelation) { string name = info.Name; selectedRelation = null; foreach (TableRelation rel in relations) { if (rel is ChildTableRelation) { ChildTableRelation myRelation = (ChildTableRelation)rel; if (info.Name == myRelation.ForeignKeyName) { selectedRelation = myRelation; return(true); } } } return(false); }
/// <summary> /// Generates the mapping files /// </summary> /// <param name="entityNames"></param> /// <param name="tableNames">String array with table names</param> /// <param name="alColumns">ArrayList with columns for each table name</param> /// <param name="alTableRelations"></param> /// <param name="fileName">The file path</param> /// <param name="namespaceName">Namespace name</param> public void GenerateTableMetadatata(string[] entityNames, string[] tableNames, ArrayList alColumns, ArrayList alTableRelations, string fileName, string namespaceName) { if (entityNames.Length != alColumns.Count) { throw new ArgumentException(); } if (!fileName.EndsWith(".cs")) { fileName = fileName + ".cs"; } FileStream fs = null; StreamWriter sw = null; try { if (File.Exists(fileName)) { fs = new FileStream(fileName, FileMode.Truncate, FileAccess.Write); } else { fs = new FileStream(fileName, FileMode.Create, FileAccess.Write); } sw = new StreamWriter(fs); namespaceName = Utilies.RemoveEmptySpaces(namespaceName); //write header; sw.WriteLine("using System;"); sw.WriteLine("using System.Data;"); sw.WriteLine("using voidsoft.DataBlock;"); sw.WriteLine(""); sw.WriteLine("namespace " + namespaceName); sw.WriteLine("{"); for (int i = 0; i < entityNames.Length; i++) { entityNames[i] = Utilies.RemoveEmptySpaces(entityNames[i].Trim()); DatabaseColumn[] column = (DatabaseColumn[])alColumns[i]; sw.WriteLine(""); sw.WriteLine(" [Serializable()]"); sw.WriteLine(" public partial class "+ entityNames[i] + " : TableMetadata"); sw.WriteLine(" {"); sw.WriteLine(""); #region generate the internal enum with myFields sw.WriteLine(" public enum " + entityNames[i] + "Fields"); sw.WriteLine(" {"); for (int ij = 0; ij < column.Length; ij++) { if (ij == column.Length - 1) { sw.WriteLine(" " + column[ij].Name); } else { sw.WriteLine(" " + column[ij].Name + ","); } } sw.WriteLine(" }"); #endregion sw.WriteLine(""); sw.WriteLine(""); sw.WriteLine(" private DatabaseField[] myFields;"); sw.WriteLine(""); #region generate ctor sw.WriteLine(" public "+ entityNames[i] + "()"); sw.WriteLine(" {"); sw.WriteLine(" myFields = new DatabaseField["+ column.Length + "];"); string isPrimaryKey; string isAutoIncremented; for (int x = 0; x < column.Length; x++) { string dataType = column[x].columnDataType; //check the type. If it's a byte[] "rename" it to if (dataType.Trim() == "System.Byte[]") { dataType = "System.Binary"; } isPrimaryKey = column[x].isPrimaryKey.ToString(); isAutoIncremented = column[x].isAutoIncremented.ToString(); //make it lower case for C# isPrimaryKey = isPrimaryKey.ToLower(); isAutoIncremented = isAutoIncremented.ToLower(); sw.WriteLine(" myFields[" + x + "] = new DatabaseField(DbType." + dataType.Substring(dataType.IndexOf(".") + 1) + ",\"" + column[x].Name + "\"," + isPrimaryKey + "," + isAutoIncremented + "," + "null);"); } sw.WriteLine(" "); sw.WriteLine(" this.currentTableName = \"" + tableNames[i] + "\";"); sw.WriteLine(""); List <TableRelation> relations = (List <TableRelation>)alTableRelations[i]; #region generate relations for (int j = 0; j < relations.Count; j++) { //check the realtion type if (relations[j] is ParentTableRelation) { ParentTableRelation pp = (ParentTableRelation)relations[j]; sw.WriteLine("this.listRelations.Add(new ParentTableRelation(\"" + pp.RelatedTableName + "\", \"" + pp.ForeignKeyName + "\"," + "TableRelationCardinality." + pp.RelationCardinality.ToString() + "," + pp.CascadeDeleteChildren.ToString().ToLower() + "));"); } else if (relations[j] is ChildTableRelation) { ChildTableRelation ch = (ChildTableRelation)relations[j]; sw.WriteLine("this.listRelations.Add(new ChildTableRelation(\"" + ch.RelatedTableName + "\",TableRelationCardinality.OneToOne,\"" + ch.RelatedTableKeyName + "\",\"" + ch.ForeignKeyName + "\"));"); } else { //many to many ManyToManyTableRelation mm = (ManyToManyTableRelation)relations[j]; sw.WriteLine("this.listRelations.Add(new ManyToManyTableRelation(\"" + mm.RelatedTableName + "\",\"" + mm.IntermediaryTableName + "\",\"" + mm.IntermediaryKeyFieldFromParentTable + "\",\"" + mm.IntermediaryKeyFieldFromChildTable + "\"));"); } } sw.WriteLine(""); sw.WriteLine(" }"); //end ctor brace. #endregion #endregion //generate DatabasemyFields sw.WriteLine(""); sw.WriteLine(""); sw.WriteLine(" public override DatabaseField[] TableFields "); sw.WriteLine(" {"); sw.WriteLine(" get{ return myFields;}"); sw.WriteLine(" set{myFields = value;}"); sw.WriteLine(" }"); #region Clone sw.WriteLine(" public " + entityNames[i] + " Clone()"); sw.WriteLine(" {"); sw.WriteLine(" return this.Clone<" + entityNames[i] + ">();"); sw.WriteLine(" }"); #endregion #region generate properties with nullable data types for (int x = 0; x < column.Length; x++) { //generate a empty byte[] if (column[x].columnDataType == "System.Byte[]") { sw.WriteLine(""); sw.WriteLine("public " + column[x].columnDataType + " " + column[x].Name); sw.WriteLine("{"); sw.WriteLine(" get"); sw.WriteLine(" {"); sw.WriteLine(" object result = (this.GetField(\"" + column[x].Name + "\")).fieldValue;"); sw.WriteLine(" if(result == null)"); sw.WriteLine(" {"); sw.WriteLine(" return new System.Byte[0];"); sw.WriteLine(" }"); sw.WriteLine(""); sw.WriteLine(" return (" + column[x].columnDataType + ") result;"); // + " (this.GetField(\"" + column[x].Name + "\")).fieldValue;"); sw.WriteLine(" }"); sw.WriteLine(""); sw.WriteLine(" set"); sw.WriteLine(" {"); sw.WriteLine(" this.SetFieldValue(\"" + column[x].Name + "\", value);"); sw.WriteLine(" }"); sw.WriteLine("}"); sw.WriteLine(""); } else if (column[x].columnDataType == "System.String") { sw.WriteLine(""); //generate validation attributes if (generateValidationAttributes) { //not null if (!column[x].allowsNull) { //sw.WriteLine("[EvilAttributes.ValidateRequired(" + column[x].Name + "Null" + ")]"); } //also add size check //sw.WriteLine("[EvilAttributes.ValidateMaxLength(" + column[x].fieldLength + ", " + column[x].Name + "MaxLength" + ")]"); } sw.WriteLine("public " + column[x].columnDataType + " " + column[x].Name); sw.WriteLine("{"); sw.WriteLine(" get"); sw.WriteLine(" {"); sw.WriteLine(" object result = this.GetField(\"" + column[x].Name + "\").fieldValue; "); sw.WriteLine(" return (result != null) ? result.ToString() : null;"); sw.WriteLine(" }"); sw.WriteLine(""); sw.WriteLine(" set"); sw.WriteLine(" {"); sw.WriteLine(" this.SetFieldValue(\"" + column[x].Name + "\", value);"); sw.WriteLine(" }"); sw.WriteLine("}"); sw.WriteLine(""); } else { //generate nullable types for the rest of the columns if (generateValidationAttributes) { if (!column[x].allowsNull) { // sw.WriteLine("[EvilAttributes.ValidateRequired(" + column[x].Name + "Null" + ")]"); } } if (column[x].allowsNull) { sw.WriteLine(""); sw.WriteLine("public " + column[x].columnDataType + "? " + column[x].Name); sw.WriteLine("{"); sw.WriteLine(" get"); sw.WriteLine(" {"); sw.WriteLine(" object result = this.GetField(\"" + column[x].Name + "\").fieldValue; "); sw.WriteLine(" return (result == null || result == DBNull.Value) ? null : (" + column[x].columnDataType + "?) result;"); sw.WriteLine(" }"); sw.WriteLine(""); sw.WriteLine(" set"); sw.WriteLine(" {"); sw.WriteLine(" this.SetFieldValue(\"" + column[x].Name + "\", value);"); sw.WriteLine(" }"); sw.WriteLine("}"); sw.WriteLine(""); } else { sw.WriteLine(""); sw.WriteLine("public " + column[x].columnDataType + " " + column[x].Name); sw.WriteLine("{"); sw.WriteLine(" get"); sw.WriteLine(" {"); sw.WriteLine(" return (" + column[x].columnDataType + ") this.GetField(\"" + column[x].Name + "\").fieldValue; "); sw.WriteLine(" }"); sw.WriteLine(""); sw.WriteLine(" set"); sw.WriteLine(" {"); sw.WriteLine(" this.SetFieldValue(\"" + column[x].Name + "\", value);"); sw.WriteLine(" }"); sw.WriteLine("}"); sw.WriteLine(""); } } } #endregion #region Generate Get methods //generate "Get" methods implementation; for (int j = 0; j < relations.Count; j++) { //check the realtion type if (relations[j] is ParentTableRelation) { ParentTableRelation pp = (ParentTableRelation)relations[j]; if (pp.RelationCardinality == RelationCardinality.OneToOne) { sw.WriteLine("public TableMetadata Get" + Utilies.GetEntityName(pp.RelatedTableName) + "()"); sw.WriteLine("{"); sw.WriteLine(" Type relatedType = Type.GetType(\"" + namespaceName + "." + Utilies.GetEntityName(pp.RelatedTableName) + "\");"); sw.WriteLine(" TableMetadata[] result = this.GetRelatedTableData(relatedType);"); sw.WriteLine(" return result.Length > 0 ? result[0] : null; "); sw.WriteLine("}"); } else if (pp.RelationCardinality == RelationCardinality.OneToMany) { sw.WriteLine("public Array Get" + Utilies.GetEntityName(pp.RelatedTableName) + "()"); sw.WriteLine("{"); sw.WriteLine(" Type relatedType = Type.GetType(\"" + namespaceName + "." + Utilies.GetEntityName(pp.RelatedTableName) + "\");"); sw.WriteLine(" return this.GetRelatedTableData(relatedType);"); sw.WriteLine("}"); } } else if (relations[j] is ChildTableRelation) { ChildTableRelation pp = (ChildTableRelation)relations[j]; sw.WriteLine("public TableMetadata Get" + Utilies.GetEntityName(pp.RelatedTableName) + "()"); sw.WriteLine("{"); sw.WriteLine(" Type relatedType = Type.GetType(\"" + namespaceName + "." + Utilies.GetEntityName(pp.RelatedTableName) + "\");"); sw.WriteLine(" TableMetadata[] result = this.GetRelatedTableData(relatedType);"); sw.WriteLine(" return result.Length > 0 ? result[0] : null; "); sw.WriteLine("}"); } else { ManyToManyTableRelation pp = (ManyToManyTableRelation)relations[j]; sw.WriteLine("public Array Get" + Utilies.GetEntityName(pp.RelatedTableName) + "()"); sw.WriteLine("{"); sw.WriteLine(" Type relatedType = Type.GetType(\"" + namespaceName + "." + Utilies.GetEntityName(pp.RelatedTableName) + "\");"); sw.WriteLine(" Type intermediaryType = Type.GetType(\"" + namespaceName + "." + Utilies.GetEntityName(pp.IntermediaryTableName) + "\");"); sw.WriteLine(" return this.GetRelatedTableData(relatedType, intermediaryType);"); sw.WriteLine("}"); } } #endregion sw.WriteLine("}"); //end class brace } //end namespace brace sw.WriteLine("}"); sw.Flush(); sw.Close(); } catch { throw; } finally { if (sw != null) { sw.Close(); } if (fs != null) { fs.Close(); } } }
/// <summary> /// Writes the edit page presenter. /// </summary> /// <param name="writer">The writer.</param> private void WriteEditPagePresenter(StreamWriter writer) { writer.WriteLine("using System;"); writer.WriteLine("using BusinessObjects;"); writer.WriteLine("using System.Data;"); writer.WriteLine("namespace " + this.parameters.NamespaceName + ".Presenters"); writer.WriteLine("{"); writer.WriteLine("public class " + this.parameters.EntityName + "EditPresenter"); writer.WriteLine("{"); writer.WriteLine(" private " + this.parameters.EntityName + "BusinessObject businessObject;"); writer.WriteLine(""); writer.WriteLine(" public " + this.parameters.EntityName + "EditPresenter()"); writer.WriteLine("{"); writer.WriteLine(" businessObject = new " + this.parameters.EntityName + "BusinessObject();"); writer.WriteLine("}"); writer.WriteLine(" public " + this.parameters.EntityName + " Get" + this.parameters.EntityName + "(int id)"); writer.WriteLine("{"); writer.WriteLine(" return businessObject.Get" + this.parameters.EntityName + "(id);"); writer.WriteLine("}"); writer.WriteLine(" public void Create(" + this.parameters.EntityName + " entity)"); writer.WriteLine("{"); writer.WriteLine(" businessObject.Create(entity);"); writer.WriteLine("}"); writer.WriteLine(" public void Update(" + this.parameters.EntityName + " entity)"); writer.WriteLine("{"); writer.WriteLine(" businessObject.Update(entity);"); writer.WriteLine("}"); foreach (TableRelation tableRelation in this.parameters.Relations) { if (tableRelation is ChildTableRelation) { ChildTableRelation currentRelation = (ChildTableRelation)tableRelation; writer.WriteLine("public DataTable Get" + tableRelation.RelatedTableName + "()"); writer.WriteLine(" {"); writer.WriteLine(tableRelation.RelatedTableName + " entity = new " + tableRelation.RelatedTableName + "();"); writer.WriteLine(currentRelation.RelatedTableName + "BusinessObject businessObject = new " + currentRelation.RelatedTableName + "BusinessObject();"); writer.WriteLine(" QueryCriteria qc = new QueryCriteria(entity.TableName, entity[" + currentRelation.RelatedTableName + "Fields." + currentRelation.ForeignKeyName + "], entity[" + currentRelation.RelatedTableName + "Fields.A]);"); writer.WriteLine(" return businessObject.GetDataTable(qc);"); writer.WriteLine(" }"); } } writer.WriteLine("}"); writer.WriteLine("}"); }
/// <summary> /// Writes the edit page code behind. /// </summary> /// <param name="writer">The writer.</param> private void WriteEditPageCodeBehind(StreamWriter writer) { writer.WriteLine("using System;"); writer.WriteLine("using System.Data;"); writer.WriteLine("using System.Web.UI;"); writer.WriteLine("using " + this.parameters.NamespaceName + ".Presenters;"); writer.WriteLine("namespace " + this.parameters.NamespaceName); writer.WriteLine("{"); writer.WriteLine(" public partial class " + this.parameters.EntityName + "Edit : Page "); writer.WriteLine(" {"); writer.WriteLine(""); writer.WriteLine(" private " + this.parameters.EntityName + "EditPresenter presenter = null;"); writer.WriteLine(""); writer.WriteLine(" public void Page_Load(object sender, EventArgs e)"); writer.WriteLine("{"); writer.WriteLine(" presenter = new " + this.parameters.EntityName + "EditPresenter();"); writer.WriteLine(" if(! this.IsPostBack)"); writer.WriteLine(" { "); writer.WriteLine("if(this.Request[" + "\"" + "id" + "\"" + "] != null)"); writer.WriteLine(" {"); writer.WriteLine(" this.BindData(Convert.ToInt32(this.Request[" + "\"" + "id" + "\"" + "]));"); writer.WriteLine(" }"); writer.WriteLine(" }"); writer.WriteLine("}"); writer.WriteLine("protected void buttonOk_Click(object sender, EventArgs e)"); writer.WriteLine("{"); writer.WriteLine("this.DoAction();"); writer.WriteLine("}"); writer.WriteLine("protected void buttonCancel_Click(object sender, EventArgs e)"); writer.WriteLine("{"); writer.WriteLine(" this.Response.Redirect(" + "\"" + this.parameters.EntityName + "View.aspx" + "\"" + ",true);"); writer.WriteLine("}"); writer.WriteLine("private void BindData(int id)"); writer.WriteLine("{"); writer.WriteLine(" " + this.parameters.EntityName + " entity = this.presenter.Get" + this.parameters.EntityName + "( Convert.ToInt32(this.Request[" + "\"" + "id" + "\"" + "]));"); writer.WriteLine(""); writer.WriteLine(""); foreach (DatabaseColumn columnInfo in this.parameters.Columns) { if (columnInfo.isPrimaryKey) { continue; } ChildTableRelation relation = null; bool isLookupColumns = this.IsLookupColumn(columnInfo, this.parameters.Relations, out relation); List <string> listOutput = new List <string>(); string controlId, controlType, markupCode; if (isLookupColumns) { this.GetOutputHtmlLookoupByType(columnInfo, relation, parameters.EntityName, parameters.NamespaceName, ref listOutput, out controlId, out controlType, out markupCode); writer.WriteLine(" string " + relation.ForeignKeyName + " = entity." + columnInfo.Name + ".ToString();"); writer.WriteLine(controlId + ".DataBind();"); writer.WriteLine("for(int i = 0; i < this." + controlId + ".Items.Count; i++)"); writer.WriteLine("{"); writer.WriteLine(" if( " + controlId + ".Items[i].Value ==" + relation.ForeignKeyName + ")"); writer.WriteLine("{"); writer.WriteLine(" this. " + controlId + ".SelectedIndex = i;"); writer.WriteLine(" break; "); writer.WriteLine("}"); writer.WriteLine("}"); } else { GetOutputHtmlByType(columnInfo, out controlId, out controlType, out markupCode); //add null checks if (columnInfo.allowsNull) { writer.WriteLine("if(entity." + columnInfo.Name + " != null)"); writer.WriteLine("{"); writer.WriteLine(""); } switch (controlType) { case "TextBox": writer.WriteLine("this." + controlId + ".Text = entity. " + columnInfo.Name + ";"); break; case "CheckBox": writer.WriteLine("this." + controlId + ".Checked = Convert.ToBoolean(entity." + columnInfo.Name + ");"); break; case "Calendar": writer.WriteLine("this." + controlId + ".SelectedDate= Convert.ToDateTime(entity." + columnInfo.Name + ");"); break; case "FileUpload": break; } } if (columnInfo.allowsNull) { writer.WriteLine("}"); } } writer.WriteLine("}"); writer.WriteLine(" private void DoAction()"); writer.WriteLine(" {"); writer.WriteLine(" bool isCreate = (this.Request[" + "\"" + "id" + "\"" + "] == null);"); writer.WriteLine(" " + this.parameters.EntityName + " entity = new " + this.parameters.EntityName + "();"); DatabaseColumn primaryKeyInfo = null; //generate create foreach (DatabaseColumn columnInfo in this.parameters.Columns) { if (columnInfo.isPrimaryKey) { primaryKeyInfo = columnInfo; continue; } ChildTableRelation relation = null; bool isLookupColumns = this.IsLookupColumn(columnInfo, this.parameters.Relations, out relation); List <string> listOutput = new List <string>(); string controlId, controlType, markupCode; if (!isLookupColumns) { GetOutputHtmlByType(columnInfo, out controlId, out controlType, out markupCode); string columnType = this.GetElementType(columnInfo); switch (controlType) { case "TextBox": if (columnType == STRING_TYPE) { writer.WriteLine("entity." + columnInfo.Name + "= this." + controlId + ".Text;"); } else { writer.WriteLine("entity." + columnInfo.Name + "= Convert.ToInt32(this." + controlId + ".Text);"); } break; case "CheckBox": writer.WriteLine("entity." + columnInfo.Name + "= this." + controlId + ".Checked;"); break; case "Calendar": writer.WriteLine("entity." + columnInfo.Name + "= this." + controlId + ".SelectedDate;"); break; case "FileUpload": break; } } else { this.GetOutputHtmlLookoupByType(columnInfo, relation, this.parameters.EntityName, this.parameters.NamespaceName, ref listOutput, out controlId, out controlType, out markupCode); writer.WriteLine("entity." + columnInfo.Name + "= Convert.ToInt32(this." + controlId + ".SelectedValue);"); } } if (primaryKeyInfo == null) { throw new ArgumentException("The entity does not have a primary key defined"); } writer.WriteLine(" if(isCreate)"); writer.WriteLine("{"); writer.WriteLine(" presenter.Create(entity);"); writer.WriteLine("}"); writer.WriteLine("else"); writer.WriteLine("{"); writer.WriteLine(" entity." + primaryKeyInfo.Name + "= Convert.ToInt32(this.Request[" + "\"" + "id" + "\"" + "]);"); writer.WriteLine(" presenter.Update(entity);"); writer.WriteLine("}"); writer.WriteLine(" this.Response.Redirect(" + "\"" + this.parameters.EntityName + "View.aspx" + "\"" + ", true);"); writer.WriteLine("}"); writer.WriteLine("}"); writer.WriteLine("}"); }
/// <summary> /// Writes the content of the edit page. /// </summary> /// <param name="writer">The writer.</param> /// <param name="dictionaryControls">The dictionary controls.</param> private void WriteEditPageContent(StreamWriter writer, out Dictionary <string, string> dictionaryControls) { writer.WriteLine("<table width=" + "\"" + "100%" + "\"" + ">"); writer.WriteLine("<tr>"); writer.WriteLine("<td colspan='2' align='center'>"); // writer.WriteLine("<asp:Label ID='labelTitle' runat='server' Text=" + "\"" + this.parameters.EntityName + "\"" + "/>"); writer.WriteLine("<h3>" + this.parameters.EntityName + "</h3>"); writer.WriteLine("</td>"); writer.WriteLine("</tr>"); List <string> listEndOutput = new List <string>(); //key - control name //value - control type dictionaryControls = new Dictionary <string, string>(); foreach (DatabaseColumn ci in this.parameters.Columns) { //skip editing the primary key if (ci.isPrimaryKey) { continue; } writer.WriteLine("<tr>"); writer.WriteLine(" <td align='right'>"); writer.WriteLine(" <asp:Label id='label" + ci.Name + "' runat='server' Text='" + ci.Name + "'></asp:Label>"); writer.WriteLine(" </td>"); dictionaryControls.Add("label" + ci.Name, "Label"); writer.WriteLine(" <td width='50%' valign='top' align='left'>"); ChildTableRelation relation = null; string controlType, controlId, markupCode; if (this.IsLookupColumn(ci, this.parameters.Relations, out relation)) { this.GetOutputHtmlLookoupByType(ci, relation, this.parameters.EntityName, this.parameters.NamespaceName, ref listEndOutput, out controlId, out controlType, out markupCode); } else { this.GetOutputHtmlByType(ci, out controlId, out controlType, out markupCode); } writer.WriteLine(markupCode); dictionaryControls.Add(controlId, controlType); if (ci.allowsNull == false && controlType == "TextBox") { //also add field validators writer.WriteLine("<br/>"); writer.WriteLine("<asp:RequiredFieldValidator ID=" + "\"" + "requiredField" + ci.Name + "\"" + " ControlToValidate='" + controlId + "' runat='server' ErrorMessage='Required field'></asp:RequiredFieldValidator>"); } writer.WriteLine(" </td>"); writer.WriteLine("</tr>"); } writer.WriteLine("<tr>"); writer.WriteLine("<td colspan='2' height='20px'></td>"); writer.WriteLine("</tr>"); writer.WriteLine("<tr>"); writer.WriteLine("<td align='right'>"); writer.WriteLine("<asp:Button runat='server' CausesValidation='true' ID='buttonOK' Text='OK' OnClick='buttonOk_Click' /> "); writer.WriteLine("</td>"); dictionaryControls.Add("buttonOk", "Button"); writer.WriteLine("<td align='left'>"); writer.WriteLine("<asp:Button runat='server' CausesValidation='false' ID='buttonCancel' OnClick='buttonCancel_Click' Text='Cancel' /> "); writer.WriteLine("</td>"); dictionaryControls.Add("buttonCancel", "Button"); writer.WriteLine("</tr>"); writer.WriteLine("</table>"); foreach (string data in listEndOutput) { writer.WriteLine(data); } }
/// <summary> /// </summary> /// <param name="tableNames">String array with table names</param> /// <param name="alColumns">ArrayList with columns for each table name</param> /// <param name="alTableRelations"></param> /// <param name="fileName">The file path</param> /// <param name="namespaceName">Namespace name</param> public void GenerateTableMetadatata(string[] entityNames, string[] tableNames, ArrayList alColumns, ArrayList alTableRelations, string fileName, string namespaceName) { if (entityNames.Length != alColumns.Count) { throw new ArgumentException(); } if (!fileName.EndsWith(".vb")) { fileName = fileName + ".vb"; } FileStream fs = null; StreamWriter sw = null; try { if (File.Exists(fileName)) { fs = new FileStream(fileName, FileMode.Truncate, FileAccess.Write); } else { fs = new FileStream(fileName, FileMode.Create, FileAccess.Write); } sw = new StreamWriter(fs); //write header; sw.WriteLine("Imports System"); sw.WriteLine("Imports System.Data"); sw.WriteLine("Imports voidsoft.DataBlock"); sw.WriteLine(""); sw.WriteLine("Namespace " + namespaceName); sw.WriteLine(" "); for (int i = 0; i < entityNames.Length; i++) { entityNames[i] = entityNames[i].Trim(); DatabaseColumn[] column = (DatabaseColumn[])alColumns[i]; sw.WriteLine(""); sw.WriteLine(" <Serializable()> Public Class " + entityNames[i]); sw.WriteLine(" Inherits TableMetadata"); #region add enum field sw.WriteLine(" Public Enum " + entityNames[i] + "Fields"); for (int k = 0; k < column.Length; k++) { sw.WriteLine(" " + column[k].Name + " = " + (k + 1).ToString()); } sw.WriteLine(" End enum"); #endregion sw.WriteLine(" Private _fields() as DatabaseField"); sw.WriteLine(""); #region generate ctor sw.WriteLine(" Sub New() "); sw.WriteLine(" "); sw.WriteLine(" _fields = new DatabaseField("+ (column.Length - 1) + ") {}"); string isPrimaryKey; string isAutoIncremented; //generate ctor for (int x = 0; x < column.Length; x++) { string dataType = column[x].columnDataType; // ds.Tables[i].Columns[x].DataType.ToString().Substring(ds.Tables[i].Columns[x].DataType.ToString().IndexOf(".") + 1); if (dataType.Trim() == "System.Byte[]") { dataType = "System.Binary"; } isPrimaryKey = column[x].isPrimaryKey.ToString(); isAutoIncremented = column[x].isAutoIncremented.ToString(); sw.WriteLine(" _fields(" + x + ") = new DatabaseField(DbType." + dataType.Substring(dataType.IndexOf(".") + 1) + ",\"" + column[x].Name + "\"," + isPrimaryKey + "," + isAutoIncremented + "," + "Nothing)"); } sw.WriteLine(" "); sw.WriteLine("me.currentTableName = \"" + tableNames[i] + "\""); sw.WriteLine(""); TableRelation[] relations = (TableRelation[])alTableRelations[i]; #region generate relations for (int j = 0; j < relations.Length; j++) { //check the realtion type if (relations[j] is ParentTableRelation) { ParentTableRelation pp = (ParentTableRelation)relations[j]; sw.WriteLine("Me.listRelations.Add(new ParentTableRelation(\"" + pp.RelatedTableName + "\", \"" + pp.ForeignKeyName + "\"," + "TableRelationCardinality." + pp.RelationCardinality.ToString() + "," + pp.CascadeDeleteChildren.ToString() + "))"); } else if (relations[j] is ChildTableRelation) { ChildTableRelation ch = (ChildTableRelation)relations[j]; sw.WriteLine("Me.listRelations.Add(new ChildTableRelation(\"" + ch.RelatedTableName + "\",TableRelationCardinality.OneToOne,\"" + ch.RelatedTableKeyName + "\",\"" + ch.ForeignKeyName + "\"))"); } else { //many to many ManyToManyTableRelation mm = (ManyToManyTableRelation)relations[j]; sw.WriteLine("Me.listRelations.Add(new ManyToManyTableRelation(\"" + mm.RelatedTableName + "\",\"" + mm.IntermediaryTableName + "\",\"" + mm.IntermediaryKeyFieldFromParentTable + "\",\"" + mm.IntermediaryKeyFieldFromChildTable + "\"))"); } } #endregion sw.WriteLine(""); sw.WriteLine("End Sub"); #endregion //generate TableName and DatabaseFields sw.WriteLine(""); sw.WriteLine(""); sw.WriteLine(""); sw.WriteLine(" Public Overrides Property TableFields() as DatabaseField() "); sw.WriteLine(" Get"); sw.WriteLine(" Return _fields"); sw.WriteLine(" End Get"); sw.WriteLine(" Set (ByVal Value as DatabaseField())"); sw.WriteLine(" _fields = value"); sw.WriteLine(" End Set"); sw.WriteLine(" End Property"); #region generate Clone sw.WriteLine(" Public Function Clone() As " + entityNames[i]); sw.WriteLine(" Return Me.Clone(Of " + entityNames[i] + ")"); sw.WriteLine(" End Function"); #endregion #region generate properties for (int x = 0; x < column.Length; x++) { if (column[x].columnDataType == "System.Byte[]") { string dataType = "System.Byte()"; sw.WriteLine(""); sw.WriteLine(" Public Property " + column[x].Name + "() As " + dataType); sw.WriteLine(" Get"); sw.WriteLine(" Dim result As Object = Me.GetField(\"" + column[x].Name + "\").fieldValue"); sw.WriteLine(" If result = Nothing Then"); sw.WriteLine(" Dim data(0) As Byte"); sw.WriteLine(" Return data"); sw.WriteLine(" End If"); sw.WriteLine(" Return CType((Me.GetField(\"" + column[x].Name + "\")).fieldValue," + dataType + ")"); sw.WriteLine(" End Get "); dataType = "System.Byte"; sw.WriteLine(" Set(ByVal Value() As " + dataType + ")"); sw.WriteLine(" Me.SetFieldValue(\"" + column[x].Name + "\", Value)"); sw.WriteLine(" End Set"); sw.WriteLine(" End Property"); } else if (column[x].columnDataType == "System.String") { sw.WriteLine(""); sw.WriteLine(" Public Property " + column[x].Name + " As " + column[x].columnDataType); sw.WriteLine(" Get"); sw.WriteLine(" Return CType((Me.GetField(\"" + column[x].Name + "\")).fieldValue," + column[x].columnDataType + ")"); sw.WriteLine(" End Get "); sw.WriteLine(" Set(ByVal Value As " + column[x].columnDataType + ")"); sw.WriteLine(" Me.SetFieldValue(\"" + column[x].Name + "\", Value)"); sw.WriteLine(" End Set"); sw.WriteLine(" End Property"); } else { //nullable types sw.WriteLine(""); sw.WriteLine(" Public Property " + column[x].Name + " As Nullable(Of " + column[x].columnDataType + ")"); sw.WriteLine(" Get"); sw.WriteLine(" Return CType((Me.GetField(\"" + column[x].Name + "\")).fieldValue," + "Nullable(Of " + column[x].columnDataType + "))"); sw.WriteLine(" End Get "); sw.WriteLine(" Set(ByVal Value As Nullable(Of " + column[x].columnDataType + "))"); sw.WriteLine(" Me.SetFieldValue(\"" + column[x].Name + "\", Value)"); sw.WriteLine(" End Set"); sw.WriteLine(" End Property"); } } #endregion #region generate "Get" methods implementation; for (int j = 0; j < relations.Length; j++) { //check the realtion type if (relations[j] is ParentTableRelation) { ParentTableRelation pp = (ParentTableRelation)relations[j]; if (pp.RelationCardinality == RelationCardinality.OneToOne) { sw.WriteLine("public Function Get" + pp.RelatedTableName + "() As TableMetadata"); sw.WriteLine(" Dim relatedType As Type = Type.GetType(\"" + namespaceName + "." + pp.RelatedTableName + "\")"); sw.WriteLine(" Dim result() As TableMetadata() = Me.GetRelatedTableData(relatedType)"); sw.WriteLine(" If result.Length > 0 Then"); sw.WriteLine(" Return result(0);"); sw.WriteLine(" Else"); sw.WriteLine(" Return Nothing"); sw.WriteLine(" End If"); sw.WriteLine("End Function"); } else if (pp.RelationCardinality == RelationCardinality.OneToMany) { sw.WriteLine("Public Function Get" + pp.RelatedTableName + "() As Array"); sw.WriteLine(" Dim relatedType As Type = Type.GetType(\"" + namespaceName + "." + pp.RelatedTableName + "\")"); sw.WriteLine(" Return Me.GetRelatedTableData(relatedType)"); sw.WriteLine("End Function"); } } else if (relations[j] is ChildTableRelation) { ChildTableRelation pp = (ChildTableRelation)relations[j]; sw.WriteLine("Public Function Get" + pp.RelatedTableName + "() As TableMetadata"); sw.WriteLine(" Dim relatedType As Type = Type.GetType(\"" + namespaceName + "." + pp.RelatedTableName + "\")"); sw.WriteLine(" Dim result() As TableMetadata = Me.GetRelatedTableData(relatedType)"); sw.WriteLine(" If result.Length > 0 Then"); sw.WriteLine(" Return result(0)"); sw.WriteLine(" Else"); sw.WriteLine(" Return Nothing"); sw.WriteLine(" End If"); sw.WriteLine("End Function"); } else { ManyToManyTableRelation pp = (ManyToManyTableRelation)relations[j]; sw.WriteLine("Public Function Get" + pp.RelatedTableName + "() As Array"); sw.WriteLine(" Dim relatedType As Type = Type.GetType(\"" + namespaceName + "." + pp.RelatedTableName + "\")"); sw.WriteLine(" Dim intermediaryType As Type = Type.GetType(\"" + namespaceName + "." + pp.IntermediaryTableName + "\")"); sw.WriteLine(" Return Me.GetRelatedTableData(relatedType, intermediaryType)"); sw.WriteLine("End Function"); } } #endregion } //end namespace brace sw.WriteLine("End Class"); sw.WriteLine("End Namespace"); sw.Flush(); sw.Close(); fs.Close(); } catch { throw; } finally { if (sw != null) { sw.Close(); } if (fs != null) { fs.Close(); } } }
private void buttonOK_Click(object sender, EventArgs e) { //do some checks try { switch (comboBoxRelationType.SelectedIndex) { case 0: if (CheckParentChildRelation()) { //create the relation ParentTableRelation relation = new ParentTableRelation(); this.relation = relation; relation.CascadeDeleteChildren = checkBoxEnableCascadeDelete.Checked; if (comboBoxParentChildRelationCardinality.SelectedIndex == 0) { relation.RelationCardinality = RelationCardinality.OneToOne; } else { relation.RelationCardinality = RelationCardinality.OneToMany; } relation.RelatedTableName = comboBoxParentChildRelatedTable.SelectedItem.ToString(); relation.ForeignKeyName = comboBoxParentChildFields.SelectedItem.ToString(); DialogResult = DialogResult.OK; this.relation = (TableRelation)relation; Close(); } break; case 1: if (CheckChildParentRelation()) { ChildTableRelation relation = new ChildTableRelation(); relation.RelationCardinality = RelationCardinality.OneToOne; relation.RelatedTableName = comboBoxChildParentRelatedTable.SelectedItem.ToString(); relation.RelatedTableKeyName = comboBoxChildParentPrimaryKeyFields.SelectedItem.ToString(); relation.ForeignKeyName = comboBoxChildParentForeignKeyFields.SelectedItem.ToString(); DialogResult = DialogResult.OK; this.relation = (TableRelation)relation; Close(); } break; case 2: if (CheckManyToManyRelation()) { ManyToManyTableRelation relation = new ManyToManyTableRelation(); relation.RelationCardinality = RelationCardinality.ManyToMany; relation.RelatedTableName = comboBoxManyToManyRelatedTable.SelectedItem.ToString(); relation.IntermediaryTableName = comboBoxManyToManyIntermediaryTable.SelectedItem.ToString(); relation.IntermediaryKeyFieldFromChildTable = comboBoxManyToManyIntermediaryForeignKeyRelatedEntity.SelectedItem.ToString(); relation.IntermediaryKeyFieldFromParentTable = comboBoxManyToManyIntermediaryForeignKeyOurEntity.SelectedItem.ToString(); this.relation = (TableRelation)relation; DialogResult = DialogResult.OK; Close(); } break; } } catch (Exception ex) { MessageBox.Show("Error \n" + ex.Message, "DataBlock Modeler", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
internal static void ParseRelation(string[] parts, ref TableRelation relation, ref string tableName) { try { Dictionary <string, string> entries = new Dictionary <string, string>(); foreach (string part in parts) { try { string[] internalPieces = part.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries); if (internalPieces.Length != 2) { continue; } entries.Add(internalPieces[0].Trim().ToLower(), internalPieces[1].Trim()); } catch { continue; } } //check the type string entry; entries.TryGetValue(TYPE, out entry); if (string.IsNullOrEmpty(entry)) { return; } if (entry == CHILD_PARENT) { ChildTableRelation childTableRelation = new ChildTableRelation(); childTableRelation.ForeignKeyName = entries[FOREIGN_KEY_FIELD_NAME]; childTableRelation.RelatedTableName = entries[RELATED_TABLE_NAME]; childTableRelation.RelationCardinality = (RelationCardinality)Enum.Parse(typeof(RelationCardinality), entries[CARDINALITY], true); childTableRelation.RelatedTableKeyName = entries[PRIMARY_KEY_FIELD_NAME]; tableName = entries[TABLE]; relation = childTableRelation; } else if (entry == PARENT_CHILD) { ParentTableRelation parentTableRelation = new ParentTableRelation(); parentTableRelation.RelatedTableName = entries[RELATED_TABLE_NAME]; parentTableRelation.ForeignKeyName = entries[FOREIGN_KEY_FIELD_NAME]; parentTableRelation.RelationCardinality = (RelationCardinality)Enum.Parse(typeof(RelationCardinality), entries[CARDINALITY], true); tableName = entries[TABLE]; parentTableRelation.CascadeDeleteChildren = Convert.ToBoolean(entries[CASCADE_DELETE_CHILDREN]); relation = parentTableRelation; } else if (entry == MANY_TO_MANY) { ManyToManyTableRelation manyTableRelation = new ManyToManyTableRelation(); manyTableRelation.RelatedTableName = entries[RELATED_TABLE_NAME]; manyTableRelation.IntermediaryTableName = entries[INTERMEDIARY_TABLE_NAME]; manyTableRelation.IntermediaryKeyFieldFromParentTable = entries[INTERMEDIARY_KEY_FIELD_FROM_PARENT_TABLE]; manyTableRelation.IntermediaryKeyFieldFromChildTable = entries[INTERMEDIARY_KEY_FIELD_FROM_CHILD_TABLE]; manyTableRelation.RelationCardinality = RelationCardinality.ManyToMany; tableName = entries[TABLE]; relation = manyTableRelation; } } catch { relation = null; } }