using visual studio .net wizards to create an n-tiered applicat

Upload: ruben-canovaca-nieto

Post on 14-Apr-2018

232 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    1/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 2

    5 Seconds : Using Visual Studio .NET Wizards to Create an N-TieredApplication - Part 2

    avid Catherman1/17 / 2005

    ntroduction

    Microsoft is known for providing good tools for Rapid Application Development (RAD) tools forevelopers. MS Access, Visual Studio 6, Visual Interdev and others have provided an environment tosually combine controls, properties, and generated code for quick applications. Visual Studio .NET hasombined the best of the previous tools into a great development environment with several differentoding languages.

    here are many wizards in Visual Studio .NET (VS) that assist new users in creating applications.nfortunately, they tend not to promote good programming habits--specifically there is not aeparation of code into layers and they do not adhere to OOP standards isolating business logic. Theefault model of VS is to drag and drop data objects onto the form we are building. VS generates theode necessary, but mixes the data access code and the business logic code directly in the usernterface form object. This limits the reusability of the code and tends to duplicate code where theame table data is used on more than one form.

    Most architects recommend more of an n-tiered approach where the code is separated into differentayers. There should at least be a data access layer, business logic layer, and a presentation layer.When working with distributed applications (different parts of the application running on differentervers) more layers may need to be added.

    here are two primary advantages for separating the layers: code reusability and de-coupling codeom the database. By separating out the data access and business logic layers, many different formsan be used to collect and display the information without rewriting or duplicating the code to accessnd use the information. The de-coupling helps keep your code from breaking when the databasechema changes and makes it easier to even change data storage providers without much codehange.

    Microsoft .NET has made great strides in supporting and encouraging developers to move towardObject Oriented Programming (OOP) standards. While OOP is a large (and deep) subject, one facet

    hat should interest developers of database applications is the concept of a business object. Whileatabase tables and fields do a good job of implementing entities and attributes, business objects bringogether both the properties and behavior of a particular entity. When the application instantiates ausiness object class to represent each entity (table), the attributes can be accessed through propertiesnd the behavior of the entity can be called through methods. This concept also brings all the code forn entity together into one place that can be referenced easily from other parts of the application.hrough inheritance and polymorphism, the business objects can be quite flexible and have substantialower to accomplish much with little code.

    art 2 - Using Visual Studio 2005

    he new version of .NET and Visual Studio offers several enhancements that change the way weevelop database centric applications. In the context of this article, we will be looking specifically atata Sources and Partial Classes.

    http://mediakit.internet.com/icom_cgi/print/pri...i?url=http://www.15seconds.com/issue/051117.htm (1 de 15) [06/11/2009 19:28:31]

  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    2/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 2

    he Binding Context Manager has been expanded and greatly simplified into Binding Sourcesomponent that allows forms to provide better data binding to datasets, Web services, and businessbjects.

    artial Classes provides a way to extend classes across multiple files which will be combined together atompile time. The Typed Dataset class has been extended to include partial classes, separatingenerated code from hand crafted code, allowing us to add business logic to the dataset class without

    he complications of inheritance.

    etting Started

    fter opening VS2005, create a new project (File / New Project) and let's start with a VB Windowsroject. In the dialog at the bottom, name your project NorthwindWin and the Solution Northwind.

    igure 1 - New Project in VS2005

    he Data Object

    he first step in creating a data application is to create a Typed DataSet object to define the databject to be used. You can add a new DataSet object to you project from the Solution Explorer windowy right-clicking on the project and selecting Add / New Item. The design surface of the DataSet haseen enhanced to automatically include relations from the database when more than one table is

    dded to the dataset (by dragging from the Server Explorer or Database Explorer (Express Version)window). The dataset has been expanded to include one or more data adapters to handle the "Fill" andUpdate" methods so we don't need to create an inherited class to implement them. The Configuration

    Wizard has been changed slightly, but accomplished the same effect.

    http://mediakit.internet.com/icom_cgi/print/pri...i?url=http://www.15seconds.com/issue/051117.htm (2 de 15) [06/11/2009 19:28:31]

  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    3/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 2

    better way to create a DataSet is to use the Data Sources wizard. With the proper project selected,ick the top line Data menu and select "Add New Data Source". The Data Source Configuration Wizard

    will take over and step you through creating a DataSet with the proper connection. Just click Next onhe first screen. The next screen allows you to choose the type of Data Source.

    igure 2 - Create DataSource Wizard, Screen 2

    his time we will choose the Database type, but take note of the other options to use a Web Service or

    xisting Business Object, because we will come back to them.

    he second screen allows you to choose an existing connection or create a new one.

    igure 3 - Data Source Wizard, Screen 3

    http://mediakit.internet.com/icom_cgi/print/pri...i?url=http://www.15seconds.com/issue/051117.htm (3 de 15) [06/11/2009 19:28:31]

  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    4/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 2

    f you do not have a connection to the Northwind database, use the New Connection button to createne now. If you have not previously set up a Project Setting for this connection, the Wizard will do itor you now.

    igure 4 - Data Source Wizard, Screen 4

    n the next screen of the Wizard, you will be shown a tree list of all the metadata in the database.xpand the Tables node and select the tables needed in this DataSet (Orders, Order Detail, androducts)

    http://mediakit.internet.com/icom_cgi/print/pri...i?url=http://www.15seconds.com/issue/051117.htm (4 de 15) [06/11/2009 19:28:31]

  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    5/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 2

    igure 5 - Data Source Wizard, Screen 5

    efore leaving this screen, be sure to correctly name your DataSet. (Some of the earlier Betas hadroblems renaming DataSets correctly.) In this case, we need to change the name of the dataset fromorthwindDataSet to OrdersDataSet.

    fter finishing the Wizard, you will have a dataset added to your project with 3 tables in it.

    igure 6 - Resulting DataSet Visual representation

    http://mediakit.internet.com/icom_cgi/print/pri...i?url=http://www.15seconds.com/issue/051117.htm (5 de 15) [06/11/2009 19:28:31]

  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    6/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 2

    With this design surface, you can continue to drag more tables from the Server Explorer (Databasexplorer in Standard version) to add to the dataset. Looking ahead, we know we will need to add theustomers and Employees tables for combo box lookups.

    ou can edit the tables by right-clicking on the header and selecting Configure... from the drop downmenu (or use top line Data menu, Configure).

    igure 7 - Configuration Wizard page 1

    lick the Query Builder button to visually edit the SQL for the Table Adapter. In this case, the comboox will need a Full Name field that combines the last and first names.

    ou can also click the Advanced Options button to deselect the option to generate Update and Deletemethods since this table is for lookup only and will not be edited. Click the Next button for moreptions on the Fill, GetData and Update methods and finish the Wizard. Repeat this configuration forhe Customers table.

    resentation Layer

    Data Sources RAD Tool

    Once the dataset is created, you can open the Data Sourcesane from the top line Data menu. This pane will already showhe dataset created, but you may also add other sources fromdatabase server, local database file (such as Access or

    oxPro), a Web Service, or a predefined Business Object class.he wizard will proceed through each step required for addingata sources. You may also expand the table node to see allhe fields available in the data table.

    When you have a form open in the IDE, the Data Sources pane

    http://mediakit.internet.com/icom_cgi/print/pri...i?url=http://www.15seconds.com/issue/051117.htm (6 de 15) [06/11/2009 19:28:31]

  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    7/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 2

    xposes some additional functionality. As each node iselected, a dropdown (combo) box allows the user to chooseow the object should be rendered when dragged to the form.or tables, the choices are GridView or Details view. TheridView will create a DataGridView control that implementsach field in a default form, but can be edited to renderifferent embedded controls. The Detail view creates a labelnd textbox (or other component) for each field showing a

    ngle record at a time.

    Other choices for field controls are: Textbox, NumericUpDown,ombobox, Label, Linked Label, and Listbox. You can alsoreate custom user controls and add them to the list.

    he Data Sources tool fosters a Rapid Application Development (RAD) environment where developersan quickly create a User Interface (UI) based on database schema. Rather than binding controlsirectly to dataset fields, VS2005 adds another layer call the Binding Source which correlates to the

    ata object stored in the dataset. The controls on the UI are bound to the Binding Source fields. This isnew component that is a combination of the Binding Context and DataView objects.

    he Controls have simplified binding by reducing the number of properties available for binding to aouple of the more popular (tag, text, selected value, etc.). You can still bind to the other myriad ofroperties through the Advanced settings if needed, but the common bindings are prominent andefaulted in most cases by the Data Sources wizard.

    uilding the Orders View/Edit screen

    ow it is time to build a form to edit the Orders data. Right-click on the project in Solution Explorer /dd / New Item and select the Windows Form icon, giving it a name of OrdersForm.vb. VS will presentblank form to work with.

    f your Data Sources window is not open, click the top line Datamenu and select Show Data Sources. In your tree, you should seehe dataset and data tables. To the right of each table is a dropdownhat allows you to choose between implementing it as aataGridView or free form Details controls. You can further expand

    he table to see the data fields and similarly select which control to

    se to implement the field in free form controls. (Note: In the Beta,ou could configure how the field would be rendered in theataGridView as well, but this was removed in the final version so

    hat only Textboxes are rendered, but they can be changed byditing the columns later.) This Wizard can be modified through theools / Options / Windows Forms Designer / Data UI Customizationo allow custom controls to be listed as well.

    Most presentations usually prefer to have parent screens shown in Details format so in Data Sources,hange the format for the Orders table to Details. Now comes the exciting part--drag the Orders tableom the Data Sources window and drop it in the upper left corner of the blank form in the designurface of Visual Studio. The Data Sources Wizard will create each of the controls in the table,ccording to the default selected. You may also drag the fields one at a time from Data Sources pane,ut it is much faster to just have them all created at once. You will notice that each control is properly

    http://mediakit.internet.com/icom_cgi/print/pri...i?url=http://www.15seconds.com/issue/051117.htm (7 de 15) [06/11/2009 19:28:31]

  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    8/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 2

    amed and bound to the correct field in the table. The wizard also creates a label for each control,sing the description property if available and otherwise, the name of the field, inserting spaces whereeeded.

    More than just the controls, the Wizard has added functionality to our form by adding a Dataavigation strip that allows the user to switch between records using VCR style buttons. The Wizardlso added the components necessary to provide connectivity and binding with the dataset andatabase. If you open the code window, you will see that the Wizard has even added a line of code toall the Table Adapter component to fill the DataSet component. If you set the project to be thetartup project and the properties of the project to show this form at startup, you can build and runhe solution now and see the form fully functional, showing all the records in the Orders table. There islittle work to do to get the Combo Box controls working correctly, but the form is basically functional.

    igure 8 - Orders Form Master

    o get the Combo Boxes functional, we can open the DataSet and add the Customer and Employeeables (or create separate datasets for them). After building the project, you can refresh the Dataources window to see the new tables or add new data sources if you put them in a different DataSet.

    ack on the form, drag the Employee table from the Data Source and drop it on the combo box. Therst thing you notice is another Binding Source component is added to for the Employee table. If youelect the employee combo box control, you will notice that the proper settings for the Data Source,

    http://mediakit.internet.com/icom_cgi/print/pri...i?url=http://www.15seconds.com/issue/051117.htm (8 de 15) [06/11/2009 19:28:31]

  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    9/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 2

    isplay Member and Value Member have been set and the binding has been changed from Text toelected Value. This is what Microsoft calls "Connect the dots"--you can drag and drop a table to anyst driven control. The wizard takes the primary key for the Value Member and the first character fieldor the Display Member property.

    ou can drag the Customer table to the Customer combo box in the same way and a Binding Sourceomponent will be added for it also. If you open the code behind the form, you will also notice that VSas added code to the OrdersForm_Load class to fill the tables with data from the dataset for eachinding source added to the form.

    fter a little rearrangement of controls, here is what the form should look like:

    igure 9 - Order Form Master final

    Master Detail Presentation

    he heart of a good relational application is the ability to display parent-child relationships. Visualtudio 2005 offers a fairly flexible tool to help rapid development of this functionality. In the Dataources pane if you expand the tables, you will see below the fields, an entry for each child relationshipf the table. In our example, expanding the Orders table node, you will see an entry for theelationship to the Order Details table. If you select the DataGridView representation and drag theelation node to the form, VS assumes you want a master-detail arrangement and will created theeeded links for you.

    S will add a new BindingSource component to the form for the table and a table adapter to fill theable on form load. The Smart Data tag will expand (or you can click on the arrow in the upper right ofhe grid control) to show several properties and actions for the control. The "Choose Data Source"hould be set to the new binding source based on the relation between the tables. This is all that isecessary to set the detail grid to link with the master record. If you look at the properties, you will seehat the Data Source for the newly added Binding Source is the OrdersBindingSource and the Data

    Member is the relationship.

    http://mediakit.internet.com/icom_cgi/print/pri...i?url=http://www.15seconds.com/issue/051117.htm (9 de 15) [06/11/2009 19:28:31]

  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    10/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 2

    igure 10 - Adding Details to the Order Form

    f you compile and run the project now, you will see the linking between the master and detail parts.ut the grid needs some editing to make it show productive data.

    ou will need to replace the ProductID with a combo box to display the name of the product instead.his will require another binding source to be added to the form. Drag a Binding Source componentom the Data section of the Toolbox, name it ProductsBindingSource and set the Data Source property

    o OrdersDataSet and the Data Member property to the Products table.

    ow expand the Smart Tag on the DataGridView control again (or look at the Properties pane) andick the "Edit Columns" action. This allows you to edit width and style of columns, reorder theolumns, and add / delete columns. You can remove any columns that are not necessary and hideVisible property equals False) the Primary Key and Foreign Key fields. You should also convert theroductID column from a Text Box control to a Combo Box control to display value of Product Name.et the Data Source property to ProductsBindingSource, the Display Member to ProductName and thealue Member to ProductID.

    When the Order Detail Binding Source was added, VS also added the following lines of code to the

    OrdersForm_Load event to fill the Order Detail table:

    Dim OrdersDetailTableAdapter As New Order_DetailsTableAdapter

    OrdersDetailTableAdapter.Fill(Me.OrdersDataSet.Order_Details)

    http://mediakit.internet.com/icom_cgi/print/pri...i?url=http://www.15seconds.com/issue/051117.htm (10 de 15) [06/11/2009 19:28:31]

  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    11/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 2

    hat is all we need to do. We can build and run our application by pressing F5 (or selecting "Startebugging from the Debug Menu.) Here is an example of the final form running. Notice that theavigation Bar allows us to move between records and the Order Detail information is linked to the

    Orders record selected. Also in the navigation bar is a yellow asterisk button to create a new record, aed X button to delete the current record, and a diskette button to save changes.

    igure 11 - Final Application Running

    Whereas VS2003 provided one inflexible wizard for RAD construction of master-detail form, VS2005 hasn infrastructure to allow RAD construction of a wide variety of form styles. The Data Sources tool is a

    welcome improvement to Visual Studio.

    eparating the Tiers

    Once again Visual Studio has fostered bad habits in promoting RAD. To get the functionality describedbove, the datasets need to be in the same project as the User Interface. But in the real world, it isetter to separate your business layer from your UI so if you decide to implement a Web interface

    nstead of Windows, much of the application will not need to change.

    We can correct this easily enough. Create a new Class Library project in your solution for your businessbjects. It is best to start out with this project and create the original DataSet there instead of in the UIroject.

    ote: If you have all ready created the application as in the above tutorial, you can move the DataSetwe just created to the new project, but you need to also move the app.config file to keep theonnection strings.

    http://mediakit.internet.com/icom_cgi/print/pri...i?url=http://www.15seconds.com/issue/051117.htm (11 de 15) [06/11/2009 19:28:31]

  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    12/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 2

    reate a new Class Library project in your solution named NorthwindBiz and move the dataset there.S will actually make a new copy of the dataset, leaving the original alone. After copying the dataset,ou will need to remove the dataset in the Windows project. Your will also need to search and replacehe hard coded Namespace references, changing "NorthwindWin" to "NorthwindBiz".

    fter the data set has been created, goack to the form and open the Dataources pane. This time when you add aew data source, instead of using theatabase tool, select the Object tool. On

    he next screen, you will see a list ofeferenced projects you could use. If theeference is not shown, you will need toick the "Add Reference" button andelect the NorthwindBiz project. Expandhe NorthwindBiz project and select the

    OrdersDataSet object. Click Next andinish and you will see the OrdersDataSetsted in the Data Sources Pane.

    f you actually create the business projectefore creating the windows project, you

    will notice a couple of differences. TheWizard no longer automatically instantiateshe table adapter in the form load event.ince we are using an Object Data Source

    which may not even be a dataset, VS

    eaves the Data Access logic up to us. Wemust write that code ourselves now, butather than write it in the Presentationayer, we need to write it in the Businessayer.

    usiness Logic Code

    f you wish to add business logic to your application, VS 2005 adds a Partial Class to the DataSet toacilitate this. Right-click on the OrdersDataSet and select View Code to generate another file under the

    ataSet with code stubs for the Partial Public Class where you can add code that will not beverwritten when the dataset is rebuilt. Partial Classes are a great tool in .NET 2.0 where a class maye separated into different physical files. When you build the project, the code will be merged andompiled together. This is valuable where we have generated code and developer code in the sameass.

    ou can add partial classes for the DataTable, DataRow, and TableAdapter as follows:

    artial Public Class OrdersDataSet

    Partial Public Class OrdersDataTable

    End Class

    Partial Public Class OrdersRow

    http://mediakit.internet.com/icom_cgi/print/pri...i?url=http://www.15seconds.com/issue/051117.htm (12 de 15) [06/11/2009 19:28:31]

  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    13/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 2

    End Class

    nd Class

    artial Public Class OrdersDataAdapter

    nd Class

    f your business logic has to do with the whole table, add your code to the DataTable class. If yourogic has to do with validating a row, add the code to the DataRow class. If you wish to add logic to theata layer of your application, add the code in the Data Adapter class (note how it is outside theataSet class.)

    When you build the dataset in the Windows project, VS automatically adds code to fill the dataset andpdate back to the database. When you build the dataset in a separate business project, VS assumeshat logic will be built into the business object. This is wise because you want to separate any dataccess logic away from the presentation layer. To build these functions, we need to add a coupleunctions to the partial class for the dataset as follows.

    mports ta = NorthwindDataSetTableAdapters

    artial Public Class NorthwindDataSet

    Private taOrders As New ta.OrdersTableAdapter

    Private taOrderDetail As New ta.Order_DetailsTableAdapter

    Private taCustomer As New ta.CustomersTableAdapter

    Private taEmployee As New ta.EmployeesTableAdapter

    Private taProduct As New ta.ProductsTableAdapter

    Public Sub FillDataSetAll()Me.taOrders.Fill(Me.Orders)

    Me.taOrderDetail.Fill(Me.Order_Details)

    Me.taCustomer.Fill(Me.Customers)

    Me.taEmployee.Fill(Me.Employees)

    Me.taProduct.Fill(Me.Products)

    End Sub

    irst, we need to instantiate an object for each of the table adapters. Then we add a method that willall the Fill method for each of the table adapters and fill dataset.

    Other methods need to be added to update the tables. In this dataset, only the Orders and Orderetails tables need to be updated since all the others are for lookup only.

    Public Sub UpdateOrders()

    Me.taOrders.Update(Me.Orders)

    End Sub

    Public Sub UpdateOrderDetails()

    Me.taOrderDetails.Update(Me.Order_Details)

    End Sub

    nd Class

    hese few lines of code will provide access to the Data Access layer through the Business Logic layer,roviding the necessary separation from the presentation layer.

    http://mediakit.internet.com/icom_cgi/print/pri...i?url=http://www.15seconds.com/issue/051117.htm (13 de 15) [06/11/2009 19:28:31]

  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    14/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 2

    ow, back in the presentation layer, in the code behind the form, we need to call these methods of theusiness object. You can create the code stub for the load even by double-clicking in the title bar of theorm and calling the method just created in the Business Layer of our application.

    artial Public Class OrderForm

    Private Sub OrderForm_Load(ByVal sender As System.Object, _

    ByVal e As System.EventArgs) Handles MyBase.LoadMe.NorthwindDataSet1.FillDataSetAll()

    End Sub

    nother piece of code needs to be added to save updates back to the database. There is a an icon inhe Navigation Bar for this for which code is written automatically when the dataset was in the

    Windows project, but when using Object Data Sources, the Wizard leaves that for us to write. You mayeed to change the enabled property for the button and then you can build a code stub for the savevent by double-clicking on the Save Item button in the navigation bar. The following code needs to bedded. Note that you must call the EndEdit method of the binding source to force the form to updatehe dataset.

    Private Sub bindingNavigatorSaveItem_Click(ByVal sender As System.Object,

    ByVal e As System.EventArgs) Handles bindingNavigatorSaveItem.Click

    Me.Validate()

    Me.Order_DetailsBindingSource.EndEdit()

    Me.OrdersBindingSource.EndEdit()

    Me.NorthwindDataSet1.UpdateOrders()

    Me.NorthwindDataSet1.UpdateOrderDetails()

    End Sub

    nd Class

    ou can once again press F5 to run the application to see that the data is filled in and all the sameunctions exist. If any changes to the data are made, the user must click the save button to write thehanges back to the database.

    ummary

    he new version of Visual Studio 2005 offers significant improvements in the flexibility of creating multi-ered application using RAD tools. The Typed Dataset generation tool allows data abstraction betweenhe database and the UI/Business Logic and also provides Object Oriented access to the entities andttributes of a database. The Dataset generator also provides the Data Access code virtually separatednto a separate layer. The Partial Classes feature gives us a nice place to implement Business Logicayer with complete access to the Dataset component.

    he Binding Sources component isolates the UI from the Business Logic layer and provides a smoothata binding tool, transforming our application into more of a 4-tiered application. Finally, the Dataources window allows rapid generation of the Presentation layer and preserving the n-tierednvironment.

    While we do have to write a few lines of code to fill the dataset--in a few minutes, we have generatedgood multi-tier application and the only code we have to write is to implement our unique business

    http://mediakit.internet.com/icom_cgi/print/pri...i?url=http://www.15seconds.com/issue/051117.htm (14 de 15) [06/11/2009 19:28:31]

  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    15/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 2

    ogic.

    What's Next?

    n Part 3 of the series, I will look more closely at what can be done in the Business Logic layer tonhance our application. I will also show some more code generation tools to help write some of theata Access code and also show how to make the Data Access code provider independent so the samepplication can work with different database servers.

    nks

    Overview of Visual Basic 9.0

    Drag once data binding (Steve Lasker)

    Domain Model Architecture (Database Guy)

    Webcast on New Data Features in Win Forms

    Webcast:: Building Data-Bound Windows Forms Applications with Visual Studio 2005

    bout the Author

    David Catherman - CMI Solutions

    Email: DCatherman (at) CMiSolutions (dot) com

    David Catherman has 20+ years designing and developing database applications withspecific concentration for the last 4-5 years on Microsoft .NET and SQL Server. He is

    urrently Application Architect and Senior Developer at CMI Solutions using Visual Studio and SQL

    erver 2005. He has 3 MCP certifications in .NET and is pursuing MCSD.

    ack to article

    Copyright 2005 Jupitermedia Corp. All Rights Reserved.Legal Notices, Licensing, Reprints, &Permissions, Privacy Policy.

    http://www.internet.com

    http://mediakit.internet.com/icom_cgi/print/pri...i?url=http://www.15seconds.com/issue/051117.htm (15 de 15) [06/11/2009 19:28:31]

    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnvs05/html/vb9overview.asphttp://www.code-magazine.com/Article.aspx?quickid=0409051http://www.devx.com/vb2themax/article/19892http://msevents.microsoft.com/CUI/WebCastEventDetails.aspx?EventID=1032271503&Culture=en-UShttp://msevents.microsoft.com/cui/WebCastEventDetails.aspx?EventID=1032268866&EventCategory=5&culture=en-US&CountryCode=UShttp://www.developersguild.org/Default.aspx?tabid=69&mid=444&ctl=Detail&xmid=9&xmfid=1http://www.15seconds.com/issue/051117.htmhttp://www.internet.com/corporate/legal.htmlhttp://www.internet.com/corporate/reprints.html#Licensinghttp://www.internet.com/corporate/reprints.html#Reprintshttp://www.internet.com/corporate/reprints.html#Permissionshttp://www.internet.com/corporate/privacy/privacypolicy.htmlhttp://www.internet.com/http://www.internet.com/http://www.internet.com/corporate/privacy/privacypolicy.htmlhttp://www.internet.com/corporate/reprints.html#Permissionshttp://www.internet.com/corporate/reprints.html#Reprintshttp://www.internet.com/corporate/reprints.html#Licensinghttp://www.internet.com/corporate/legal.htmlhttp://www.15seconds.com/issue/051117.htmhttp://www.developersguild.org/Default.aspx?tabid=69&mid=444&ctl=Detail&xmid=9&xmfid=1http://msevents.microsoft.com/cui/WebCastEventDetails.aspx?EventID=1032268866&EventCategory=5&culture=en-US&CountryCode=UShttp://msevents.microsoft.com/CUI/WebCastEventDetails.aspx?EventID=1032271503&Culture=en-UShttp://www.devx.com/vb2themax/article/19892http://www.code-magazine.com/Article.aspx?quickid=0409051http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnvs05/html/vb9overview.asp
  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    16/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 3

    5 Seconds : Using Visual Studio .NET Wizards to Create an N-TieredApplication - Part 3

    avid Catherman1/23 / 2005

    art 3 - Building the Business Tier

    n Part 1 and 2 of this series, we looked at using the Rapid Application Development (RAD) tools in Visualtudio to develop 3-tiered applications with a strong emphasis on Object Oriented Programming (OOP). Byuilding Typed DataSet objects in a separate Business project and the Object Data Sources tool in ourresentation layer, the parts of our application are isolated into tiers that can be compiled separately and evenstributed to different servers if necessary.

    omain Model Architecture

    While there are many different architecture models available today, there is one that fits the methodologyromoted by Microsoft Visual Studio that is a balance between relational architecture and pure object-oriented

    rchitecture. This architecture has recently been promoted by several renowned architects such as Jimmyilsson and is known as the Domain Model Architecture. Instead of burying the Domain layer deep inside the

    usiness tier, this model elevates it to a position that allows several different layers to have access to the data.gure 1 shows how the model fits with Visual Studio 2005.

    gure 1 - Domain Model Architecture with VS2005 implementation

    his model uses the Typed DataSet as the Domain layer. The TDS wraps the DataSet object with a set ofasses, methods and properties to allow access to data in almost a pure object oriented manner and makes

    he most of using Intellisense. In Visual Studio 2005, theses classes are contained in the generated Designerub-file of the DataSet in a Partial Class. Another Partial Class is provided in a sub-file that is customizable byhe developer and is a good place to implement business logic that affects the data.

    n another part of the Designer sub-file, separated by namespace is the Data Access logic that provides all theDO code needed to retrieve and update the data from a database. The classes generated are called Tabledapters and are Data Adapters wrapped in strongly typed properties and methods. While these classes areenerated, you can extend them by adding code to a Partial Class for the Table Adapters.

    http://mediakit.internet.com/icom_cgi/print/pri...i?url=http://www.15seconds.com/issue/051123.htm (1 de 14) [06/11/2009 19:33:12]

    http://www.devx.com/vb2themax/article/19892http://www.devx.com/vb2themax/article/19892http://www.devx.com/vb2themax/article/19892http://www.devx.com/vb2themax/article/19892
  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    17/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 3

    When first generated, the DataSet mirrors very closely the structure or schema of the database. Somerchitects complain that the DataSet is too tightly coupled with the database schema, but in reality only theetadata is represented. All of the tables and fields can be renamed and mapped to better represent entitiesnd columns if necessary. But if the database has been properly designed, this is not often necessary.

    dding Business Layers

    sing the partial classes for business logic will work for minor code that deals directly with the data. Most

    nterprise developers prefer to have a separate class to contain the logic for each entity. I am currentlyorking with the Mere Mortals Framework by Kevin McNeish which heavily uses business objects. It is fairlyasy to use a Typed DataSet as we have in this example while also instantiating the separate business objectasses and pointing them to a DataTable in the existing DataSet. In his way, you get the best of both worlds

    he power and reusability of business object classes with all the business logic and the data sources wizards forase of building screens.

    usiness Logic

    s we saw in Part 2 of this series, one of the important parts of business logic is providing a pass-through forhe application to call the Data Access layer. Each Table Adapter needs to be instantiated and a methodrovided to fill the DataTable in the DataSet. For those tables that are updateable, a method should also berovided to pass updates back to the database. For the Northwind DataSet containing 5 tables in the Part 2xample, here is the Data Access code needed:

    mports ta = NorthwindDataSetTableAdapters

    artial Public Class NorthwindDataSet

    Private taOrders As New ta.OrdersTableAdapter

    Private taOrderDetail As New ta.Order_DetailsTableAdapter

    Private taCustomer As New ta.CustomersTableAdapter

    Private taEmployee As New ta.EmployeesTableAdapterPrivate taProduct As New ta.ProductsTableAdapter

    Public Sub FillDataSetAll()

    Me.taOrders.Fill(Me.Orders)

    Me.taOrderDetail.Fill(Me.Order_Details)

    Me.taCustomer.Fill(Me.Customers)

    Me.taEmployee.Fill(Me.Employees)

    Me.taProduct.Fill(Me.Products)

    End Sub

    Public Sub UpdateOrders()Me.taOrders.Update(Me.Orders)

    End Sub

    Public Sub UpdateOrderDetails()

    Me.taOrderDetails.Update(Me.Order_Details)

    End Sub

    nd Class

    his is a simplistic example where the DataTables are filled with all the records in the database. For larger

    atabases, the fills can be done by passing a filter parameter.

    arameterized Queries

    ne of the options in the DataSet Designer that we have not covered yet is the ability to add multiple

    http://mediakit.internet.com/icom_cgi/print/pri...i?url=http://www.15seconds.com/issue/051123.htm (2 de 14) [06/11/2009 19:33:12]

  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    18/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 3

    arameterized queries through which data can be retrieved from the database if you want something less thanl the records in the table. If you open the dataset and right-click on one of the table adapter headers, you seelist of functions available. The Add Query option opens the Table Adapter Configuration Wizard with theptions to use SQL statements, create new stored procedures, or use existing stored procedures. For simpleueries you can use SQL statements but in a secure environment, it is best to use stored procedures to accesshe data. The ones generated by the Wizard are adequate, but you may use some that are generated by yourBA. If you do use existing SPs the next screen will allow you to select them for a list of all stored procedures the database.

    gure 2 - Table Adapter Command Type

    he next screen offers the choice of what the query will be used for. The options are: Select a set of rows,eturn a single value, Update, Delete, or Insert. Most often the query will be to return a set of rows, but theption to change the way an update or delete happens is interesting also.

    http://mediakit.internet.com/icom_cgi/print/pri...i?url=http://www.15seconds.com/issue/051123.htm (3 de 14) [06/11/2009 19:33:12]

  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    19/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 3

    gure 3 - Table Adapter Query Type

    ach query is defined by a SQL Statement which can be typed in here or built visually using the standard Visualuery Builder.

    gure 4 - Table Adapter Select Statement

    t this point you can add a filter parameter to the query to only get orders for a specific customer

    http://mediakit.internet.com/icom_cgi/print/pri...i?url=http://www.15seconds.com/issue/051123.htm (4 de 14) [06/11/2009 19:33:12]

  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    20/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 3

    gure 5 - Visual Query Builder

    gure 6 - Table Adapter Method Names

    he next screen in the Wizard allows you to edit the names for the FillBy (for existing DataTables) andetDataBy (returns an DataTable object) types of methods. Clicking the Finish button will complete the query.

    he DataSet Designer will add another line to the Table Adapter section of the table representation showing theew method. Now the DataTable can be filled with only part of the orders by calling the FillByCustomerID andassing a CustomerID parameter.

    http://mediakit.internet.com/icom_cgi/print/pri...i?url=http://www.15seconds.com/issue/051123.htm (5 de 14) [06/11/2009 19:33:12]

  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    21/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 3

    sing Optional Parameters

    nother way to provide flexibility in your table adapters is to use optional parameters and allow the user thehoice of several different parameters with one call. In this example, we could make one query that wouldlow the user to fill by either the CustomerID or the EmployeeID by adding to the WHERE clause "OR

    @Parameter IS NULL" as follows.

    ELECT *

    ROM OrdersHERE (CustomerID = @CustomerID OR @CustomerID IS NULL)

    AND (EmployeeID = @EmployeeID OR @EmployeeID IS NULL)

    AND NOT (@CustomerID IS NULL AND @EmployeeID IS NULL)

    n this example you can pass any or both parameters but if you don't pass any, you will get an empty resultet.

    yped DataSets handle optional parameters fairly well. The generator will create Nullable(Of Type) parametersor value types and correctly convert to dbnull.

    he only disadvantage with optional parameters in Typed DataSets is you have to take care of the parametersollection yourself. Most of the time you have to set the AllowDBNull property by hand, and the Wizard willeset its state every time you reconfigure the query.

    illing a Table by Relation

    nce we have limited the number of records in the Orders table, we should also limit the rows when filling therder Details table. It would be nice if Microsoft added a feature for filling by relationship, but it did not make itto this version. So we need to come up with a work around.

    we were using stored procedures, we could use the Multiple Active Result Sets (MARS) feature of SQL Server005 to return the data for both tables at once. You have to add some extra code to map the result sets intohe correct Data Tables, but it is not very difficult. Using the partial class for the Table Adapter is a good placeo write this code since you have access to the Data Adapter object to add the TableMappings method.

    http://mediakit.internet.com/icom_cgi/print/pri...i?url=http://www.15seconds.com/issue/051123.htm (6 de 14) [06/11/2009 19:33:12]

  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    22/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 3

    gure 7 - Query to Fill Order Details by Relation

    nother approach would be to loop through the records in the Orders table and create a string of delimitedrderIDs to pass as a parameter to be used by an IN() clause filter. But the IN() clause does note accept aariable, so you would have to build the SQL Statement concatenating the list of IDs into the statement and

    sing an EXEC function to execute it at runtime.

    he easiest solution is to add another query to the Order Details Table Adapter that joins the tables togethernd filters on the same CompanyID as shown in the Query Builder of Figure 7. If this is the primary queryefining the Order Details table, this will not work since it is hard for the Update to know which table to update.ut as a secondary query, it should work fine.

    pdating Multiple Tables

    n the previous article, I showed a very simple procedure for updating the dataset back to the database. Buthe update method requires special concern when updating related tables. If the tables are updated in therong order, you could end up trying to delete parent records before child record or inserting child recordefore inserting parent records.

    he correct sequence for updating related tables is to first send the deleted children, then update the parentable, and then update and add the children records. The GetChanges method of the DataTable allows for thisunctionality. First we create new temporary DataTables and define them as subsets of the current Data Tableased on which records have been added or deleted. Then each of these temporary Data Tables is updated inhe correct sequence. (Note: The format for this code can be found in the VB Code Snippets insert.)

    Public Sub UpdateDB()

    Dim DeletedChildRecords As DataTable = _Me.Order_Details.GetChanges(DataRowState.Deleted)

    Dim NewChildRecords As DataTable = _

    Me.Order_Details.GetChanges(DataRowState.Added)

    Dim ModifiedChildRecords As DataTable = _

    http://mediakit.internet.com/icom_cgi/print/pri...i?url=http://www.15seconds.com/issue/051123.htm (7 de 14) [06/11/2009 19:33:12]

  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    23/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 3

    Me.Order_Details.GetChanges(DataRowState.Modified)

    Try

    If Not DeletedChildRecords Is Nothing Then

    taOrderDetail.Update(DeletedChildRecords)

    DeletedChildRecords.Dispose()

    End If

    taOrders.Update(Me.Orders)

    If Not ModifiedChildRecords Is Nothing Then

    taOrderDetail.Update(ModifiedChildRecords)

    ModifiedChildRecords.Dispose()

    End If

    If Not NewChildRecords Is Nothing Then

    taOrderDetail.Update(NewChildRecords)

    NewChildRecords.Dispose()

    End If

    Me.AcceptChanges()

    Catch ex As Exception

    Throw ex

    End Try

    End Sub

    dding Other Business Logic

    he partial class of the DataSet is a great place to implement any business logic that has to do with actual dataems. We used the partial class for the dataset to instantiate the table adapters, but there are also sub partialasses for each of the tables (row collections), individual rows of a table, and even the row change event.utside of the dataset partial class, you can also access the partial class for each of the Table Adapters.

    or example, if you wanted to create method that would consolidate two orders for the same customer by

    moving all the Order Detail records from one Order to another, you could create the following class inside theataSet partial class (sub-class):

    artial Public Class OrdersDataSet

    ..

    Partial Public Class Order_DetailsDataTable

    Public Sub MoveDetailRecords(ByVal FromOrderID As Integer,

    ByVal ToOrderID As Integer)

    For Each row As Order_DetailsRow In Me.Select("OrderID=" & FromOrderID)

    row.OrderID = ToOrderID

    NextEnd Sub

    End Class

    ..

    nd Class

    ack in the form code the new method is accessible on the Intellisense list.

    http://mediakit.internet.com/icom_cgi/print/pri...i?url=http://www.15seconds.com/issue/051123.htm (8 de 14) [06/11/2009 19:33:12]

  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    24/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 3

    gure 8 - Customized Method in Intellisense

    nother example might be the need for a method that will copy the address information from the customer tohe shipping section of the order.

    Partial Public Class OrdersRow

    Public Sub ShipToCustomer()

    If Me.CustomerID Is Nothing Then

    MsgBox("Customer not defined") 'TODO: should throw an exception

    Return

    End IfDim CustTable As CustomersDataTable = Me.Table.DataSet.Tables

    "Customers")

    Dim CustRow As CustomersRow = CustTable.FindByCustomerID(Me.CustomerID)

    Me.ShipName = CustRow.ContactName

    Me.ShipAddress = CustRow.Address

    Me.ShipCity = CustRow.City

    Me.ShipRegion = CustRow.Region

    Me.ShipPostalCode = CustRow.PostalCode

    Me.ShipCountry = CustRow.Country

    End Sub

    End Class

    ack in the form code, when you get a reference to an OrderRow object, the method is available to copy thehipping address.

    hese are just a couple examples of how to build business logic in the partial class of the DataSet. Thedvantage is that all of the DataSet objects are available in context. If you were to create another specific classs your business object, you would always have to pass a reference to the dataset to access the data objects.n the above examples, the data object can be referenced as "Me" since the coding is inside the dataset object.

    sing Macros to Generate Data Access Code

    nce the code for the Data Access layer is very repetitive, varying only by the table name, this is a good placeor code generation. There are many different code generators available, each with their strengths and shortomings. Recently I have been investigating using macros to generate code. The advantage to this method ishat the generation is done in the context of the IDE. All of the formatting, indentation, and End tags areserted just like when you are typing the code manually.

    o create a macro, from the VS top line menu select Tools / Macros / Macros IDE. This will open another IDEmilar to VS for editing macros. In the class list, right click on MyMacros and add a new class (or Module)

    alled GenDataAccessLayer. Inside of the new class create the following method.

    he following macro uses reflection to look into the dataset, instantiate each table adapter and call the fillmethod of each. The following namespaces need to be included:

    http://mediakit.internet.com/icom_cgi/print/pri...i?url=http://www.15seconds.com/issue/051123.htm (9 de 14) [06/11/2009 19:33:12]

  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    25/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 3

    mports EnvDTE

    mports EnvDTE80

    mports System.Diagnostics

    mports System.Reflection

    mports System

    n a macro, the Visual Studio integrated development environment (DTE) contains a pointer to the activeocument which points to the item from the Solution Explorer that is open. The item also knows which project

    is in.

    ublic Sub DefineTAviaReflectionVB()

    Dim pItem As ProjectItem = DTE.ActiveDocument.ProjectItem

    Dim ItemName As String = pItem.Name.Substring(0, pItem.Name.LastIndexOf("."))

    Dim proj As Project = pItem.ContainingProject

    Dim line As String = ""

    Dim TableName As String

    Dim taList As String

    Dim UpdateList As String = ""

    Dim UpdateType As MethodInfo

    rom the full project name, we can build the location of the actual assembly. If you are looking for a Windowsorms assembly rather than the Business class library, you should use the .EXE instead of the .DLL extension.

    ProjName = ProjName.Substring(0, ProjName.LastIndexOf("\") + 1)

    ProjName = ProjName & "bin\debug\" & proj.Name & ".dll"

    nce you have the assembly, you can load the assembly from the file. There should be a better way to get aeference to the assembly from the project itself, but I have not yet found one.

    Dim targetAssembly As Assembly = Assembly.LoadFrom(ProjName)

    ow loop through each Type in the assembly, looking for those in the group of dataset table adapters ending inTableAdapter".

    For Each typ As Type In targetAssembly.GetTypes()

    If typ.FullName Like "*" & ItemName & "TableAdapters." & _

    "*TableAdapter" Then

    TableName = typ.Name.Substring(0, _

    typ.Name.LastIndexOf("TableAdapter"))

    ere is where the line of code actually gets built.

    line = "Dim ta" & TableName & " As " & ItemName & _

    "TableAdapters." & typ.Name

    DTE.ActiveDocument.Selection.NewLine()

    DTE.ActiveDocument.Selection.Text = line

    ave the object name for building the fill methods later.

    taList &= "ta" & TableName & ","

    heck if the table adapter has an update method (actually it is easier to check for the Delete method) and storehe table adapter for later use.

    http://mediakit.internet.com/icom_cgi/print/pri...i?url=http://www.15seconds.com/issue/051123.htm (10 de 14) [06/11/2009 19:33:12]

  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    26/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 3

    UpdateType = typ.GetMethod("Delete")

    If UpdateType IsNot Nothing Then

    UpdateList &= "ta" & TableName & ","

    End If

    Next

    ow build a method to call the fill method for each table adapter.

    DTE.ActiveDocument.Selection.EndOfLine()DTE.ActiveDocument.Selection.NewLine()

    'Add the Update methods

    For Each ta As String In UpdateList.Split(",")

    If ta.Length > 0 Then

    DTE.ActiveDocument.Selection.Text = "Public Sub Update" + _

    ta.Substring(2) + "()"

    DTE.ActiveDocument.Selection.NewLine()

    DTE.ActiveDocument.Selection.Text = ta & ".Update(" & _

    ta.Substring(2) & ");"

    DTE.ActiveDocument.Selection.NewLine()

    End IfNext

    targetAssembly = Nothing

    nd Sub

    his code applied to our Northwind example generates the following code:

    artial Class NorthwindDataSet

    Dim taCustomers As New NorthwindDataSetTableAdapters.CustomersTableAdapter

    Dim taEmployees As New NorthwindDataSetTableAdapters.EmployeesTableAdapter

    Dim taOrder_Details As New NorthwindDataSetTableAdapters.rder_DetailsTableAdapter

    Dim taOrders As New NorthwindDataSetTableAdapters.OrdersTableAdapter

    Dim taProducts As New NorthwindDataSetTableAdapters.ProductsTableAdapter

    Public Sub FillAll()

    taCustomers.Fill(Customers)

    taEmployees.Fill(Employees)

    taOrder_Details.Fill(Order_Details)

    taOrders.Fill(Orders)

    taProducts.Fill(Products)

    End SubPublic Sub UpdateOrder_Details()

    taOrder_Details.Update(Order_Details)

    End Sub

    Public Sub UpdateOrders()

    taOrders.Update(Orders)

    End Sub

    nd Class

    would appreciate some feedback on the logic here. Is it better to leave the table adapter instantiated for the

    fe of the dataset (is there a large memory hit for this object), or would it be better to instantiate it each time itneeded (what is the processor requirement to instantiate this object) and free up the memory. In this case, Ihose to leave them instantiated so they would be available for the update call.

    atabase Provider Independence

    http://mediakit.internet.com/icom_cgi/print/pri...i?url=http://www.15seconds.com/issue/051123.htm (11 de 14) [06/11/2009 19:33:12]

  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    27/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 3

    ne thing Microsoft did not get added to the Table Adapter logic is to take advantage of the Provider Pattern tolow switching between different back end database engines. The Provider Pattern is a combination of thebstract Factory Pattern and a couple others to streamline the ability to switch between different back-endsithout recompiling the application. This pattern is available in DotNetNuke, ASP.NET and a few other Microsoft

    echnologies, but they did not have time to get it to work with the generated Table Adapters. Since I still haveneed to develop an application that can be database independent, I have continued to pursue a strategy forccomplishing the feat.

    n my first attempt, I tried to change the connection string to a different source and then regenerate theataset. This did not work because the dataset generator trying to use the old ADO connection type. But youan create another connection to the other database and inside the dataset generator, change whichonnection each table points to and then regenerate the table.

    o continue with our Northwinds example, the sample database from Microsoft is available in MS Access,oxPro, and SQL Server. To demonstrate this procedure, I will convert our sample application so that it will rungainst the Access database as well as the SQL Server database. Where this is less complicated if the OLEDBrovider were originally used for the SQL Server connection, this demonstration will use OLEDB provider for theccess database and continue to use the SQLClient provider for SQL Server.

    ur sample application currently is configured to work with the SQL Server connection. Before we change thato an Access Connection, let's save the current configuration so we can easily come back to it. Open theataSet and open the Designer code file. (You may have to turn on the "Show All Files" option at the top ofolution Explorer in order to see the sub files under the DataSet.) There are two main sections inside theesigner file: the Partial Public Class OrdersDataSet and the Namespace OrdersDataSetTableAdapters. Therere several rows of attributes decorating the class, but if you collapse the section by clicking the minus sign inhe margin, you should see the two sections.

    gure 9 - DataSet Designer code file

    you highlight the Table Adapters section and press Ctrl+C, you are copying the whole section. Now create aew Class module in the project, name it OrdersDataSetTableAdapters.SQL and paste the copied code into it.f course this will generate errors because of the duplication, but if we change the Namespace by adding a ".QL" on the end of it, it should compile fine.

    he next step is to go back to the DataSet Designer for the Orders DataSet, right click on the Orders table andelect Configure.... The Wizard starts on page 3, but you can click the Previous button twice to get back to therst page where the connection is defined. Select the connection for the Access database or click the Newonnection button to create a new one. By adding a connection here, it will be recorded in Project settings and the App.Config file.

    fter changing the connection string, proceed through and finish the Configuration Wizard. The Table Adapteras now been changed to point to the Access database.

    http://mediakit.internet.com/icom_cgi/print/pri...i?url=http://www.15seconds.com/issue/051123.htm (12 de 14) [06/11/2009 19:33:12]

  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    28/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 3

    gure 10 - Changing Table Adapter Connections

    ontinue this procedure for each table in the dataset and you will have converted the application to now usehe Access database instead of SQL Server. You should be able to run the application and see the Access data.

    you have doubts, you can try changing some of the information and then look into both the Access and SQLerver tables to see where it has changed.

    he next step is to capture the Table Adapters section from the Designer file and create another Class modulealled OrderDataSetTableAdapters.Jet and paste in the code. Change the Namespace this time by adding a ".et" on the end of it.

    ow we can switch back and forth between Access and SQL Server simply by changing the extension of theamespace on the Imports statement at the top of the Developers partial class file. Adding a ".Jet" points the

    able adapters to the code saved for connecting to Access.

    mports ta = NorthwindDataSetTableAdapters.Jet

    artial Public Class NorthwindDataSet

    Private taOrders As New ta.OrdersTableAdapter

    Private taOrderDetail As New ta.Order_DetailsTableAdapter

    ..

    While this is a large step in the right direction, it is not the final solution because you still have to build theroject after changing the extension. In a true Provider Pattern, you should be able to make the change simplyy changing a parameter in the App.Config file and never have to recompile. I plan to continue working on theroblem and will probably come back with a solution in a future article. If any of you come up with an idea,ease let me know.

    onclusion

    http://mediakit.internet.com/icom_cgi/print/pri...i?url=http://www.15seconds.com/issue/051123.htm (13 de 14) [06/11/2009 19:33:12]

  • 7/29/2019 Using Visual Studio .NET Wizards to Create an N-Tiered Applicat

    29/29

    15 Seconds : Using Visual Studio .NET Wizards to Create an N-Tiered Application - Part 3

    am still very impressed with Visual Studio 2005 and the advances made in developing data applicationsapidly. I am finally using the actual release bits and all of this development done during the Beta cycle stillorks. One interesting change is the new attributes added to each class in the Designer code. One of theroblems of working with Table Adapters is that they are not inherited from any base class nor do they

    mplement any interface making it hard to apply object oriented techniques to them. The inclusion of thettributes should provide the links necessary to work with using CodeDom and reflection. Look for futurerticles as I figure out what is going on.

    bout the Author

    David Catherman - CMI Solutions

    Email: DCatherman (at) CMiSolutions (dot) com

    David Catherman has 20+ years designing and developing database applications with specificconcentration for the last 4-5 years on Microsoft .NET and SQL Server. He is currently

    pplication Architect and Senior Developer at CMI Solutions using Visual Studio and SQL Server 2005. He has 3CP certifications in .NET and is pursuing MCSD.

    ack to article

    Copyright 2005 Jupitermedia Corp. All Rights Reserved.Legal Notices, Licensing, Reprints, &Permissions, Privacy Policy.

    http://www.internet.com

    http://www.developersguild.org/Default.aspx?tabid=69&mid=444&ctl=Detail&xmid=9&xmfid=1http://www.15seconds.com/issue/051123.htmhttp://www.internet.com/corporate/legal.htmlhttp://www.internet.com/corporate/reprints.html#Licensinghttp://www.internet.com/corporate/reprints.html#Reprintshttp://www.internet.com/corporate/reprints.html#Permissionshttp://www.internet.com/corporate/privacy/privacypolicy.htmlhttp://www.internet.com/http://www.internet.com/http://www.internet.com/corporate/privacy/privacypolicy.htmlhttp://www.internet.com/corporate/reprints.html#Permissionshttp://www.internet.com/corporate/reprints.html#Reprintshttp://www.internet.com/corporate/reprints.html#Licensinghttp://www.internet.com/corporate/legal.htmlhttp://www.15seconds.com/issue/051123.htmhttp://www.developersguild.org/Default.aspx?tabid=69&mid=444&ctl=Detail&xmid=9&xmfid=1