Beispiel #1
0
        /// <summary>
        /// Tests to see if a given column is part of the primary key.
        /// </summary>
        /// <param name="elementTable">The table schema to test.</param>
        /// <param name="columnSchema">The column schema to test.</param>
        /// <returns>True if the column belongs to the primary key of the table.</returns>
        public bool IsPrimaryKeyColumn(ColumnSchema columnSchema)
        {
            // Find the primary key of the requested table.
            ConstraintSchema keySchema = PrimaryKey;

            // Test each field in the key to see if the selector matches the given column name.
            if (keySchema != null)
            {
                foreach (ColumnSchema fieldSchema in keySchema.Fields)
                {
                    if (fieldSchema == columnSchema)
                    {
                        return(true);
                    }
                }
            }

            // If there is a base class, then see if this column is part of the base class primary key.
            if (this.BaseTable != null)
            {
                return(this.BaseTable.IsPrimaryKeyColumn(columnSchema));
            }

            // At this point, the column doesn not belong to any of the primary keys in the hiearchy.
            return(false);
        }
Beispiel #2
0
 public KeyrefSchema(DataModelSchema dataModelSchema, XmlSchemaKeyref xmlSchemaKeyref)
     : base(dataModelSchema, xmlSchemaKeyref)
 {
     // Initialize the object
     this.xmlSchemaKeyref = xmlSchemaKeyref;
     this.Refer           = GetRefer(xmlSchemaKeyref);
 }
Beispiel #3
0
 /// <summary>
 /// Generates a property to get a parent row.
 /// </summary>
 /// <param name="keyrefSchema">The foreign key that references the parent table.</param>
 public TableIndexField(ConstraintSchema constraintSchema)
 {
     //			// The DepartmentKey Index
     //			private DepartmentKeyIndex indexDepartmentKey;
     this.Type = new CodeTypeReference(string.Format("{0}Index", constraintSchema.Name));
     this.Name = string.Format("index{0}", constraintSchema.Name);
     this.Comments.Add(new CodeCommentStatement(string.Format("The {0} Index", constraintSchema.Name)));
 }
Beispiel #4
0
        /// <summary>
        /// Generates the method used to find a record given a unique key.
        /// </summary>
        /// <param name="tableSchema">The table to which this method belongs.</param>
        /// <param name="constraintSchema">The constraint used to find the record.</param>
        public TableFindByMethod(TableSchema tableSchema, ConstraintSchema constraintSchema)
        {
            // This construct is used several times to generate the method.
            string rowTypeName = string.Format("{0}Row", tableSchema.Name);

            //			/// <summary>
            //			/// Finds a row in the Department table containing the key elements.
            //			/// </summary>
            //			/// <param name="departmentId">The DepartmentId element of the key.</param>
            //			/// <returns>A DepartmentRow that contains the key elements, or null if there is no match.</returns>
            //			public DepartmentRow FindByDepartmentId(int departmentId)
            //			{
            //				// Use the index to find a row containing the key elements.
            //				try
            //				{
            //					this.ReaderWriterLock.AcquireReaderLock(System.Threading.Timeout.Infinite);
            //					return ((DepartmentRow)(this.Rows.Find(new object[] {
            //								departmentId})));
            //				}
            //				finally
            //				{
            //					this.ReaderWriterLock.ReleaseReaderLock();
            //				}
            //			}
            this.Comments.Add(new CodeCommentStatement("<summary>", true));
            this.Comments.Add(new CodeCommentStatement(string.Format("Finds a row in the {0} table containing the key elements.", tableSchema.Name), true));
            this.Comments.Add(new CodeCommentStatement("</summary>", true));
            foreach (ColumnSchema columnSchema in constraintSchema.Fields)
            {
                string camelCaseColumnName = string.Format("{0}", columnSchema.Name[0].ToString().ToLower() + columnSchema.Name.Remove(0, 1));
                this.Comments.Add(new CodeCommentStatement(string.Format("<param name=\"{0}\">The {1} element of the key.</param>", camelCaseColumnName, columnSchema.Name), true));
            }
            this.Comments.Add(new CodeCommentStatement("<returns>A DepartmentRow that contains the key elements, or null if there is no match.</returns>", true));
            this.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            this.ReturnType = new CodeTypeReference(rowTypeName);
            this.Name       = "FindBy";
            List <CodeExpression> findByArguments = new List <CodeExpression>();

            foreach (ColumnSchema columnSchema in constraintSchema.Fields)
            {
                string camelCaseColumnName = string.Format("{0}", columnSchema.Name[0].ToString().ToLower() + columnSchema.Name.Remove(0, 1));
                this.Name += columnSchema.Name;
                this.Parameters.Add(new CodeParameterDeclarationExpression(columnSchema.DataType, camelCaseColumnName));
                findByArguments.Add(new CodeArgumentReferenceExpression(camelCaseColumnName));
            }
            CodeMethodInvokeExpression   codeMethodInvokeExpression = new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "Rows"), "Find", new CodeArrayCreateExpression(typeof(System.Object), findByArguments.ToArray()));
            CodeTryCatchFinallyStatement tryCatchFinallyStatement   = new CodeTryCatchFinallyStatement();

            tryCatchFinallyStatement.TryStatements.Add(new CodeCommentStatement("The table must be locked to use the index to find a row containing the key elements."));
            tryCatchFinallyStatement.TryStatements.Add(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "ReaderWriterLock"), "AcquireReaderLock", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(System.Threading.Timeout)), "Infinite")));
            tryCatchFinallyStatement.TryStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(rowTypeName, codeMethodInvokeExpression)));
            tryCatchFinallyStatement.FinallyStatements.Add(new CodeCommentStatement("The table can be accessed by other threads once the row is found."));
            tryCatchFinallyStatement.FinallyStatements.Add(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "ReaderWriterLock"), "ReleaseReaderLock"));
            this.Statements.Add(tryCatchFinallyStatement);
        }
        /// <summary>
        /// Add a constraint to the collection.
        /// </summary>
        /// <param name="constraintSchema">A constraint to be added to the collection.</param>
        public void Add(ConstraintSchema constraintSchema)
        {
            // Add the item a collection of constraints ordered by the qualified name.
            int index = this.arrayList.BinarySearch(constraintSchema);

            if (index < 0)
            {
                this.arrayList.Insert(~index, constraintSchema);
            }

            // Broadcast the addition to anyone listening.  For practical purposes, this means the TableSchema that needs to be
            // informed about new relations so it can build relations between the tables.
            if (this.ItemAdded != null)
            {
                this.ItemAdded(this, new ConstraintEventArgs(constraintSchema));
            }
        }
Beispiel #6
0
        /// <summary>
        /// Generate the keys on a table.
        /// </summary>
        /// <param name="streamWriter">The file to which the DDL is written.</param>
        /// <param name="tableSchema">The schema description of the table.</param>
        private static void GenerateKeys(StreamWriter streamWriter, TableSchema tableSchema)
        {
            // This architecture foregoes the 'query' mechanism for finding records in favor of a more direct record identifier.
            // Every table has an implicit key created on the row identifier used to quickly find any given record.
            streamWriter.WriteLine("	/* Unique Constraints */");
            streamWriter.WriteLine("	alter table \"{0}\" with nocheck add ", tableSchema.Name);
            // This will add any additional keys to the table.
            for (int keyIndex = 0; keyIndex < tableSchema.Keys.Count; keyIndex++)
            {
                ConstraintSchema constraintSchema = tableSchema.Keys[keyIndex];

                if (constraintSchema.IsNullable)
                {
                    continue;
                }

                if (constraintSchema.IsPrimaryKey)
                {
                    streamWriter.WriteLine("		constraint \"{0}\" primary key clustered", constraintSchema.Name);
                }
                else
                {
                    streamWriter.WriteLine("		constraint \"{0}\" unique", constraintSchema.Name);
                }
                streamWriter.WriteLine("		(");
                ColumnSchema[] keyFields = constraintSchema.Fields;
                for (int columnIndex = 0; columnIndex < keyFields.Length; columnIndex++)
                {
                    ColumnSchema columnSchema = keyFields[columnIndex];
                    streamWriter.Write("			\"{0}\"", columnSchema.Name);
                    streamWriter.WriteLine(columnIndex == keyFields.Length - 1 ? "" : ",");
                }
                streamWriter.Write("		)  on \"PRIMARY\" ");

                // End with a comment if there are more foreign constraints comming.
                streamWriter.WriteLine(keyIndex < tableSchema.Keys.Count - 1 ? "," : "");
            }
            streamWriter.WriteLine("");

            // Roll the transaction back if the indices can't be created.
            streamWriter.WriteLine("");
        }
Beispiel #7
0
 /// <summary>
 /// Generates a property to get a parent row.
 /// </summary>
 /// <param name="keyrefSchema">The foreign key that references the parent table.</param>
 public TableKeyProperty(ConstraintSchema constraintSchema)
 {
     //			/// <summary>
     //			/// Gets the DepartmentKey index on the Department table.
     //			/// </summary>
     //			public DepartmentKeyIndex DepartmentKey
     //			{
     //				get
     //				{
     //					return this.indexDepartmentKey;
     //				}
     //			}
     this.Comments.Add(new CodeCommentStatement("<summary>", true));
     this.Comments.Add(new CodeCommentStatement(string.Format("Gets the {0} index on the {1} table.", constraintSchema.Name, constraintSchema.Selector.Name), true));
     this.Comments.Add(new CodeCommentStatement("</summary>", true));
     this.Attributes = MemberAttributes.Public | MemberAttributes.Final;
     this.Type       = new CodeTypeReference(string.Format("{0}Index", constraintSchema.Name));
     this.Name       = constraintSchema.Name;
     this.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), string.Format("index{0}", constraintSchema.Name))));
 }
Beispiel #8
0
        /// <summary>
        /// Compares a ConstraintSchema to another object.
        /// </summary>
        /// <param name="obj">The object to be compared.</param>
        /// <returns>-1 if this object is less than the specified object, -1 if it is greater and 0 if they are equal.</returns>
        public int CompareTo(object obj)
        {
            // Compare the object to an XmlQualifiedName.
            if (obj is XmlQualifiedName)
            {
                XmlQualifiedName xmlQualifiedName = obj as XmlQualifiedName;
                int compare = this.QualifiedName.Namespace.CompareTo(xmlQualifiedName.Namespace);
                return(compare == 0 ? this.QualifiedName.Name.CompareTo(xmlQualifiedName.Name) : compare);
            }

            // Compare the object to another ConstraintSchema.
            if (obj is ConstraintSchema)
            {
                ConstraintSchema constraintSchema = obj as ConstraintSchema;
                int compare = this.QualifiedName.Namespace.CompareTo(constraintSchema.QualifiedName.Namespace);
                return(compare == 0 ? this.QualifiedName.Name.CompareTo(constraintSchema.Name) : compare);
            }

            // No other comparisons are recognized.
            throw new Exception(string.Format("The method or operation is not implemented for a {0} type.", obj.GetType()));
        }
Beispiel #9
0
        /// <summary>
        /// Indicates that a column is an identity column.
        /// </summary>
        /// <param name="columnSchema">The description of a column.</param>
        /// <returns>true if the column has an internally generated identifier.</returns>
        public bool IsIdentityColumn(ColumnSchema columnSchema)
        {
            if (columnSchema.IsAutoIncrement)
            {
                return(true);
            }

            // See if the column may is part of an identity column in the base table.
            TableSchema baseTable = this.BaseTable;

            if (baseTable != null)
            {
                // See if the column is the identity column in the base table.
                if (baseTable.IsIdentityColumn(columnSchema))
                {
                    return(true);
                }

                // If the column is part of the primary key, then it's possible that the column is an identity column through a
                // primary key relation.
                ConstraintSchema keySchema = this.PrimaryKey;
                if (keySchema != null && keySchema.Fields.Length == 1 && keySchema.Fields[0] == columnSchema)
                {
                    // See if the column is related to an identity column through the primary index.
                    ConstraintSchema baseKeySchema    = baseTable.PrimaryKey;
                    KeyrefSchema     baseKeyRefSchema = this.FindForeignKey(new ColumnSchema[] { columnSchema });
                    if (baseKeyRefSchema != null && baseKeyRefSchema.Refer == baseKeySchema)
                    {
                        if (baseKeySchema.Fields.Length == 1)
                        {
                            ColumnSchema baseColumnSchema = baseTable.Columns[baseKeySchema.Fields[0].QualifiedName];
                            return(baseTable.IsExternalIdColumn(baseColumnSchema));
                        }
                    }
                }
            }

            return(false);
        }
Beispiel #10
0
        /// <summary>
        /// Creates the CodeDOM for a strongly typed index on a table.
        /// </summary>
        /// <param name="schema">The parent schema.</param>
        /// <param name="keySchema">The key schema.</param>
        public TypedPrimaryIndexClass(ConstraintSchema constraintSchema)
        {
            // Initialize the object.
            this.constraintSchema = constraintSchema;

            // Construct the type names for the table and rows within the table.
            string indexTypeName = string.Format("{0}Index", constraintSchema.Name);
            string indexRowName  = string.Format("{0}Row", constraintSchema.Selector.Name);

            //		/// <summary>
            //		/// Represents a means of identifying a Department row using a set of columns in which all values must be unique.
            //		/// </summary>
            //		[System.Diagnostics.DebuggerStepThrough()]
            //		public class DepartmentKeyIndex
            //		{
            this.Comments.Add(new CodeCommentStatement("<summary>", true));
            this.Comments.Add(new CodeCommentStatement(string.Format("Represents a means of identifying a {0} row using a set of columns in which all values must be unique.", constraintSchema.Selector.Name), true));
            this.Comments.Add(new CodeCommentStatement("</summary>", true));
            CodeTypeDeclaration tableClass = new CodeTypeDeclaration();

            this.IsClass        = true;
            this.Name           = indexTypeName;
            this.TypeAttributes = TypeAttributes.Public;
            this.CustomAttributes.Add(new CodeAttributeDeclaration("System.Diagnostics.DebuggerStepThrough"));

            //			// Primary indicies use the primary key of the table to find the rows.
            //			private Table table;
            CodeMemberField tableField = new CodeMemberField();

            tableField.Comments.Add(new CodeCommentStatement("Primary indicies use the primary key of the table to find the rows."));
            tableField.Attributes = MemberAttributes.Private;
            tableField.Type       = new CodeTypeReference("Table");
            tableField.Name       = "table";
            this.Members.Add(tableField);

            //			/// <summary>
            //			/// Create a unique, primary index on the Department table.
            //			/// </summary>
            //			/// <param name="name">The name of the index.</param>
            //			/// <param name="columns">The columns that describe a unique key.</param>
            //			public DepartmentKeyIndex(Column[] columns)
            //			{
            //				// While technically an index could be created with no columns, it would require a run-time check that would
            //				// needlessly steal processor power.
            //				if ((columns.Length == 0))
            //					throw new Exception("Can't create an index with an empty key");
            //				// The primary index uses the native 'Find' method of the base table to search for records.
            //				this.table = columns[0].Table;
            //				this.table.PrimaryKey = columns;
            //			}
            CodeConstructor constructor = new CodeConstructor();

            constructor.Comments.Add(new CodeCommentStatement("<summary>", true));
            constructor.Comments.Add(new CodeCommentStatement(string.Format("Create a primary, unique index on the {0} table.", constraintSchema.Selector.Name), true));
            constructor.Comments.Add(new CodeCommentStatement("</summary>", true));
            constructor.Comments.Add(new CodeCommentStatement("<param name=\"columns\">The columns that describe a unique key.</param>", true));
            constructor.Attributes = MemberAttributes.Public;
            constructor.Name       = indexTypeName;
            constructor.Parameters.Add(new CodeParameterDeclarationExpression("Column[]", "columns"));
            constructor.Statements.Add(new CodeCommentStatement("While technically an index could be created with no columns, it would require a run-time check that would"));
            constructor.Statements.Add(new CodeCommentStatement("needlessly steal processor power."));
            List <CodeStatement> constructorTrueStatements = new List <CodeStatement>();

            constructorTrueStatements.Add(new CodeThrowExceptionStatement(new CodeObjectCreateExpression(typeof(System.Exception), new CodePrimitiveExpression("Can't create an index with an empty key"))));
            constructor.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(new CodeArgumentReferenceExpression("columns"), "Length"), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(0)), constructorTrueStatements.ToArray()));
            constructor.Statements.Add(new CodeCommentStatement("The primary index uses the native 'Find' method of the base table to search for records."));
            constructor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "table"), new CodeFieldReferenceExpression(new CodeIndexerExpression(new CodeArgumentReferenceExpression("columns"), new CodePrimitiveExpression(0)), "Table")));
            constructor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "table"), "PrimaryKey"), new CodeArgumentReferenceExpression("columns")));
            this.Members.Add(constructor);

            CodeMemberMethod findByPrimaryKey = new CodeMemberMethod();

            findByPrimaryKey.Comments.Add(new CodeCommentStatement("<summary>", true));
            findByPrimaryKey.Comments.Add(new CodeCommentStatement(string.Format("Finds a row in the {0} table containing the key elements.", this.constraintSchema.Selector.Name), true));
            findByPrimaryKey.Comments.Add(new CodeCommentStatement("</summary>", true));
            foreach (ColumnSchema columnSchema in constraintSchema.Fields)
            {
                string camelCaseColumnName = string.Format("{0}", columnSchema.Name[0].ToString().ToLower() + columnSchema.Name.Remove(0, 1));
                findByPrimaryKey.Comments.Add(new CodeCommentStatement(string.Format("<param name=\"{0}\">The {1} element of the key.</param>", camelCaseColumnName, columnSchema.Name), true));
            }
            findByPrimaryKey.Comments.Add(new CodeCommentStatement("<returns>A DepartmentRow that contains the key elements, or null if there is no match.</returns>", true));
            findByPrimaryKey.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            findByPrimaryKey.ReturnType = new CodeTypeReference(indexRowName);
            findByPrimaryKey.Name       = "Find";
            List <CodeExpression> findByArguments = new List <CodeExpression>();

            foreach (ColumnSchema columnSchema in constraintSchema.Fields)
            {
                string camelCaseColumnName = string.Format("{0}", columnSchema.Name[0].ToString().ToLower() + columnSchema.Name.Remove(0, 1));
                findByPrimaryKey.Parameters.Add(new CodeParameterDeclarationExpression(columnSchema.DataType, camelCaseColumnName));
                findByArguments.Add(new CodeArgumentReferenceExpression(camelCaseColumnName));
            }
            CodeMethodInvokeExpression codeMethodInvokeExpression = new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "table"), "Rows"), "Find", new CodeArrayCreateExpression(typeof(System.Object), findByArguments.ToArray()));

            findByPrimaryKey.Statements.Add(new CodeCommentStatement("Use the base table to find a row containing the key elements."));
            findByPrimaryKey.Statements.Add(new CodeMethodReturnStatement(new CodeCastExpression(indexRowName, codeMethodInvokeExpression)));
            this.Members.Add(findByPrimaryKey);

            //		}
        }
 public void Add(ConstraintSchema constraintSchema)
 {
     this.constraintList.Add(constraintSchema.Name, constraintSchema);
 }
Beispiel #12
0
        /// <summary>
        /// Creates a method to delete a record in the ADO database.
        /// </summary>
        /// <param name="coreInterfaceClass"></param>
        /// <param name="this.TableSchema.ElementTable"></param>
        private void ArchiveWithoutBase()
        {
            // Shorthand notations for the elements used to construct the interface to this table:
            string tableTypeName     = string.Format("{0}.{1}DataTable", this.ServerSchema.Name, this.TableSchema.Name);
            string tableVariableName = string.Format("{0}Table", this.TableSchema.Name[0].ToString().ToLower() + this.TableSchema.Name.Remove(0, 1));
            string rowTypeName       = string.Format("{0}.{1}Row", this.ServerSchema.Name, this.TableSchema.Name);
            string rowVariableName   = string.Format("{0}Row", this.TableSchema.Name[0].ToString().ToLower() + this.TableSchema.Name.Remove(0, 1));

            // Method Header:
            //        /// <summary>Archives a Algorithm record.</summary>
            //        /// <param name="transaction">Commits or rejects a set of commands as a unit</param>
            //        /// <param name="algorithmId">The value for the AlgorithmId column.</param>
            //        /// <param name="rowVersion">The value for the RowVersion column.</param>
            //        public static void Archive(Transaction transaction, int algorithmId, long rowVersion)
            //        {
            this.Comments.Add(new CodeCommentStatement(string.Format("<summary>Archives a {0} record.</summary>", this.TableSchema.Name), true));
            this.Comments.Add(new CodeCommentStatement(@"<param name=""transaction"">Commits or rejects a set of commands as a unit</param>", true));
            this.Comments.Add(new CodeCommentStatement(@"<param name=""RowVersion"">The version number of this row.</param>", true));
            foreach (ColumnSchema columnSchema in this.TableSchema.Columns)
            {
                if (this.TableSchema.IsPrimaryKeyColumn(columnSchema))
                {
                    string variableName = columnSchema.Name[0].ToString().ToLower() + columnSchema.Name.Remove(0, 1);
                    this.Comments.Add(new CodeCommentStatement(string.Format(@"<param name=""{0}"">The value for the {1} column.</param>", variableName, columnSchema.Name), true));
                }
            }
            this.Comments.Add(new CodeCommentStatement(@"<param name=""archive"">true to archive the object, false to unarchive it.</param>", true));
            this.Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static;
            if (this.TableSchema.BaseTable != null)
            {
                this.Attributes |= MemberAttributes.New;
            }
            this.Name = "Archive";
            this.Parameters.Add(new CodeParameterDeclarationExpression("AdoTransaction", "adoTransaction"));
            this.Parameters.Add(new CodeParameterDeclarationExpression("SqlTransaction", "sqlTransaction"));
            this.Parameters.Add(new CodeParameterDeclarationExpression(typeof(long), "rowVersion"));
            foreach (ColumnSchema columnSchema in this.TableSchema.Columns)
            {
                if (this.TableSchema.IsPrimaryKeyColumn(columnSchema))
                {
                    string variableName = columnSchema.Name[0].ToString().ToLower() + columnSchema.Name.Remove(0, 1);
                    this.Parameters.Add(new CodeParameterDeclarationExpression(columnSchema.DataType, variableName));
                }
            }

            // Get an accessor to the table schema information.  This makes accessing information about the table much faster as
            // it doesn't need to do the lock checking each time it references the table.
            //            // Accessor for the Algorithm Table.
            //            ServerMarketData.AlgorithmDataTable algorithmTable = ServerMarketData.Algorithm;
            this.Statements.Add(new CodeCommentStatement(string.Format("Accessor for the {0} Table.", this.TableSchema.Name)));
            this.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(tableTypeName), tableVariableName, new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(this.ServerSchema.Name), this.TableSchema.Name)));

            // Rule #1: Make sure the record exists.
            //            // Rule #1: Make sure the record exists before updating it.
            //            ServerMarketData.AlgorithmRow algorithmRow = algorithmTable.FindByAlgorithmId(algorithmId);
            //            if ((algorithmRow == null))
            //            {
            //                throw new Exception(string.Format("The Algorithm table does not have an element identified by {0}", algorithmId));
            //            }
            this.Statements.Add(new CodeCommentStatement(string.Format("Rule #1: Make sure the record exists before updating it.", this.TableSchema.Name)));
            string keyColumns     = string.Empty;
            string exeptionFormat = string.Empty;

            CodeExpression[] keyVariables       = new CodeExpression[this.TableSchema.PrimaryKey.Fields.Length];
            CodeExpression[] exceptionVariables = new CodeExpression[this.TableSchema.PrimaryKey.Fields.Length + 1];
            for (int index = 0; index < this.TableSchema.PrimaryKey.Fields.Length; index++)
            {
                string columnName   = this.TableSchema.PrimaryKey.Fields[index].Name;
                string variableName = columnName[0].ToString().ToLower() + columnName.Remove(0, 1);
                keyColumns                   += columnName;
                exeptionFormat               += string.Format("{{0}}", index);
                keyVariables[index]           = new CodeVariableReferenceExpression(variableName);
                exceptionVariables[index + 1] = new CodeVariableReferenceExpression(variableName);
            }
            exceptionVariables[0] = new CodePrimitiveExpression(string.Format("The {0} table does not have an element identified by {1}", this.TableSchema.Name, exeptionFormat));
            this.Statements.Add(new CodeVariableDeclarationStatement(rowTypeName, rowVariableName, new CodeMethodInvokeExpression(new CodeArgumentReferenceExpression(tableVariableName), string.Format("FindBy{0}", keyColumns), keyVariables)));
            this.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression(rowVariableName), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null)), new CodeThrowExceptionStatement(new CodeObjectCreateExpression("Exception", new CodeExpression[] { new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(string)), "Format", exceptionVariables) }))));

            // Rule #2: Optimistic Concurrency Check.
            //            // Rule #2: Optimistic Concurrency Check
            //            if ((algorithmRow.RowVersion != rowVersion))
            //            {
            //                throw new System.Exception("This record is busy.  Please try again later.");
            //            }
            this.Statements.Add(new CodeCommentStatement("Rule #2: Optimistic Concurrency Check"));
            CodeStatement[] trueTest2Array = new CodeStatement[] { new CodeThrowExceptionStatement(new CodeObjectCreateExpression(typeof(System.Exception), new CodeExpression[] { new CodePrimitiveExpression("This record is busy.  Please try again later.") })) };
            this.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(rowVariableName), "RowVersion"), CodeBinaryOperatorType.IdentityInequality, new CodeVariableReferenceExpression("rowVersion")), trueTest2Array));

            //			// Archive the child records.
            //			for (int index = 0; index < securityRow.GetBlotterMapRows().Length; index = index)
            //			{
            //				ServerMarketData.BlotterMapRow blotterMapRow = securityRow.GetBlotterMapRows()[index];
            //				BlotterMap.Archive(transaction, blotterMapRow.BlotterMapId, blotterMapRow.RowVersion);
            //			}
            this.Statements.Add(new CodeCommentStatement("Archive the child records."));
            foreach (KeyrefSchema outerChild in this.TableSchema.ChildKeyrefs)
            {
                TableSchema childTable = outerChild.Selector;
                if (childTable == this.TableSchema)
                {
                    continue;
                }
                string           childRowTypeName     = string.Format("{0}Row", childTable.Name);
                string           childRowVariableName = string.Format("child{0}Row", childTable.Name);
                string           getRowMethodName     = string.Format("Get{0}Rows", childTable.Name);
                ConstraintSchema childPrimaryKey      = outerChild.Refer;

                foreach (KeyrefSchema innerChild in this.TableSchema.ChildKeyrefs)
                {
                    if (outerChild != innerChild && outerChild.Selector == innerChild.Selector)
                    {
                        getRowMethodName = string.Format("Get{0}RowsBy{1}", childTable.Name, outerChild.Name);
                        break;
                    }
                }

                CodeStatement    initStatement      = new CodeVariableDeclarationStatement(typeof(int), "index", new CodePrimitiveExpression(0));
                CodeExpression   testExpression     = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("index"), CodeBinaryOperatorType.LessThan, new CodeFieldReferenceExpression(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(rowVariableName), getRowMethodName, new CodeExpression[] {}), "Length"));
                CodeStatement    incrementStatement = new CodeAssignStatement(new CodeVariableReferenceExpression("index"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("index"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1)));
                CodeStatement    getRow             = new CodeVariableDeclarationStatement(new CodeTypeReference(string.Format("{0}.{1}", this.ServerSchema.Name, childRowTypeName)), childRowVariableName, new CodeArrayIndexerExpression(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(rowVariableName), getRowMethodName, new CodeExpression[] {}), new CodeExpression[] { new CodeVariableReferenceExpression("index") }));
                CodeExpression[] deleteArguments    = new CodeExpression[childPrimaryKey.Fields.Length + 3];
                deleteArguments[0] = new CodeArgumentReferenceExpression("adoTransaction");
                deleteArguments[1] = new CodeArgumentReferenceExpression("sqlTransaction");
                deleteArguments[2] = new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(childRowVariableName), "RowVersion");
                for (int index = 0; index < childPrimaryKey.Fields.Length; index++)
                {
                    deleteArguments[index + 3] = new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(childRowVariableName), childPrimaryKey.Fields[index].Name);
                }
                string        methodName      = childTable.BaseTable == null ? "Archive" : "ArchiveChildren";
                CodeStatement deleteStatement = new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(childTable.Name), methodName, deleteArguments));
                this.Statements.Add(new CodeIterationStatement(initStatement, testExpression, incrementStatement, new CodeStatement[] { getRow, deleteStatement }));
            }

            // Assign a RowVersion
            //            // Increment the row version.
            //            rowVersion = ServerMarketData.RowVersion.Increment();
            this.Statements.Add(new CodeCommentStatement("Increment the row version"));
            this.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("rowVersion"), new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(this.ServerSchema.Name), "RowVersion"), "Increment", new CodeExpression[] {})));

            // Delete the record in the ADO database.
            //            // Delete the record in the ADO database.
            //            transaction.AdoTransaction.DataRows.Add(algorithmRow);
            //            algorithmRow.Delete();
            this.Statements.Add(new CodeCommentStatement("Delete the record in the ADO database."));
            this.Statements.Add(new CodeAssignStatement(new CodeArrayIndexerExpression(new CodeVariableReferenceExpression(rowVariableName), new CodeExpression[] { new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tableVariableName), "RowVersionColumn") }), new CodeVariableReferenceExpression("rowVersion")));
            this.Statements.Add(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeArgumentReferenceExpression("adoTransaction"), "DataRows"), "Add", new CodeExpression[] { new CodeVariableReferenceExpression(rowVariableName) }));
            this.Statements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(rowVariableName), "Delete", new CodeExpression[] {}));

            // If the table is persistent, then it will be deleted from the SQL database.
            if (this.TableSchema.IsPersistent)
            {
                // Archive the record in the SQL database
                //            // Archive the record in the SQL database.
                //            SqlCommand sqlCommand = new SqlCommand("delete Algorithm where AlgorithmId=@algorithmId");
                //            sqlCommand.Connection = transaction.SqlTransaction.Connection;
                //            sqlCommand.Transaction = transaction.SqlTransaction;
                //            sqlCommand.Parameters.Add("@algorithmId", @algorithmId);
                //            sqlCommand.ExecuteNonQuery();
                this.Statements.Add(new CodeCommentStatement("Archive the record in the SQL database."));
                string whereList = string.Empty;
                foreach (ColumnSchema columnSchema in this.TableSchema.Columns)
                {
                    if (this.TableSchema.IsPrimaryKeyColumn(columnSchema))
                    {
                        string variableName       = columnSchema.Name[0].ToString().ToLower() + columnSchema.Name.Remove(0, 1);
                        bool   isPrimaryKeyColumn = this.TableSchema.IsPrimaryKeyColumn(columnSchema);

                        if (columnSchema.IsPersistent)
                        {
                            if (isPrimaryKeyColumn)
                            {
                                whereList += (whereList == string.Empty ? string.Empty : " and ") + string.Format("\"{0}\"=@{1}", columnSchema.Name, variableName);
                            }
                        }
                        else
                        {
                            if (isPrimaryKeyColumn)
                            {
                                throw new Exception(string.Format("Primary key element {0} in table {1} is not doesn't exist in the SQL database.", columnSchema.Name, this.TableSchema.Name));
                            }
                        }
                    }
                }
                string deleteCommandText = string.Format("update \"{0}\" set \"IsArchived\" = 1 where {1}", this.TableSchema.Name, whereList);
                this.Statements.Add(new CodeVariableDeclarationStatement("SqlCommand", "sqlCommand", new CodeObjectCreateExpression("SqlCommand", new CodeExpression[] { new CodePrimitiveExpression(deleteCommandText) })));
                this.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("sqlCommand"), "Connection"), new CodeFieldReferenceExpression(new CodeArgumentReferenceExpression("sqlTransaction"), "Connection")));
                this.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("sqlCommand"), "Transaction"), new CodeArgumentReferenceExpression("sqlTransaction")));
                foreach (ColumnSchema columnSchema in this.TableSchema.Columns)
                {
                    if (this.TableSchema.IsPrimaryKeyColumn(columnSchema) && columnSchema.IsPersistent)
                    {
                        string         variableName   = string.Format("{0}", columnSchema.Name[0].ToString().ToLower() + columnSchema.Name.Remove(0, 1));
                        CodeExpression dataExpression = (CodeExpression) new CodeArgumentReferenceExpression(variableName);
                        this.Statements.Add(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("sqlCommand"), "Parameters"), "Add", new CodeExpression[] { new CodeObjectCreateExpression("SqlParameter", new CodeExpression[] { new CodePrimitiveExpression(string.Format("@{0}", variableName)), TypeConverter.Convert(columnSchema.DataType), new CodePrimitiveExpression(0), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("ParameterDirection"), "Input"), new CodePrimitiveExpression(false), new CodePrimitiveExpression(0), new CodePrimitiveExpression(0), new CodePrimitiveExpression(null), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DataRowVersion"), "Current"), dataExpression }) }));
                    }
                }
                this.Statements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("sqlCommand"), "ExecuteNonQuery", new CodeExpression[] {}));
            }
        }
Beispiel #13
0
        /// <summary>
        /// Creates the CodeDOM for a strongly typed index on a table.
        /// </summary>
        /// <param name="schema">The parent schema.</param>
        /// <param name="keySchema">The key schema.</param>
        public IndexClass(ConstraintSchema constraintSchema)
        {
            // Initialize the object.
            this.constraintSchema = constraintSchema;

            // Construct the type names for the table and rows within the table.
            string indexTypeName = string.Format("{0}Index", constraintSchema.Name);
            string indexRowName  = string.Format("{0}Row", constraintSchema.Selector.Name);

            //		/// <summary>
            //		/// Represents a means of identifying a Department row using a set of columns in which all values must be unique.
            //		/// </summary>
            //		[System.Diagnostics.DebuggerStepThrough()]
            //		public class DepartmentKeyIndex
            //		{
            this.Comments.Add(new CodeCommentStatement("<summary>", true));
            this.Comments.Add(new CodeCommentStatement(string.Format("Represents a means of identifying a {0} row using a set of columns in which all values must be unique.", constraintSchema.Selector.Name), true));
            this.Comments.Add(new CodeCommentStatement("</summary>", true));
            CodeTypeDeclaration tableClass = new CodeTypeDeclaration();

            this.IsClass        = true;
            this.Name           = indexTypeName;
            this.TypeAttributes = TypeAttributes.Public;
            this.CustomAttributes.Add(new CodeAttributeDeclaration("System.Diagnostics.DebuggerStepThrough"));

            //			// A non-primary index is created using a DataView find rows matching the keys.
            //			private DataView dataView;
            CodeMemberField dataViewField = new CodeMemberField();

            dataViewField.Comments.Add(new CodeCommentStatement("A non-primary index is created using a DataView find rows matching the keys."));
            dataViewField.Attributes = MemberAttributes.Private;
            dataViewField.Type       = new CodeTypeReference(typeof(System.Data.DataView));
            dataViewField.Name       = "dataView";
            this.Members.Add(dataViewField);

            //			/// <summary>
            //			/// Create an index on the Object table.
            //			/// </summary>
            //			/// <param name="name">The name of the index.</param>
            //			/// <param name="columns">The columns that describe a unique key.</param>
            //			public ObjectKeyExternalId0Index(Column[] columns)
            //			{
            CodeConstructor constructor = new CodeConstructor();

            constructor.Comments.Add(new CodeCommentStatement("<summary>", true));
            constructor.Comments.Add(new CodeCommentStatement(string.Format("Create an index on the {0} table.", constraintSchema.Selector.Name), true));
            constructor.Comments.Add(new CodeCommentStatement("</summary>", true));
            constructor.Comments.Add(new CodeCommentStatement("<param name=\"name\">The name of the index.</param>", true));
            constructor.Comments.Add(new CodeCommentStatement("<param name=\"columns\">The columns that describe a unique key.</param>", true));
            constructor.Attributes = MemberAttributes.Public;
            constructor.Name       = indexTypeName;
            constructor.Parameters.Add(new CodeParameterDeclarationExpression("Column[]", "columns"));

            //				// The DataView is used to implement an index on the table that can be used to find elements.
            //				this.dataView = new System.Data.DataView();
            constructor.Statements.Add(new CodeCommentStatement("The DataView is used to implement an index on the table that can be used to find elements."));
            constructor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "dataView"), new CodeObjectCreateExpression(typeof(System.Data.DataView))));

            //				// When a meaningful key is specified, the DataView is used to find current rows containing non-null values in the
            //				// specified columns that match key elements.
            //				if ((columns.Length != 0))
            //				{
            constructor.Statements.Add(new CodeCommentStatement("When a meaningful key is specified, the DataView is used to find current rows containing non-null values in the "));
            constructor.Statements.Add(new CodeCommentStatement("specified columns that match key elements."));
            List <CodeStatement> constructorTrueStatements = new List <CodeStatement>();

            //					// This will construct the strings that the DataView uses to sort and filter the rows.  Note that only non-null
            //					// keys are allowed into the view.
            //					string sort = string.Empty;
            //					string rowFilter = string.Empty;
            //					for (int columnIndex = 0; (columnIndex < columns.Length); columnIndex = (columnIndex + 1))
            //					{
            //						Column column = columns[columnIndex];
            //						if ((columnIndex
            //									< (columns.Length - 1)))
            //						{
            //							sort = string.Format("{0}{1},", sort, column.ColumnName);
            //							rowFilter = string.Format("{0}IsNull({1}, \'null\')<>\'null\',", rowFilter, column.ColumnName);
            //						}
            //						else
            //						{
            //							sort = string.Format("{0}{1}", sort, column.ColumnName);
            //							rowFilter = string.Format("{0}IsNull({1}, \'null\')<>\'null\'", rowFilter, column.ColumnName);
            //						}
            //					}
            constructorTrueStatements.Add(new CodeCommentStatement("This will construct the strings that the DataView uses to sort and filter the rows.  Note that only non-null"));
            constructorTrueStatements.Add(new CodeCommentStatement("keys are allowed into the view."));
            constructorTrueStatements.Add(new CodeVariableDeclarationStatement(typeof(System.String), "sort", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(System.String)), "Empty")));
            List <CodeStatement> constructorIterationStatements = new List <CodeStatement>();

            constructorIterationStatements.Add(new CodeVariableDeclarationStatement("Column", "column", new CodeIndexerExpression(new CodeVariableReferenceExpression("columns"), new CodeVariableReferenceExpression("columnIndex"))));
            constructorIterationStatements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("columnIndex"), CodeBinaryOperatorType.LessThan, new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(new CodeArgumentReferenceExpression("columns"), "Length"), CodeBinaryOperatorType.Subtract, new CodePrimitiveExpression(1))),
                                                                          new CodeStatement[] {
                new CodeAssignStatement(new CodeVariableReferenceExpression("sort"), new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(System.String)), "Format"), new CodePrimitiveExpression("{0}{1},"), new CodeVariableReferenceExpression("sort"), new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("column"), "ColumnName"))),
            },
                                                                          new CodeStatement[] {
                new CodeAssignStatement(new CodeVariableReferenceExpression("sort"), new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(System.String)), "Format"), new CodePrimitiveExpression("{0}{1}"), new CodeVariableReferenceExpression("sort"), new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("column"), "ColumnName"))),
            }));
            constructorTrueStatements.Add(new CodeIterationStatement(new CodeVariableDeclarationStatement(typeof(System.Int32), "columnIndex", new CodePrimitiveExpression(0)),
                                                                     new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("columnIndex"), CodeBinaryOperatorType.LessThan, new CodeFieldReferenceExpression(new CodeArgumentReferenceExpression("columns"), "Length")),
                                                                     new CodeAssignStatement(new CodeVariableReferenceExpression("columnIndex"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("columnIndex"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1))),
                                                                     constructorIterationStatements.ToArray()));

            //					// This DataView will be used to find the current rows in the Department table that contain the non-null key
            //					// elements.
            //					this.dataView.Table = columns[0].Table;
            //					this.dataView.Sort = sort;
            //					this.dataView.RowStateFilter = System.Data.DataViewRowState.CurrentRows;
            constructorTrueStatements.Add(new CodeCommentStatement("This DataView will be used to find the current rows in the Department table that contain the non-null key "));
            constructorTrueStatements.Add(new CodeCommentStatement("elements."));
            constructorTrueStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "dataView"), "Table"), new CodeFieldReferenceExpression(new CodeIndexerExpression(new CodeArgumentReferenceExpression("columns"), new CodePrimitiveExpression(0)), "Table")));
            constructorTrueStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "dataView"), "Sort"), new CodeVariableReferenceExpression("sort")));
            constructorTrueStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "dataView"), "RowStateFilter"), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(System.Data.DataViewRowState)), "CurrentRows")));

            //				}
            constructor.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(new CodeArgumentReferenceExpression("columns"), "Length"), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(0)), constructorTrueStatements.ToArray()));

            //			}
            this.Members.Add(constructor);

            //			/// <summary>
            //			/// Finds a row in the Department table containing the key elements.
            //			/// </summary>
            //			/// <param name="departmentId">The DepartmentId element of the key.</param>
            //			/// <returns>A DepartmentRow that contains the key elements, or null if there is no match.</returns>
            //			public DepartmentRow Find(int departmentId)
            //			{
            //				// This will find the first row in the DataView that contains the key values.  A 'null' indicates that there was no
            //				// matching column.
            //				int index = this.dataView.Find(new object[] {
            //							departmentId});
            //				if ((index == -1))
            //				{
            //					return null;
            //				}
            //				else
            //				{
            //					return ((DepartmentRow)(this.dataView[index].Row));
            //				}
            //			}
            CodeMemberMethod findMethod = new CodeMemberMethod();

            findMethod.Comments.Add(new CodeCommentStatement("<summary>", true));
            findMethod.Comments.Add(new CodeCommentStatement(string.Format("Finds a row in the {0} table containing the key elements.", this.constraintSchema.Selector.Name), true));
            findMethod.Comments.Add(new CodeCommentStatement("</summary>", true));
            foreach (ColumnSchema columnSchema in constraintSchema.Fields)
            {
                string camelCaseColumnName = string.Format("{0}", columnSchema.Name[0].ToString().ToLower() + columnSchema.Name.Remove(0, 1));
                findMethod.Comments.Add(new CodeCommentStatement(string.Format("<param name=\"{0}\">The {1} element of the key.</param>", camelCaseColumnName, columnSchema.Name), true));
            }
            findMethod.Comments.Add(new CodeCommentStatement(string.Format("<returns>A {0} that contains the key elements, or null if there is no match.</returns>", indexRowName), true));
            findMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            findMethod.ReturnType = new CodeTypeReference(indexRowName);
            findMethod.Name       = "Find";
            List <CodeExpression> findByArguments = new List <CodeExpression>();

            foreach (ColumnSchema columnSchema in constraintSchema.Fields)
            {
                string camelCaseColumnName = string.Format("{0}", columnSchema.Name[0].ToString().ToLower() + columnSchema.Name.Remove(0, 1));
                findMethod.Parameters.Add(new CodeParameterDeclarationExpression(columnSchema.DataType, camelCaseColumnName));
                findByArguments.Add(new CodeArgumentReferenceExpression(camelCaseColumnName));
            }
            findMethod.Statements.Add(new CodeCommentStatement("This will find the first row in the DataView that contains the key values.  A 'null' indicates that there was no"));
            findMethod.Statements.Add(new CodeCommentStatement("matching column."));
            findMethod.Statements.Add(new CodeVariableDeclarationStatement(typeof(System.Int32), "index", new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "dataView"), "Find", new CodeArrayCreateExpression(typeof(System.Object), findByArguments.ToArray()))));
            findMethod.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("index"), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(-1)),
                                                                 new CodeStatement[] { new CodeMethodReturnStatement(new CodePrimitiveExpression(null)) },
                                                                 new CodeStatement[] { new CodeMethodReturnStatement(new CodeCastExpression(indexRowName, new CodeFieldReferenceExpression(new CodeIndexerExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "dataView"), new CodeVariableReferenceExpression("index")), "Row"))) }));
            this.Members.Add(findMethod);

            //		}
        }
Beispiel #14
0
        /// <summary>
        /// Creates a strongly typed DataSet from a schema description.
        /// </summary>
        /// <param name="dataSetNamespace">The CodeDOM namespace that contains this strongly typed DataSet.</param>
        public TypedDataSetClass(MiddleTierNamespace dataSetNamespace)
        {
            // Initialize the object.
            this.dataSetNamespace = dataSetNamespace;

            //	/// <summary>
            //	/// A thread-safe, multi-tiered DataModel.
            //	/// </summary>
            //	[System.ComponentModel.DesignerCategoryAttribute("code")]
            //	[System.Diagnostics.DebuggerStepThrough()]
            //	[System.ComponentModel.ToolboxItem(true)]
            //	public class DataModel : System.ComponentModel.Component
            //	{
            this.Comments.Add(new CodeCommentStatement("<summary>", true));
            this.Comments.Add(new CodeCommentStatement(string.Format("A thread-safe, multi-tiered {0}.", this.Schema.Name), true));
            this.Comments.Add(new CodeCommentStatement("</summary>", true));
            this.IsClass        = true;
            this.Name           = this.Schema.Name;
            this.TypeAttributes = TypeAttributes.Public;
            this.BaseTypes.Add(new CodeTypeReference(typeof(Component)));
            this.CustomAttributes.Add(new CodeAttributeDeclaration("System.ComponentModel.DesignerCategoryAttribute", new CodeAttributeArgument[] { new CodeAttributeArgument(new CodePrimitiveExpression("code")) }));
            this.CustomAttributes.Add(new CodeAttributeDeclaration("System.Diagnostics.DebuggerStepThrough"));
            this.CustomAttributes.Add(new CodeAttributeDeclaration("System.ComponentModel.ToolboxItem", new CodeAttributeArgument[] { new CodeAttributeArgument(new CodePrimitiveExpression(true)) }));

            //		// Counts the number of the DataModel has been referenced.
            //		private static int referenceCount;
            CodeMemberField referenceCountField = new CodeMemberField();

            referenceCountField.Comments.Add(new CodeCommentStatement(string.Format("Counts the number of the {0} has been referenced.", this.Schema.Name)));
            referenceCountField.Attributes = MemberAttributes.Private | MemberAttributes.Static;
            referenceCountField.Type       = new CodeTypeReference(typeof(System.Int32));
            referenceCountField.Name       = "referenceCount";
            this.Members.Add(referenceCountField);

            //		// Represents the in-memory cache of data for the DataModel.
            //		private static DataSet dataSet;
            CodeMemberField dataSetField = new CodeMemberField();

            dataSetField.Comments.Add(new CodeCommentStatement(string.Format("Represents the in-memory cache of data for the {0}.", this.Schema.Name)));
            dataSetField.Attributes = MemberAttributes.Private | MemberAttributes.Static;
            dataSetField.Type       = new CodeTypeReference("DataSet");
            dataSetField.Name       = "dataSet";
            this.Members.Add(dataSetField);

            //		// The Department table
            //		private static DepartmentDataTable tableDepartment;
            foreach (TableSchema tableSchema in this.Schema.Tables)
            {
                CodeMemberField codeMemberField = new CodeMemberField();
                codeMemberField.Comments.Add(new CodeCommentStatement(string.Format("The {0} table", tableSchema.Name)));
                codeMemberField.Attributes = MemberAttributes.Private | MemberAttributes.Static;
                codeMemberField.Type       = new CodeTypeReference(String.Format("{0}DataTable", tableSchema.Name));
                codeMemberField.Name       = string.Format("table{0}", tableSchema.Name);
                this.Members.Add(codeMemberField);
            }

            //		// Relates the Department table to the Employee table.
            //		private static Relation relationFK_Department_Employee;
            foreach (TableSchema tableSchema in this.Schema.Tables)
            {
                foreach (ConstraintSchema constraintSchema in tableSchema.Constraints)
                {
                    if (constraintSchema is KeyrefSchema)
                    {
                        KeyrefSchema    keyrefSchema    = constraintSchema as KeyrefSchema;
                        CodeMemberField codeMemberField = new CodeMemberField();
                        codeMemberField.Comments.Add(new CodeCommentStatement(string.Format("Relates the {0} table to the {1} table.", keyrefSchema.Refer.Selector.Name, keyrefSchema.Selector.Name)));
                        codeMemberField.Attributes = MemberAttributes.Private | MemberAttributes.Static;
                        codeMemberField.Type       = new CodeTypeReference("Relation");
                        codeMemberField.Name       = string.Format("relation{0}", keyrefSchema.Name);
                        this.Members.Add(codeMemberField);
                    }
                }
            }

            //		/// <summary>
            //		/// Static Constructor for the DataModel.
            //		/// </summary>
            //		static DataModel()
            //		{
            CodeTypeConstructor voidTypeConstructor = new CodeTypeConstructor();

            voidTypeConstructor.Comments.Add(new CodeCommentStatement("<summary>", true));
            voidTypeConstructor.Comments.Add(new CodeCommentStatement(string.Format("Static Constructor for the {0}.", this.Schema.Name), true));
            voidTypeConstructor.Comments.Add(new CodeCommentStatement("</summary>", true));

            //			// Create the DataModel DataSet
            //			DataModel.dataSet = new DataSet();
            //			DataModel.dataSet.Name = "DataModel";
            //			DataModel.dataSet.CaseSensitive = true;
            //			DataModel.dataSet.EnforceConstraints = true;
            voidTypeConstructor.Statements.Add(new CodeCommentStatement(string.Format("Create the {0} DataSet", this.Schema.Name)));
            voidTypeConstructor.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(this.Schema.Name), "dataSet"), new CodeObjectCreateExpression("DataSet", new CodeExpression[] { })));
            voidTypeConstructor.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(this.Schema.Name), "dataSet"), "DataSetName"), new CodePrimitiveExpression(this.Schema.Name)));
            voidTypeConstructor.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(this.Schema.Name), "dataSet"), "CaseSensitive"), new CodePrimitiveExpression(true)));
            voidTypeConstructor.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(this.Schema.Name), "dataSet"), "EnforceConstraints"), new CodePrimitiveExpression(true)));

            //			// Create the Department Table.
            //			DataModel.tableDepartment = new DepartmentDataTable();
            //			DataModel.Tables.Add(DataModel.tableDepartment);
            foreach (TableSchema tableSchema in this.Schema.Tables)
            {
                voidTypeConstructor.Statements.Add(new CodeCommentStatement(string.Format("Create the {0} Table.", tableSchema.Name)));
                voidTypeConstructor.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(this.Schema.Name), String.Format("table{0}", tableSchema.Name)), new CodeObjectCreateExpression(string.Format("{0}DataTable", tableSchema.Name), new CodeExpression[] { })));
                voidTypeConstructor.Statements.Add(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(this.Schema.Name), "Tables"), "Add", new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(this.Schema.Name), String.Format("table{0}", tableSchema.Name))));
            }

            //			// Create and enforce the relation between Department and Employee tables.
            //			DataModel.relationFK_Department_Employee = new Relation("FK_Department_Employee", new Column[] {
            //						DataModel.tableDepartment.DepartmentIdColumn}, new Column[] {
            //						DataModel.tableEmployee.DepartmentIdColumn}, true);
            //			DataModel.Relations.Add(DataModel.relationFK_Department_Employee);
            foreach (TableSchema tableSchema in this.Schema.Tables)
            {
                foreach (ConstraintSchema constraintSchema in tableSchema.Constraints)
                {
                    if (constraintSchema is KeyrefSchema)
                    {
                        // Extract the parent and child tables from the keys.
                        KeyrefSchema     keyrefSchema = constraintSchema as KeyrefSchema;
                        ConstraintSchema referSchema  = keyrefSchema.Refer;
                        TableSchema      parentTable  = referSchema.Selector;
                        TableSchema      childTable   = keyrefSchema.Selector;

                        // Collect the key fields in the parent table.
                        List <CodeExpression> parentFieldList = new List <CodeExpression>();
                        foreach (ColumnSchema columnSchema in referSchema.Fields)
                        {
                            string parentColumnName = String.Format("{0}Column", columnSchema.Name);
                            string parentTableName  = String.Format("table{0}", parentTable.Name);
                            parentFieldList.Add(new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(this.Schema.Name), parentTableName), parentColumnName));
                        }

                        // Collect the referenced fields in the child table.
                        List <CodeExpression> childFieldList = new List <CodeExpression>();
                        foreach (ColumnSchema columnSchema in keyrefSchema.Fields)
                        {
                            string childColumnName = String.Format("{0}Column", columnSchema.Name);
                            string childTableName  = String.Format("table{0}", childTable.Name);
                            childFieldList.Add(new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(this.Schema.Name), childTableName), childColumnName));
                        }

                        // Create the CodeDOM statements to create the relationship between the two tables and the foreign key
                        // constraint that insures the integrity of the relation.
                        voidTypeConstructor.Statements.Add(new CodeCommentStatement(string.Format("Create and enforce the relation between {0} and {1} tables.", parentTable.Name, childTable.Name)));
                        CodeObjectCreateExpression newForeignKey = new CodeObjectCreateExpression("Relation", new CodeExpression[] { new CodePrimitiveExpression(keyrefSchema.Name), new CodeArrayCreateExpression("Column", parentFieldList.ToArray()), new CodeArrayCreateExpression("Column", childFieldList.ToArray()), new CodePrimitiveExpression(true) });
                        voidTypeConstructor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(this.Schema.Name), string.Format("relation{0}", keyrefSchema.Name)), newForeignKey));
                        CodeExpression parameterExpression = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(this.Schema.Name), String.Format("relation{0}", keyrefSchema.Name));
                        voidTypeConstructor.Statements.Add(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(this.Schema.Name), "Relations"), "Add", new CodeExpression[] { parameterExpression }));
                    }
                }
            }

            foreach (TableSchema tableSchema in this.Schema.Tables)
            {
                //			// Initialze the relation fields for the Department table.
                //			DataModel.Department.InitializeRelations();
                voidTypeConstructor.Statements.Add(new CodeCommentStatement(string.Format("Initialze the relation fields for the {0} table.", tableSchema.Name), true));
                voidTypeConstructor.Statements.Add(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(this.Schema.Name), tableSchema.Name), "InitializeRelations"));
            }


            //		}
            this.Members.Add(voidTypeConstructor);

            //		/// <summary>
            //		/// Initializer for instances of DataModel not managed as a component.
            //		/// </summary>
            //		public DataModel()
            //		{
            //			// This is used to keep track of the number of references to this shared component.  When the count drops to zero, the
            //			// external resources (namely the thread) are destroyed.
            //			DataModel.referenceCount = (DataModel.referenceCount + 1);
            //		}
            CodeConstructor voidConstructor = new CodeConstructor();

            voidConstructor.Attributes = MemberAttributes.Public;
            voidConstructor.Comments.Add(new CodeCommentStatement("<summary>", true));
            voidConstructor.Comments.Add(new CodeCommentStatement(string.Format("Initializer for instances of {0} not managed as a component.", this.Schema.Name), true));
            voidConstructor.Comments.Add(new CodeCommentStatement("</summary>", true));
            voidConstructor.Statements.Add(new CodeCommentStatement("This is used to keep track of the number of references to this shared component.  When the count drops to zero, the"));
            voidConstructor.Statements.Add(new CodeCommentStatement("external resources (namely the thread) are destroyed."));
            voidConstructor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(this.Schema.Name), "referenceCount"), new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(this.Schema.Name), "referenceCount"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1))));
            this.Members.Add(voidConstructor);

            //		/// <summary>
            //		/// Initializer for instances of DataModel not managed as a component.
            //		/// </summary>
            //		public DataModel(System.ComponentModel.IContainer iContainer)
            //		{
            //			// Add this component to the list of components managed by its client.
            //			iContainer.Add(this);
            //			// This is used to keep track of the number of references to this shared component.  When the count drops to zero, the
            //			// external resources (namely the thread) are destroyed.
            //			DataModel.referenceCount = (DataModel.referenceCount + 1);
            //		}
            CodeConstructor iComponentConstructor = new CodeConstructor();

            iComponentConstructor.Attributes = MemberAttributes.Public;
            iComponentConstructor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(System.ComponentModel.IContainer), "iContainer"));
            iComponentConstructor.Comments.Add(new CodeCommentStatement("<summary>", true));
            iComponentConstructor.Comments.Add(new CodeCommentStatement(string.Format("Initializer for instances of {0} not managed as a component.", this.Schema.Name), true));
            iComponentConstructor.Comments.Add(new CodeCommentStatement("</summary>", true));
            iComponentConstructor.Statements.Add(new CodeCommentStatement("Add this component to the list of components managed by its client."));
            iComponentConstructor.Statements.Add(new CodeMethodInvokeExpression(new CodeArgumentReferenceExpression("iContainer"), "Add", new CodeThisReferenceExpression()));
            iComponentConstructor.Statements.Add(new CodeCommentStatement("This is used to keep track of the number of references to this shared component.  When the count drops to zero, the"));
            iComponentConstructor.Statements.Add(new CodeCommentStatement("external resources (namely the thread) are destroyed."));
            iComponentConstructor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(this.Schema.Name), "referenceCount"), new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(this.Schema.Name), "referenceCount"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1))));
            this.Members.Add(iComponentConstructor);

            //		/// <summary>
            //		/// The number of times the DataModel has been referenced.
            //		/// </summary>
            //		[System.ComponentModel.Browsable(false)]
            //		[System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Content)]
            //		public static int ReferenceCount
            //		{
            //			get
            //			{
            //				return DataModel.referenceCount;
            //			}
            //		}
            CodeMemberProperty referenceCountProperty = new CodeMemberProperty();

            this.Members.Add(referenceCountProperty);
            referenceCountProperty.Comments.Add(new CodeCommentStatement("<summary>", true));
            referenceCountProperty.Comments.Add(new CodeCommentStatement(string.Format("The number of times the {0} has been referenced.", this.Schema.Name), true));
            referenceCountProperty.Comments.Add(new CodeCommentStatement("</summary>", true));
            referenceCountProperty.CustomAttributes.Add(new CodeAttributeDeclaration("System.ComponentModel.Browsable", new CodeAttributeArgument[] { new CodeAttributeArgument(new CodePrimitiveExpression(false)) }));
            referenceCountProperty.CustomAttributes.Add(new CodeAttributeDeclaration("System.ComponentModel.DesignerSerializationVisibilityAttribute", new CodeAttributeArgument[] { new CodeAttributeArgument(new CodeTypeReferenceExpression("System.ComponentModel.DesignerSerializationVisibility.Content")) }));
            referenceCountProperty.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            referenceCountProperty.Type       = new CodeTypeReference(typeof(int));
            referenceCountProperty.Name       = "ReferenceCount";
            referenceCountProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(this.Schema.Name), "referenceCount")));

            //		/// <summary>
            //		/// Gets or sets a value indicating whether constraint rules are followed when attempting any update operation.
            //		/// </summary>
            //		[System.ComponentModel.Browsable(false)]
            //		[System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Content)]
            //		public static bool EnforceConstraints
            //		{
            //			get
            //			{
            //				return DataModel.dataSet.EnforceConstraints;
            //			}
            //			set
            //			{
            //				DataModel.dataSet.EnforceConstraints = value;
            //			}
            //		}
            CodeMemberProperty enforceConstraintsProperty = new CodeMemberProperty();

            enforceConstraintsProperty.Comments.Add(new CodeCommentStatement("<summary>", true));
            enforceConstraintsProperty.Comments.Add(new CodeCommentStatement("Gets or sets a value indicating whether constraint rules are followed when attempting any update operation.", true));
            enforceConstraintsProperty.Comments.Add(new CodeCommentStatement("</summary>", true));
            enforceConstraintsProperty.CustomAttributes.Add(new CodeAttributeDeclaration("System.ComponentModel.Browsable", new CodeAttributeArgument[] { new CodeAttributeArgument(new CodePrimitiveExpression(false)) }));
            enforceConstraintsProperty.CustomAttributes.Add(new CodeAttributeDeclaration("System.ComponentModel.DesignerSerializationVisibilityAttribute", new CodeAttributeArgument[] { new CodeAttributeArgument(new CodeTypeReferenceExpression("System.ComponentModel.DesignerSerializationVisibility.Content")) }));
            enforceConstraintsProperty.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            enforceConstraintsProperty.Type       = new CodeTypeReference(typeof(bool));
            enforceConstraintsProperty.Name       = "EnforceConstraints";
            enforceConstraintsProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(this.Schema.Name), "dataSet"), "EnforceConstraints")));
            enforceConstraintsProperty.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(this.Schema.Name), "dataSet"), "EnforceConstraints"), new CodePropertySetValueReferenceExpression()));
            this.Members.Add(enforceConstraintsProperty);

            //		/// <summary>
            //		/// Gets the collection of tables contained in the DataModel.
            //		/// </summary>
            //		[System.ComponentModel.Browsable(false)]
            //		[System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Content)]
            //		public static TableCollection Tables
            //		{
            //			get
            //			{
            //				return new TableCollection(DataModel.dataSet.Tables);
            //			}
            //		}
            CodeMemberProperty tablesProperty = new CodeMemberProperty();

            tablesProperty.Comments.Add(new CodeCommentStatement("<summary>", true));
            tablesProperty.Comments.Add(new CodeCommentStatement(string.Format("Gets the collection of tables contained in the {0}.", this.Schema.Name), true));
            tablesProperty.Comments.Add(new CodeCommentStatement("</summary>", true));
            tablesProperty.CustomAttributes.Add(new CodeAttributeDeclaration("System.ComponentModel.Browsable", new CodeAttributeArgument[] { new CodeAttributeArgument(new CodePrimitiveExpression(false)) }));
            tablesProperty.CustomAttributes.Add(new CodeAttributeDeclaration("System.ComponentModel.DesignerSerializationVisibilityAttribute", new CodeAttributeArgument[] { new CodeAttributeArgument(new CodeTypeReferenceExpression("System.ComponentModel.DesignerSerializationVisibility.Content")) }));
            tablesProperty.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            tablesProperty.Type       = new CodeTypeReference("TableCollection");
            tablesProperty.Name       = "Tables";
            tablesProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodeObjectCreateExpression("TableCollection", new CodeExpression[] { new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(this.Schema.Name), "dataSet"), "Tables") })));
            this.Members.Add(tablesProperty);

            //		/// <summary>
            //		/// Gets the collection of relations that link tables and allow navigation between parent tables and child tables.
            //		/// </summary>
            //		[System.ComponentModel.Browsable(false)]
            //		[System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Content)]
            //		public static RelationCollection Relations
            //		{
            //			get
            //			{
            //				return new RelationCollection(DataModel.dataSet.Relations);
            //			}
            //		}
            CodeMemberProperty relationsProperty = new CodeMemberProperty();

            relationsProperty.Comments.Add(new CodeCommentStatement("<summary>", true));
            relationsProperty.Comments.Add(new CodeCommentStatement("Gets the collection of relations that link tables and allow navigation between parent tables and child tables.", true));
            relationsProperty.Comments.Add(new CodeCommentStatement("</summary>", true));
            relationsProperty.CustomAttributes.Add(new CodeAttributeDeclaration("System.ComponentModel.Browsable", new CodeAttributeArgument[] { new CodeAttributeArgument(new CodePrimitiveExpression(false)) }));
            relationsProperty.CustomAttributes.Add(new CodeAttributeDeclaration("System.ComponentModel.DesignerSerializationVisibilityAttribute", new CodeAttributeArgument[] { new CodeAttributeArgument(new CodeTypeReferenceExpression("System.ComponentModel.DesignerSerializationVisibility.Content")) }));
            relationsProperty.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            relationsProperty.Type       = new CodeTypeReference("RelationCollection");
            relationsProperty.Name       = "Relations";
            relationsProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodeObjectCreateExpression("RelationCollection", new CodeExpression[] { new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(this.Schema.Name), "dataSet"), "Relations") })));
            this.Members.Add(relationsProperty);

            //		/// <summary>
            //		/// Gets an accessor for the Department table.
            //		/// </summary>
            //		[System.ComponentModel.Browsable(false)]
            //		[System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Content)]
            //		public static DepartmentDataTable Department
            //		{
            //			get
            //			{
            //				return DataModel.tableDepartment;
            //			}
            //		}
            foreach (TableSchema tableSchema in this.Schema.Tables)
            {
                CodeMemberProperty codeMemberProperty = new CodeMemberProperty();
                codeMemberProperty.Comments.Add(new CodeCommentStatement("<summary>", true));
                codeMemberProperty.Comments.Add(new CodeCommentStatement(string.Format("Gets an accessor for the {0} table.", tableSchema.Name), true));
                codeMemberProperty.Comments.Add(new CodeCommentStatement("</summary>", true));
                codeMemberProperty.CustomAttributes.Add(new CodeAttributeDeclaration("System.ComponentModel.Browsable", new CodeAttributeArgument[] { new CodeAttributeArgument(new CodePrimitiveExpression(false)) }));
                codeMemberProperty.CustomAttributes.Add(new CodeAttributeDeclaration("System.ComponentModel.DesignerSerializationVisibilityAttribute", new CodeAttributeArgument[] { new CodeAttributeArgument(new CodeTypeReferenceExpression("System.ComponentModel.DesignerSerializationVisibility.Content")) }));
                codeMemberProperty.Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static;
                codeMemberProperty.Type       = new CodeTypeReference(string.Format("{0}DataTable", tableSchema.Name));
                codeMemberProperty.Name       = tableSchema.Name;
                codeMemberProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(this.Schema.Name), string.Format("table{0}", tableSchema.Name))));
                this.Members.Add(codeMemberProperty);
            }

            //		/// <summary>
            //		/// Dispose of an instance of the DataModel.
            //		/// </summary>
            //		protected override void Dispose(bool disposing)
            //		{
            //			// This section disposes of the managed resources.
            //			if ((disposing == true))
            //			{
            //				// This controls the disposal of the static resources.  When the instance count reaches zero, then all static resources
            //				// should be released back to the operating system.
            //				DataModel.referenceCount = (DataModel.referenceCount - 1);
            //			}
            //			// Allow the base class to complete the disposal.
            //			base.Dispose(disposing);
            //		}
            CodeMemberMethod disposeMethod = new CodeMemberMethod();

            disposeMethod.Comments.Add(new CodeCommentStatement("<summary>", true));
            disposeMethod.Comments.Add(new CodeCommentStatement(string.Format("Dispose of an instance of the {0}.", this.Schema.Name), true));
            disposeMethod.Comments.Add(new CodeCommentStatement("</summary>", true));
            disposeMethod.Name       = "Dispose";
            disposeMethod.Attributes = MemberAttributes.Override | MemberAttributes.Family;
            disposeMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(System.Boolean), "disposing"));
            disposeMethod.Statements.Add(new CodeCommentStatement("This section disposes of the managed resources."));
            CodeStatement[] disposeMethodTrue = new CodeStatement[]
            {
                new CodeCommentStatement("This controls the disposal of the static resources.  When the instance count reaches zero, then all static resources"),
                new CodeCommentStatement("should be released back to the operating system."),
                new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(this.Schema.Name), "referenceCount"), new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(this.Schema.Name), "referenceCount"), CodeBinaryOperatorType.Subtract, new CodePrimitiveExpression(1)))
            };
            disposeMethod.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression("disposing"), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(true)), disposeMethodTrue));
            disposeMethod.Statements.Add(new CodeCommentStatement("Allow the base class to complete the disposal."));
            disposeMethod.Statements.Add(new CodeMethodInvokeExpression(new CodeBaseReferenceExpression(), "Dispose", new CodeArgumentReferenceExpression("disposing")));
            this.Members.Add(disposeMethod);

            //		/// <summary>
            //		/// Commits all the changes that were made to this DataModel since the last time DataModel.AcceptChanges was called.
            //		/// </summary>
            //		public static void AcceptChanges()
            //		{
            //			// Commit the changes.
            //			DataModel.dataSet.AcceptChanges();
            //		}
            CodeMemberMethod acceptChangesMethod = new CodeMemberMethod();

            acceptChangesMethod.Comments.Add(new CodeCommentStatement("<summary>", true));
            acceptChangesMethod.Comments.Add(new CodeCommentStatement(string.Format("Commits all the changes that were made to this {0} since the last time {0}.AcceptChanges was called.", this.Schema.Name), true));
            acceptChangesMethod.Comments.Add(new CodeCommentStatement("</summary>", true));
            acceptChangesMethod.Name       = "AcceptChanges";
            acceptChangesMethod.Attributes = MemberAttributes.Final | MemberAttributes.Static | MemberAttributes.Public;
            acceptChangesMethod.Statements.Add(new CodeCommentStatement("Commit the changes."));
            acceptChangesMethod.Statements.Add(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(this.Schema.Name), "dataSet"), "AcceptChanges", new CodeExpression[] {}));
            this.Members.Add(acceptChangesMethod);

            //		/// <summary>
            //		/// Clears the DataModel of any data by removing all rows in a table.
            //		/// </summary>
            //		public static void Clear()
            //		{
            //			// Clear the DataModel.
            //			DataModel.dataSet.Clear();
            //		}
            CodeMemberMethod clearMethod = new CodeMemberMethod();

            clearMethod.Comments.Add(new CodeCommentStatement("<summary>", true));
            clearMethod.Comments.Add(new CodeCommentStatement(string.Format("Clears the {0} of any data by removing all rows in a table.", this.Schema.Name), true));
            clearMethod.Comments.Add(new CodeCommentStatement("</summary>", true));
            clearMethod.Name       = "Clear";
            clearMethod.Attributes = MemberAttributes.Final | MemberAttributes.Static | MemberAttributes.Public;
            clearMethod.Statements.Add(new CodeCommentStatement(string.Format("Clear the {0}.", this.Schema.Name)));
            clearMethod.Statements.Add(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(this.Schema.Name), "dataSet"), "Clear", new CodeExpression[] { }));
            this.Members.Add(clearMethod);

            //		/// <summary>
            //		/// Gets the instance of the data model.
            //		/// </summary>
            //		public static System.Data.DataSet GetDataSet()
            //		{
            //			// This is used by the ADO Resource Manager to identify the instance of the data model.
            //			return DataModel.dataSet;
            //		}
            CodeMemberMethod getDataModelMethod = new CodeMemberMethod();

            this.Members.Add(getDataModelMethod);
            getDataModelMethod.Comments.Add(new CodeCommentStatement("<summary>", true));
            getDataModelMethod.Comments.Add(new CodeCommentStatement("Gets the instance of the data model.", true));
            getDataModelMethod.Comments.Add(new CodeCommentStatement("</summary>", true));
            getDataModelMethod.Name       = "GetDataSet";
            getDataModelMethod.ReturnType = new CodeTypeReference(typeof(System.Data.DataSet));
            getDataModelMethod.Attributes = MemberAttributes.Final | MemberAttributes.Static | MemberAttributes.Public;
            getDataModelMethod.Statements.Add(new CodeCommentStatement("This is used by the ADO Resource Manager to identify the instance of the data model."));
            getDataModelMethod.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(this.Schema.Name), "dataSet")));

            //		/// <summary>
            //		/// Delegate for handling changes to the Department table.
            //		/// </summary>
            //		/// <param name="sender">The object that originated the event.</param>
            //		/// <param name="e">The event arguments.</param>
            //		public delegate void DepartmentRowChangeEventHandler(object sender, DepartmentRowChangeEvent e);
            foreach (TableSchema tableSchema in this.Schema.Tables)
            {
                CodeTypeDelegate codeTypeDelegate = new CodeTypeDelegate();
                codeTypeDelegate.Comments.Add(new CodeCommentStatement("<summary>", true));
                codeTypeDelegate.Comments.Add(new CodeCommentStatement(string.Format("Delegate for handling changes to the {0} table.", tableSchema.Name), true));
                codeTypeDelegate.Comments.Add(new CodeCommentStatement("</summary>", true));
                codeTypeDelegate.Comments.Add(new CodeCommentStatement("<param name=\"sender\">The object that originated the event.</param>", true));
                codeTypeDelegate.Comments.Add(new CodeCommentStatement("<param name=\"e\">The event arguments.</param>", true));
                codeTypeDelegate.Name           = String.Format("{0}RowChangeEventHandler", tableSchema.Name);
                codeTypeDelegate.ReturnType     = new CodeTypeReference(typeof(void));
                codeTypeDelegate.TypeAttributes = System.Reflection.TypeAttributes.Public;
                codeTypeDelegate.Parameters.AddRange(new CodeParameterDeclarationExpression[] { new CodeParameterDeclarationExpression(typeof(System.Object), "sender"), new CodeParameterDeclarationExpression(String.Format("{0}RowChangeEvent", tableSchema.Name), "e") });
                this.Members.Add(codeTypeDelegate);
            }

            // This will create the strongly typed table, indices, rows and event handlers for each of the tables in the schema.
            foreach (TableSchema tableSchema in this.Schema.Tables)
            {
                // Add a strongly typed definition for each of the tables to the data model class.
                this.Members.Add(new TypedTableClass(tableSchema));

                // Add a strongly typed index for each of the keys on the table.
                foreach (ConstraintSchema constraintSchema in tableSchema.Keys)
                {
                    if (constraintSchema.IsPrimaryKey)
                    {
                        this.Members.Add(new TypedPrimaryIndexClass(constraintSchema));
                    }
                    else
                    {
                        this.Members.Add(new TypedIndexClass(constraintSchema));
                    }
                }

                // Create the strongly typed rows of the table.
                this.Members.Add(new TypedRowClass(tableSchema));

                // Create the strongly typed event handlers for the table.
                this.Members.Add(new TypedChangeEventArgsClass(tableSchema));
            }
        }
Beispiel #15
0
 /// <summary>
 /// Create event arguments using a constraint.
 /// </summary>
 /// <param name="constraintSchema">The constraint involved in the event.</param>
 public ConstraintEventArgs(ConstraintSchema constraintSchema)
 {
     // Initialize the object
     this.ConstraintSchema = constraintSchema;
 }