.Net Implementation of three- tier application.
Posted On August 26, 2008 by Madhu AP filed under
While teaching software engineering ,I realized that multi-tier architecture is the best example to illustrate the concept of ‘coupling and cohesion ‘ .As we know that for a good software design, the coupling between the modules should be minimum .In other words, the modules should be independent as much as possible and hence the degree of interaction(coupling) among the modules should be less. Similarly, for a better design, the cohesion within a module should be maximum. More tightly the functions within a module are glued, more cohesive the module is. Both Coupling and cohesion are complimentary to each other. In this article, I will discuss the implementation of 3-tier architecture of a very small business application, which incorporates the concept of modularity i.e. ‘Coupling and cohesion’. The 3-architecture, or in general, the n-tier architecture has inherent feature of modularity as all the layers (tiers) in the architecture encapsulate unique kind of task. In 3-tier architecture the system is composed of three layers. The bottom layer is abstracted as data layer. The middle layer is business layer and the top layer is presentation layer. The data-layer encapsulates all the methods and functions to interact with your data source, such as Oracle, Sqlserver, MS Access, etc. In our example, we will assume MS Access as the data source. The business layer consists of all the function and methods to implement business logic of the application, such as entry of product information, stock verification, updation of product information, etc. The presentation layer consists of GUI/UI to present and receive the data from the external agent, such as textbox, combobox, datagrid, etc. See table1.

Here, I have selected .Net as an implantation language for 3 – tier application for two reasons .First, it provides us the primitives to build the application at all the levels of n-tier architecture. Second, it has natural feature to support reusability by means of code interoperability. By exploiting the feature of ‘managed code ‘in .Net we can build the component in c# (that is what, I am actually going to do.) and use it in Visual Basic Application.
In our example, we will design a webpage in VB.net, which will consist of four textboxes to enter the data for ProductiId, ProductName, ProductQuantity and ProductPrice respectively. We will also add one label, which displays the information about the supplier like SuplierId, SuplierName and SupplierCountry of the given product. The Supplier’s information is read-only therefore it will be displayed in label.
In order to build a complete reusable component for our purpose ,we will include all the three required classes – ClsMydbase.cs for handling data source(data layer) ,clsProduct.cs for handling business logic of product (business layer ) and clsSuplier.cs for handling business logic of supplier(Business layer) in the same namespace which I, for myself have named it as –InventryMgmt.To create your own namespace, select class library in visual studio c# project, type the name of library as InventoryMgmt or any other name of your choice for the namespace.
Once you created the namespace, you will see a default class class1 within the brace of namespace InventryMgmt .Change the name of the class to clsMydbase or you name it what so ever you think relevant. Write the following code for this class as shown in table2.
| .................................................................................................................................................... using System; using System.Data.OleDb; using System.Configuration; namespace InventoryMgmt { public class ClsMydbase { public static string dbpath { get { return ConfigurationSettings.AppSettings["DbConPath"]; } public static OleDbDataReader GetReader(String Prd_StrQuery) OleDbConnection Connection = new OleDbConnection(dbpath); Connection.Open(); public static int ExecuteNonQuery(string Prd_StrQuery,OleDbParameter[] Params) { int intResult; for(int i = 0 ; (i<=(Params.Length - 1)); i++) Connection.Open(); |
Table2.
The class ClsMydbase.cs is detail of data layer which consists of one property named dbpath and two methods -named GetReader(…) and ExecuteNonQuery(…,…) respectively. Please note that all the properties and methods are static by nature and there fore to use them, you need not instantiate ClsMydbase. The property dbpath is read-only and returns the value of the key named DbConPath, which is defined within the tag of appSettings in your web.config file of your asp.net project.The value of dbpath is the path of your datasource .In my case I have defined the value of dbpath in the web.config file of my asp.net project –webmultitier as shown in Table: 5. In order to access the appSettings in web.config of the asp.net project, system.configuration namespace has been imported.
The method getreader(…) receives the query as string and returns the data reader through which various fields of query- result can be accessed. We will see its use in the presentation layer. The method ExecuteNonQuery(…,…) receives two parameters ;one is query of string type and other is array of OleDbParameter which is added as the parameters to the oledcommand .This method return the value of type integer which represents the number of rows of database table that have been affected after the execution of the method. In order to implement these two methods, a namespace system.data.oledb has been imported as it defines various classes, such as oledbconnection, oledbcommand, oledbreader and oledbparameter, which are used by the methods of this class. These two methods of data layer are used by objects residing in business layer. Or, you can say that through these two functions business layer and data layer communicates with each other.
This is all about your data layer.
Now, write the code for the business layer. Add the class named clsMyproduct.cs to your existing Inventorymgmt component. All the business logic related to the product will be coded into this class which is as follows. See Table3.
| using System; public class ClsMyProduct public int ProdId public string ProdName set public Double ProdPrice set public int ProdQuant set public ClsMySuplier supplier public ClsMyProduct(int ArgPrdId ) OleDbDataReader dtrProduct ; if(dtrProduct.Read()) } _blnChanged = false; } public int edit() strEdit = "UPDATE TblProduct SET ProductName= @ProdName, Quantity = @Quan WHERE ProductId= @ProduId"; OleDbParameter[] Params ; } } } } |
Table3.
In the above code ,first- we have implemented the properties of the clsMyproduct out of which productid is readonly.The other properties of the clsMyproduct can be updated also .As soon as we modify them the Boolean variable( _blnChanged) is set to true to signify that product properties have been changed. We have also declared here, the clsMysupplier as the member field of the clsMyproduct.Declaring one class within another class is one way to establish association between two classes. Also note that we can merely get the associated supplier object here, but we can’t set its properties.
Second, we have implemented the constructor of the clsMyproduct through which specific object of this class could be instansiated.You see here that object is created virgin as its _blnchanged property is false when it creates which is made true when any of its properties ,except its id which cant be changed, is modified.
Third, we have equipped the clsMyproduct with a service named ‘edit’, through which you can update the properties of the object of this class.
This is all about your business logic of clsMyproduct class. If your clsMyproduct class is more complex and provides number of more other services , you can add number of other methods into the class.
Now , write the coding for businees logic of clsMysupplier.cs class as shown in Table4.
| .................................................................................................................................................................. using System; using System.Data.OleDb; namespace InventoryMgmt { public class ClsMySuplier { private int _intSupId ; private string _strSupName; private string _strSupCountry; public int SuplierId { get { return _intSupId; } } public string SuplierName public String SuplierCountry OleDbDataReader dtrSuplier = ClsMydbase.GetReader("select * from tblsuplier where SuplierId =" + ArgSupId); if(dtrSuplier.Read()) { _intSupId = ArgSupId; _strSupName = Convert.ToString ( dtrSuplier["Name"]); _strSupCountry =Convert.ToString (dtrSuplier["Country"]); } dtrSuplier.Close(); } } } |
Table4.
In the code, we can retrieve three properties of supplier –SupplierId, SupplierName and Suppliercountry.We are not provisioned to modify any of them.The code also implements the constructor of clsMysupplier of specific Supplierid.This is enough for our ClsMySuplier.cs as per the business requirement.
And, this is all about your InventoryMgmt component. As you can see that component here implement data layer and business layer of the 3-tier architecture of the application.
You are required to compile this component; this makes the dll of this component. Now, I will use this component into my VB.Net web application.
Now, open new project and select visual basic asp.net web application .Do not forget to add appsettings tag to your web.config file of your asp.net project like this. See Table5.
| <appSettings> <add key="DbConPath" value="Provider=Microsoft.Jet.OLEDB.4.0;data source=F:\salesmgmt\salesrecord.mdb" /> </appSettings> |
Table5.
Within appsettings tag, I have added a key named DbConPath, which you can trace in dbpath property of class – clsMydatabase.cs.The value of the key is a string which stores the type of data provider and the path where your MS Access database named, as in my case it is - salesrecord.mdb, is stored.
You are also required to add reference to this created InventoryMgmt.dll by right clicking at the solution explorer of your ASP.Net project, selecting add reference to browse your InventoryMgmt.dll.Now you need to import this InventoryMgmt namespace to use the classes packaged within this namespace.
Now ,in webform, drag and drop four textboxes namely –TxtProdid,TxtPrdName, TxtPrdPrice and TxtPrdQunt.Drop one label named LblSupName.Also drop two command buttons named BtnLoad and BtnUpdate.The BtnLoad command button loads the information about the product whose id has been entered in TxtPrdId.The code for BtnLoad is as follows which is very simple. See Table6.
| Private Sub BtnLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnLoad.Click Dim ObjProduct As New ClsMyProduct(Val(TxtPrdId.Text)) TxtPrdName.Text = ObjProduct.ProdName |
Table6.
As you can see the above code which is the manifestation of presentation layer is interacting with the business layer of the application.The code simply loads the information of product of entered id .You can also update the information of the product.To accomplice this write the following code to update the product. See Table7.
| Private Sub BtnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnUpdate.Click Dim updated As Integer |
Table7.
Again you can see in the above code that the presentation layer is making use of services provided by the business layer to update the product. In the code, we have simply invoked the service –edit () of product object to accomplish modification on the product.
Conclusion:
In my article, I have shown that how application can be split into three different layers-data layer, business layer and presentation layer. You can further split any of these layers into sub layers if the complexity of the given layer is intuitively high. The main objective of the layered architecture is to achieve lesser coupling and higher cohesion .If we obsess the modularity, which I think we must, we can deliver well proven quality product on time. This is the path which will lead us to the factory where software is assembled not always developed from scratch.

Siddhartha Suripunj.
(Project Coordinator)
NICE Society, Meerut
An Alumnus of Motilal Nehru Regional Engineering College ,Allahabad.Passed out as MCA in 1999.Over six years of experience in teaching and training of software engineering’s application on various Microsoft technologies which includes VB ,COM,DCOM and .Net. He is Currently working as a Project coordinator in the same organisatation and can be reached on s_suripunj@rediffmail.com
