Using SchemaExplorer
SchemaExplorer is CodeSmith's built-in interface for working with metadata from databases. You can use the classes in SchemaExplorer either programmatically or interactively; often, you'll combine the two approaches. For example, you may want to allow the user to interactively select a database, and then programmatically build a list of all of the tables in the selected database. Here's a template that demonstrates using SchemaExplorer for this purpose:
<%@ CodeTemplate Language="C#" TargetLanguage="Text" Description="List all database tables" %> <%@ Property Name="SourceDatabase" Type="SchemaExplorer.DatabaseSchema" Category="Context" Description="Database containing the tables." %> <%@ Assembly Name="SchemaExplorer" %> <%@ Import Namespace="SchemaExplorer" %> Tables in database "<%= SourceDatabase %>": <% for (int i = 0; i < SourceDatabase.Tables.Count; i++) { %> <%= SourceDatabase.Tables[i].Name %> <% } %>
Before you can execute this template, you must supply a value for the SourceDatabase property. When you place your cursor in the property sheet row for this property, CodeSmith will display a builder button, indicating that there is an external editor hooked up for this property. CodeSmith automatically uses editors built into SchemaExplorer:
Clicking the builder button opens the Database Picker dialog box. A dropdown list lets you choose from all of the data sources that you have previously defined on your computer. There's also a builder button to define a new data source:
If you click the builder button, SchemaExplorer opens the Data Source Manager dialog box. Here you can see the type of each existing data source, and manage your data sources. You can copy, add, edit, or remove data sources from this dialog box.
If you choose to add a new data source, SchemaExplorer opens the Data Source dialog box. To add a new data source, you must provide a name for the new data source, then select a provider type and type in a connection string. CodeSmith ships with providers for SQL Server and ADOX data sources.
Here's a sample of the output for this template when it's used with the SQL Server Northwind sample database:
Tables in database "Northwind": Orders ComponentTypes Products Order Details CustomerCustomerDemo CustomerDemographics Region Territories EmployeeTerritories Employees Categories Customers Shippers Suppliers
After the user specifies the SourceDatabase, CodeSmith is able to use it as the root of an object model of the entire database.
Refer to the CodeSmith API Reference for a complete listing of the classes and members within the SchemaExplorer library.
Advanced: Using Extended Properties to Define Custom Metadata