Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Building an N-Tier Application in VB.NET, in 8 Steps

0.00/5 (No votes)
24 May 2012 1  
This article will show you how to build an N-Tier application in VB.NET.

Introduction

Many people Google for an article or tutorial that demonstrates how to create an N-Tier applications step by step in VB.NET and for a Windows Application. In this article, I will show you step by step on  how to do it. I made an example from one of the small projects I did in N-Tier. I have included ways to request to pass data between layers. This is a good practice and it is simple to maintain your code if it is in tiers. Imagine having your Business Layer, Data Layer in the Presentation Layer (your VB form, ASP page). Your code will be spaghetti code that will be time consuming when it has to be maintained. Before we start coding, let's see what is N-Tier and why it is used.

Background 

N-Tier is a client-server architecture in which User interface (Presentation Layer), Business Rules (Business Logic Layer), Data Access (Data Layer) are separated in layers, maintained and developed independently. The application will be broken into tiers. The Presentation Layer will be your Form or ASP.NET page, the Business Layer will be the classes that will check if the Business Rules have been violated or not before sending data to the dataLayer and the Data Access layer will accept the validated data from the Business Logic Layer and run the SQL commands on the actual database.

When reading this article, I assume that you know how

  • ADO.NET works 
  • OOPS works 
  • Visual Studio 2003 works 

Getting started 

Make sure that your table is in place and it has a Primary key. Because if you are using an Adapter, you cannot update a table that has no Primary key, you will only select.

Step 1 (Adding PL and BLL) 

In the first step we are going create a Solution. You can call it anything meaningful. In my case I call it "Pro_Client". This will be will be your Presentation Layer, that is where the user will interact with the actual data that we are going to consume later in the article. This can be a windows project or a web project it does not matter. 

Step 2 (Adding PL and BLL)

In the Solution Explorer, select your Solution "Prop_Client" and right click. In the menu, select "Add" and "New Project". An Add New Project dialog box will appear and you must select "Class Library" because we are going to use this project as our BLL (Business Logic Layer), and name it "Prop_BLL" or something meaningful that will show you that it is a BLL. Rename "Class1" to "clsPropertyBLL", or something meaningful. Double click on the renamed class or view the code. You will notice that "Class1" is still there. Change it to something meaningful, if you are working with Employees, use "Employees", in my case "Properties". You are done with your BLL, we will visit it later.

Step 3 (Adding DAL to a Solution)

In this step, we are going to add our DAL in the same Solution. Select your Solution "Prop_Client" and right click; in the menu, select "Add" and "New Project". An Add New Project dialog box will appear and you must select "Class Library" and name it "PropDAL", or something meaningful to show that this is your DAL. After you have done that, delete "Class1" from your DAL project, we will not use it. The next thing is to add a component. For a beginner, you will not use a Class directly. I want you to drag and drop some adapters from the Toolbox. Now to add a component into our DAL, you must right click on the DAL project, in my case "PropDAL", and select "Add" and "Add Component" and give it a meaningful name; in my case, I have named it "Property_DAL". Double click the component and you will see that the name of the component is the same as the class name. Use the name for the class you used in your BLL, in my case "Properties". That means the code in your component will look like this.

Public Class Properties
Inherits System.ComponentModel.Component         
End Class

Now our solution will look like:

Screenshot - Structure_Vs2003.jpg

Figure 1

Step 4 (Adding DAL components)

In this step we are going to add an Adapter. On your DAL project, double click on the component, "Property_DAL" in my case, and select your toolbox section of "DATA". In the Toolbox, select SQLdataAdapter and the Adapter dialog box will appear. Click on "Next", select the connection. Note that if it is the first time you do this, you will have to create a connection like in this example. Click Next when the connection is established. In "Query type", for now, let's select "Use SQL Statement", and click Next. You will get a space where you can type in your SQL statement or use a Query Builder to let Visual Studio build a query for you. Let's type our SQL statement like this:

select * from Clients  where Client_name = @Clientname

This is a parameterized query. Sometimes we don't know what to display until runtime and we might decide to display something else at runtime. In that case we use a parameterized query. The above SQL query will be your commandtext in the adapter. When you are finished, you will click Next, then the Report about your adapter will appear. If you see a yellow exclamation mark on the Update, you should know that it might be that you did not set a Primary Key in your table. If there are no Errors in your Adapter, click on Finish and your adapter will be created for you, and note that the Connection object will appear on your component. Right click and rename the connection object to "cnProperties" and your adapter to "daProperties". If you are using SQL, on the Properties of your connection, click on Connection string and enter the password after the user ID and your Connectionstring will look like this:

user id=sa; Password=topman;data source=Myserver;persist security info=False;initial catalog=ValRollClients

The next step is to right click on the Adapter "daProperties" and Generate a dataset. Name your dataset as "dsProperties" and check the option "Add this Dataset to the Designer" to visually see it on top of the component; after that, click OK.

Now everything has been setup. Our data source is fine, let's go back to the Presentation Layer.

Step 5 (Presentation Layer)

Now in this step, we have to do a few small adjustments. First add a DataGrid into your Form and name it dgproperties and add four buttons like this:

Screenshot - Appl.jpg

Figure 2

Don't forget to rename your form to "frmsearch".

Step 6 (Function in DAL)

Let's go back again to our DAL project. We are going to give our data to BLL from DAL and BLL will give the data to the front-end (PL).

Screenshot - N-Tier.jpg

Figure 3

Now let's create a function that will return a DataSet and takes a parameter. Double click on your component and enter the following code inside the class.

Public Function Getdat(ByVal strname As String) As dsProperties
    Dim dsdata As dsProperties
    Try 
        dsdata = New dsProperties
        'We are Accepting an input parameter 
        daproperties.SelectCommand.Parameters("Clients").Value = strname
        'filling the dataset 
        daproperties.Fill(dsdata)
    Catch Throw 
        'In this Layer we dont Display Error or Exceptions. BLl will take care of that 
        'we are throwing the Exception to be handled by the Calling Function End Try 
        'Here we are returning a dataset filled with requested data 
        Return dsdata
End Function  

Remember, we have to save changes too, so we are going to create another Sub procedure that will save the changes into the database. So for saving, create this sub procedure in your component class. After the first one, like this:

Public Sub SaveData(ByVal dsdata As dsProperties)
    Try
        daproperties.Update(dsdata)
    Catch
    Throw
        'In this Layer we dont Display Error or Exceptions. BLl will take care of that 
        'we are throwing the Exception to be handled by the Calling Function
    End Try
End Sub

Now everything has been added to our DAL, so we are going to call this function and Sub Procedure in the BLL (Business Logic Layer).

Step 7 (Calling DAL Functions in BLL)

Now we are going to call the DAL function when data is requested from the Business Logic layer from the Presentation Layer. Go to the BLL project and double click on "clsPropertyBLL" to view the code. The first thing we need to create is a function that will request the data from the DAL and a Save function that will send data to the BLL and some Business Rules check before we save to the actual database. Before we start coding, add a reference to the DAL on the BLL. Right click on the BLL and select Add Reference, in the dialog box, select the Project tab and click on your DAL project and click OK.

In the Class Properties of the BLL, add the following code:

Public Function GetData(ByVal strname As String) As Prop_DAL.dsProperties
    Dim dsdata As Prop_DAL.dsProperties
    'Creating an Object of a Class Properties in the Dal layer
    Dim objgetdal As Prop_DAL.Properties
    Try
        dsdata = New Prop_DAL.dsProperties
        objgetdal = New Prop_DAL.Properties
        'Calling the Function of DAL and Passing Arguments to the Function
        dsdata = objgetdal.Getdata(strname)
        If dsdata.Tables("Clients").Rows.Count = 0 Then
            MsgBox("No record with that Name was Found")
        Else
            'return a dataset with Data
            Return dsdata
        End If
    Catch ex As SqlClient.SqlException
        Throw ex
    End Try
End Function

The next Sub should save and we need a Sub to check if the Business Rules have been violated.

Public Function SaveData(ByVal dsdata As Prop_DAL.dsProperties) As Prop_DAL.dsProperties
    Dim objDal As Prop_DAL.Properties
    Try
        objDal = New Prop_DAL.Properties
        Me.CheckRules(dsdata)

        'saving the Data
        objDal.SaveData(dsdata)
    Catch ex As Exception
    End Try
End Function

In the above function, we will check the Rules using a Sub that will be explained below. If the Rules are not violated, then we can save the data by calling a DAL function through a DAL object "objDAL". The following code is for checking Business Rules.

Private Sub CheckRules(ByVal dsdata As Prop_DAL.dsProperties)
    Dim strMsg As String
    Dim row As Prop_DAL.dsProperties.ClientsRow
    'Iterating through the Dataset and Checking the Rules
    For Each row In dsdata.Clients.Rows
        If row.RowState = DataRowState.Added Or _
            row.RowState = DataRowState.Modified Then
            'Start Checking the Rules now
            If row.Client_Name.Trim = "" Then
                MsgBox("Name Cannot be Empty")
            End If
            If row.Client_Address = "" Then
                MsgBox("Address Cannot be Empty")
            End If
            If row.Client_ID.ToString.Length > 13 Then
                MsgBox("ID number must less than 13")
            End If
        End If
    Next
    If strMsg <> "" Then
        'throw a new ApplicationException
        'with our Custom Error message in it
        Throw New ApplicationException(strMsg)
    End If
End Sub

everything is done, and your BLL can now communicate with your DAL and your PL will communicate with your DAL through your BLL. The next thing is to call your BLL functions from your PL. Add a reference to your BLL project in the PL project as I did when I added a reference to the DAL in the BLL project.

Step 8 (Call BLL functions from PL)

This is the last step of our article. In this step we are going to call the BLL functions. Firstly double click on your Form and declare a module level dataset like this:

Public Class Form1
Inherits System.Windows.Forms.Form
Dim mdsProperty As Prop_DAL.dsProperty

Note that this should not be inside your Form load, but outside, because it is a Module level declaration that we want. On your Search button, insert the following code:

Dim objBll As Prop_BLL.Properties Dim strsearch As String = CStr(txtsearch.Text)
btnClear.Enabled = True
Try
    mdsProperty = New Prop_DAL.dsProperty
    objBll = New Prop_BLL.Properties
    mdsProperty = objBll.GetData(strsearch)
    'Binding the Datagrid
    dgProperties.DataMember = "Clients"
    dgProperties.DataSource = mdsProperty
Catch ex As SqlClient.SqlException
    Messagebox.Show(ex.Message)
End Try

And in the code for the button Clear, you will enter the following code to clear the grid.

mdsProperty.Clear()
btnClear.Enabled = False

And the last button will be the Exit button, you can enter your own code to exit the application or Form. So your N-Tier application should be done now in 8 steps.

Conclusion

Designing your application as an N-Tier application helps you to trace bugs and helps you to improve your application at ease, than trying to trace a small bug in a mixed application having everything in one place. I would like to learn more from anyone who has suggestions and has more knowledge on N-tier applications. My next article will be on Web Services. I want to make the subject broad by building an example of a Windows N-tier application that uses Web Services. To those who know me, you know that this is not my first article. Thanks for every e-mail I got asking questions about the article and how to implement it in their situations. If you liked this article, vote for it and email me at  

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here