Showing posts with label Multi tier. Show all posts
Showing posts with label Multi tier. Show all posts

Sunday, May 25, 2008

Multi tier Architecture utilities (NLOG)

see these Related topics:

  1. Multi tier basics
  2. A best practice for multi tier architecture
  3. A sample code based on best practice
  4. Examine utilities to speed up Multi tier programming- NLog

Please download the second version of Multi tier code

In previous lessons I talked about basic concepts of Multi tier and a best practice Architecture. Also I examine a sample code about that Architecture in this lesson I am going to review ”NLOG” one of the best tools that with no doubt you better use in that architecture to Log both errors and interaction with application.
What is NLOG?
NLOG is a free tool could be used to log into different resources like file, event viewer, database, Memory, Console, MSMQ, Mail and Web Service and etc. Meanwhile it can be configured to different level of log. Moreover, it can be switched off or on. Also you can have different source of log. Above of all it is open source application. Should you need any changes you will be able to make it.
How NLOG works?NLog gives you a class library to call its services. Also it has a configuration file called NLog.config where you set which log sources you need for instance file or database. Also you can configure the source for example for a file you probably configures the file name. You can have multiple sources. Take look at this sample:


this configuration file will be in UI application then other layers in Multi tier architecture do not need extra Nlog.config file all of them will use this configuration file. If you look at the logDirecotry in above code you will see that actually nlog will create a folder called Logs inside application folder and it will log data for each day. I just showed you logging in files. Log in other data sources like database has its own configuration variables.
It you look at the rules tag you will find two logger tags where you define each one of these logger
1- which class will represents them (“name”)
2- what is the minimum level of log also you can disable log by setting this value to debug for a release version of application (“minLevel”)
3- Which target this logger is using to log information

In a multi tier application we always put our logger in Common Layer because we need this library in other layers. Also I highly recommend you to write a rapper class to simplify using NLog. Take a look at the DataLogger code:



In above code simply two methods are written Info and Warn to log information. If you look at the parameters you see multiple parameters. To save these parameters an xml structure is being used.
Please see the next version of multi tier code with logging
I remind you that I used very simple logging here you may change it and adapt it to your requirements. So this is not a best practice however, it is a good practice using Nlog in your projects. Nlog is really a lot more than I show you here. If you need any extra information or you think it is worth to have more detail information about NLOG let me know and raise some comments here. Do not underestimate this fabulous tool. I believe it needs at least 20 posts to show its capability!
In next lesson I am going to talk about my favourite tool Code Smith to generate code. Please download the next version of the code.

Tuesday, May 20, 2008

Multi Tier Sample Code (Best Practice)

see these Related topics:

  1. Multi tier basics
  2. A best practice for multi tier architecture
  3. A sample code based on best practice
  4. Examine utilities to speed up Multi tier programming- NLog
In previous lessons I discussed about different layers and now I am going to Show you a sample code and discus what goes where.


We are going to create a web application to show different products and add products. See the database definition:


First open visual studio then create an empty solution afterwards add these projects to the Solution:

Common Layer (A class library)
In this layer we are going to define business entities and interfaces. Also sometimes we may define enumerations since it should be understandable for all other layers. We may want log information so having a logger class here could be useful serving all layers. The best tool for logging information and bugs is NLog (I will explain how to work with NLog in future posts). We also need a serviceFacotry class to create proper object of Facade layer. If you look at the architecture (previous lesson) you will see that UIProvider layer connect to facade layer but we may need to change this facade layer to a webservice so creating object from this layer should be configurable. One way is that a service factory can be used another way is using Spring. I will talk about Spring in future posts. Please look at the sample code.


Let's look at the code in ServiceFactory class:

using System;

using System.Collections.Generic;

using System.Text;

using MultiTier.Common.ServiceInterface;

using MultiTier.Common.BusinessEntities;

using System.Configuration;

using System.Reflection;

using System.Web;

namespace MultiTier.Common

{

public class ServiceFactory

{

private static Assembly asm;

public static IProductService GetProductService()

{

if (asm == null)

{

//Load Assembly

string AssemblyName = ConfigurationManager.AppSettings["Assembly"];

string asmPath = HttpContext.Current.Server.MapPath("~/bin/" + AssemblyName);

asm = Assembly.LoadFile(asmPath);

if (asm == null)

throw new Exception("Assembly could not be found: " + AssemblyName);

}

string className = ConfigurationManager.AppSettings["Product"];

IProductService obj = asm.CreateInstance(className) as IProductService;

if (obj == null)

throw new Exception("class could not be created: " + className);

return obj;

}

}

}

There are different ways of implementing ServiceFactory. This implementation is the simplest way but not the efficient way. I would say using spring is the best approach. Firstly a proper assembly is loaded then a new product object is created afterwards it is casted to the IProductService interface finally object is returned as IProductService. What you need to know is that we are using Reflection to load assembly and to create productService object. The address of assembly and the class name that we need to create object is configured in configuration file (in our case this configuration is web.config in UI project)

Data Access Layer (a class library)

The main purpose of this layer is to save and retrieve data from database. So there is a class named "ProductDal" gets data from database and map the data to the business entity. And send it back to BL layer. In ProductDal some stored procedures are called and a helper class is created to add parameter for each stored procedure. (Please download the source code)

Business Layer (a class library)

In This business layer we do not have any special business but let me give you an example if a user select bunch of products to buy then in this layer the price should be calculated. And then some code will be written here to withdraw his account.

Facade Layer (a class library)

The responsibility of this layer is that make it easier for UI to connect to this layer without understanding the complexity of backend. Let me give you an example. In this layer we may add some code to log accessing to data also we may check security etc. Please see the code.

UIProvider Layer (a class library)
What you need in UI may different in terms of object entities so you need add some modification or even create new objects to bind to UI elements. Moreover, you can test this layer so you know what is binding to UI. Best practice suggests that we should test this layer to sure about data which is going to be bind to UI. One of the best tools for testing is NUnit that I am going to talk about NUnit in next lessons.

UI(a web application)
Main purpose of this layer is showing information to user and getting information from user. In our case this layer is a web application. As you see I applied a css (some free template form dear Google search). There is a Master page and also two pages, one page to add Product and another to see list of products. In both pages I used object data bindings. Please get the code.
In next Lesson I am going to talk about NLog, Spring, NUnit and my favourite tool "code smith" to generate code automatically. I am sure you came up with the idea that this is really time consuming and you need something to speed up your implementation. Code smith helps you to generate code automatically and fast.

Important: After getting the code you need to change the connection string (It depends on where you put the sample code but if you look at the sample code there is a database that is in web.config you need to specify address of this file)


Thursday, May 15, 2008

Best Practice for Multi tier Applications Architecture

see these Related topics:

  1. Multi tier basics
  2. A best practice for multi tier architecture
  3. A sample code based on best practice
  4. Examine utilities to speed up Multi tier programming- NLog
There are many ways to implement multi tier applications. You can have different layers. Meanwhile, there are various ways to pass data between layers. First I am going to talk about one of the best practice to arrange your layers.


Look at this picture:

Common Layer
A key layer is Common layer if you look closely to picture you will see that all the layers are using this layer. So it has shared information like your data structure which can be business entities or your typed dataset. (Depend on which approach you choose to pass data. We will see more detail about passing data between layers)
User Interface
User Interface can be Web application or Windows Application. In this layer some classes represents UI. Like Windows forms or Web Forms.

User Provider
Then there is a layer called User Provider which is responsible to provide data the way UI needs. Sometimes objects or data you are retrieving from data base will not match User interface need. Let me give you an example in one of my projects I was asked to show a customize calendar indicating shift information in it. I had to retrieve data from different entities and change those objects to a month and each month had some weeks each week had 7 days each day had shift information data. Then I bounded those data to repeaters recursively (web application). Remember the best practice for this layer suggests that you may have all your methods as static methods.
interface
After UI layer you may want retrieve this data by different technologies like remoting or web services or directly. Let me give you an example again in one of my projects I was asked to implement a web application but the functionality should be implemented in a way that data could be loaded from a web service as well. So I had an interface then I configured this interface to load data from a dll which was my Facade layer. Then I told them all the functionalities are implemented in my facade layer all they need is that implementing a web service calling my facade layer and configuring the interface to connect to that web service. So when you configure interface then you can specify to which layer you need to connect. So sometimes you can make it web service or a dll or a remoting service. Spring is a library that you can use then you can take advantage of loosely coupled feature. I will get back to spring later on. Or you can use abstract factory pattern. So this layer which is an interface is very critical and makes your application so maintainable.
Facade Layer
Facade Layer is a place that you can connect from UI so main purpose of this layer is that somehow separate your User Interface form backend and business layers. Also in this layer we may check security and do some logging. Every class here better just connect to business layer however, some people believe that connecting to data access through this layer is fine. Nevertheless, I should say if you accept just one function call then you better just connect to business layer so you have more flexibility later on.
Business layer
Business layer helps you to apply all your business rules. Also since all request passing from this layer , you can apply business to your classes in later steps.
Data Access
Data Access Layer is the place where you save and retrieve data from data base.

Passing data through layers

There are different ways:
1- Using Xml Structure
2- Using untyped data set
3- Using Typed data set
4- Using Business entities
5- Using simple parameters
I should say a lot of these ways has its own advantages and disadvantages. The best way to do that is using Business entities which give you more flexibility and you can apply design patterns approach on them. Like proxy patterns. Also it is now fully supported by .net.

In next lesson I am going to discuss a code also I am going to talk about some helper tools to facilitate your layers like: Code smith, NLog and Spring. Also I will discuss object data binding in .net especially in web applications. See Next Lesson for sample code

Sunday, May 11, 2008

Multi tier programming –Part1

see these Related topics:

  1. Multi tier basics
  2. A best practice for multi tier architecture
  3. A sample code based on best practice
  4. Examine utilities to speed up Multi tier programming- NLog
First of all having a good understanding of multi tier programming is really important. Then we need to look into how we can implement it. What is a good practice especially for web applications? Unfortunately Multi tier programming needs massive time in terms of implementation so how we can utilize speeding at the same time write our code in this architecture?

Let’s start with what is multi tier programming?
Multi tier programming suggests that instead of writing code in just UI we need to separate our applications code to various layers. What does layer mean? Each layer provide some classes that having a unique purpose like one layer is just to check your business rule or do complex calculation to satisfy your business. Another layer can have responsibility for saving and retrieving data. Be careful we do not suggesting that these layers should be in different computers all we suggest is that we need to separate our application code to different layers logically. Let’s understand this concept in one example:

We need to save and show information of some customers. Customers’ data exists in an Access database. We are asked to create a web application to show these data. So we create two pages one page to save new customer information another for showing all customer data. To implement each page usually we write some code in code behind of that page to save or retrieve data then we bind to database. This is wrong! I know that some of us have been doing this for years and everything was fine but I will convince you that is absolutely wrong. We get back to this issue that why this is wrong. Multi tier programming suggests that we can have one class to save and retrieve from data base (which can be our data access) another class to work with previous class and apply possible business rules and finally in UI to save and load information, object of business class should be created. It seems the code that could be very simple is more complicated. Yeah this is true it is a little bit more complicated however, it is definitely worth it. Why?

Reasons of using multi tier programming:

It helps you to separate each layer purpose so finding a code will be much easier. You can replace each layer let’s say in last example what if you need to change your database to SQL server then you need just replace data access layer.
In next part of multi tier programming you will see a good practice that can be used with full sample code.