Click here to Skip to main content
15,879,053 members
Articles / Database Development / SQL Server

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

Rate me:
Please Sign up or sign in to vote.
3.53/5 (31 votes)
24 May 2012CPOL9 min read 271.9K   7.8K   129   41
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

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.

VB
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:

SQL
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.

VB
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:

VB
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:

VB
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.

VB
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.

VB
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:

VB
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:

VB
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.

VB
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Vimalsoft
South Africa South Africa
Vuyiswa Junius Maseko is a Founder of Vimalsoft (Pty) Ltd (http://www.vimalsoft.com/) and a forum moderator at www.DotnetFunda. Vuyiswa has been developing for 16 years now. his major strength are C# 1.1,2.0,3.0,3.5,4.0,4.5 and vb.net and sql and his interest were in asp.net, c#, Silverlight,wpf,wcf, wwf and now his interests are in Kinect for Windows,Unity 3D. He has been using .net since the beta version of it. Vuyiswa believes that Kinect and Hololen is the next generation of computing.Thanks to people like Chris Maunder (codeproject), Colin Angus Mackay (codeproject), Dave Kreskowiak (Codeproject), Sheo Narayan (.Netfunda),Rajesh Kumar(Microsoft) They have made vuyiswa what he is today.
This is a Organisation

4 members

Comments and Discussions

 
QuestionConnection Pin
Indytw26-Nov-18 16:09
Indytw26-Nov-18 16:09 
QuestionConverting to 3 tier structure Pin
Member 1336241815-Aug-17 9:28
Member 1336241815-Aug-17 9:28 
QuestionQuestion About N-Tier Tutorial Pin
Member 119887601-Feb-16 5:55
Member 119887601-Feb-16 5:55 
AnswerRe: Question About N-Tier Tutorial Pin
Vimalsoft(Pty) Ltd1-Feb-16 6:52
professionalVimalsoft(Pty) Ltd1-Feb-16 6:52 
QuestionStep 8 Pin
Marvz24-Apr-15 3:03
Marvz24-Apr-15 3:03 
AnswerRe: Step 8 Pin
Vimalsoft(Pty) Ltd13-Jun-15 6:54
professionalVimalsoft(Pty) Ltd13-Jun-15 6:54 
GeneralMy vote of 5 Pin
awadhassan11-Jan-13 20:49
awadhassan11-Jan-13 20:49 
GeneralRe: My vote of 5 Pin
Vimalsoft(Pty) Ltd11-Jan-13 21:00
professionalVimalsoft(Pty) Ltd11-Jan-13 21:00 
GeneralMy vote of 5 Pin
Sainey31-May-12 15:24
Sainey31-May-12 15:24 
GeneralMy vote of 4 Pin
Sean Botha27-May-12 20:17
Sean Botha27-May-12 20:17 
GeneralMy vote of 3 Pin
Leonardo Paneque21-May-12 10:03
Leonardo Paneque21-May-12 10:03 
GeneralThanks N-Tier App Pin
JAYANTHIMURUGESAN19-Mar-12 15:52
JAYANTHIMURUGESAN19-Mar-12 15:52 
GeneralRe: Thanks N-Tier App Pin
Vimalsoft(Pty) Ltd19-Mar-12 18:39
professionalVimalsoft(Pty) Ltd19-Mar-12 18:39 
QuestionThis isn't n-tier, IMO Pin
Marc Clifton28-Feb-12 6:24
mvaMarc Clifton28-Feb-12 6:24 
AnswerRe: This isn't n-tier, IMO Pin
Vimalsoft(Pty) Ltd28-Feb-12 21:35
professionalVimalsoft(Pty) Ltd28-Feb-12 21:35 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey23-Feb-12 19:41
professionalManoj Kumar Choubey23-Feb-12 19:41 
GeneralMy vote of 5 Pin
Rahul Rajat Singh22-Feb-12 1:28
professionalRahul Rajat Singh22-Feb-12 1:28 
Questionwhy two catch blocks in BLL and PLL Pin
Amila thennakoon21-Feb-12 18:05
Amila thennakoon21-Feb-12 18:05 
AnswerRe: why two catch blocks in BLL and PLL Pin
Vimalsoft(Pty) Ltd22-Feb-12 0:58
professionalVimalsoft(Pty) Ltd22-Feb-12 0:58 
1) You have made a good point.

The BLL and DAL must only pass or throw the error occured in the layers. So note that i have updated the article to use throw. So this means for every exception that are caught in the DataLayer , they will be thrown back to the Business Layer , and also the Business will pass the Error back to the PL. Now the Reason that i used

VB
throw ex


it is because if you use only throw statement you will loose the real exception on the way while throwing between layers, so to preserve it pass the object.

2)Yes i dont see anything wrong with that.
Vuyiswa Maseko,

Spoted in Daniweb-- Sorry to rant. I hate websites. They are just wierd. They don't behave like normal code.

C#/VB.NET/ASP.NET/SQL7/2000/2005/2008
http://www.vuyiswamaseko.com
vuyiswa[at]dotnetfunda.com
http://www.Dotnetfunda.com

GeneralMy vote of 5 Pin
aaroncampf31-Dec-10 19:29
aaroncampf31-Dec-10 19:29 
Questionquestion on n-tier application framework design Pin
BensonWong6-Nov-07 14:32
BensonWong6-Nov-07 14:32 
AnswerRe: question on n-tier application framework design Pin
Vimalsoft(Pty) Ltd6-Nov-07 20:23
professionalVimalsoft(Pty) Ltd6-Nov-07 20:23 
Generalperformance is not a reason for n-tier Pin
wk6335-Nov-07 18:06
wk6335-Nov-07 18:06 
GeneralRe: performance is not a reason for n-tier Pin
Vimalsoft(Pty) Ltd5-Nov-07 19:44
professionalVimalsoft(Pty) Ltd5-Nov-07 19:44 
GeneralRe: performance is not a reason for n-tier Pin
wk6336-Nov-07 4:26
wk6336-Nov-07 4:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.