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)


Saturday, May 17, 2008

.Net Remoting Sample

DownLoad The Source Code

See Clip

Remoting is a technology that helps you to communicate between different applications regardless of whether they reside on the same computer or on different computers. Even these applications can have different operation systems.

Remoting needs:

1. A server object that expose the functionality to callers outside its boundary

2. A client that makes calls to the server object

3. A transportation mechanism to pass the calls from one end to the other

.Net Remoting system provides a number of services:

1. to activate objects

2. control the lifetime of each object

3. Transport message to and from remote objects using communication channels from client application to server application.

All objects in .Net divide to 2 groups

1. Remotable objects

2. NonRemotable objects

Remotable Objects:

There are two types of Remotable objects:

1. Marshal by Value objects: when these objects are created actually a copy of these objects will be send to client so actually object is sent to client. In .Net if you have a class that is serializable then it is marshal by value. To make a class serializable you should just add an attribute to the class [Serializable].

2. Marshal by Reference objects: When these objects are created they are actually stay in Server and client will connect to these objects. So a reference to server object exists in the client. In fact client application has another object which is called proxy. Proxy object is like server object. However, when proxy method is called it will pass that request to server object. Still client assumes that it is working with real object. In .Net classes that are inherited from MarshalByRefObject are in this category.

Other objects apart from these two categories are NonRemotable.

In .net Remoting marshal value objects are simple one because they are in context of client. Sometimes you cannot send copy of object to client and you need client call server object like applying business rule. Generally data objects (like dataset or business entities) have to be marshal by value and business objects have to be marshal by reference.

In .net Remoting Marshal by reference objects are more complicated since these objects are created in server. There are some concerns about them for instance When objects are created in server, When objects will be deleted, how long objects can leave in server so on so forth.

So let's have a look to marshal by reference concept and see different types of marshal by ref objects.

Activation

Before an object instance of a remotable type can be access it must be created and initialized by a process known as activation.

Different types of marshal by ref objects:

1- Server activation (in .net Remoting code it is called Wellknown)

2- Client activation (in .net Remoting code it is called Activated)

There are two types of server activation

1- Singleton: it means that there is just one object in server serving all clients and all requests. (if you understand web applications this kind of objects are like Application object in web)

2- SingleCall :it means that for each call from each client an object will be created and afterwards that object will be deleted immediately. (it is like webforms in web)

Client activation: for each instance of client and each instance that client create from server object there is a separate object in server (like session in web)

What is passed in Remoting between server and client?

1- URI : When Remoting activate an object give that object a URI to reference for all requests. For server activated the URI is in server application. On the other hand, for client activated Remoting will generate a GUID for the URI and maps it to remote object. So for client activation it is handled by Remoting.

2- Metadata: Remoting has to pass type information (it means it has to pass type of class)

3- Channel Information: Remoting needs to know from which channel can access the object.

Basics for coding .net Remoting

In .Net Remoting we have different types of channels (I will get back to this concept in next lessons) as you know in .Net Remoting we need a server application and a client application and a channel we usually register channel in server. There is a class named Remotingconfiguration that we use to register objects. This class has 4 type of Register

1-RegisterActivatedClientType

2-RegisterActivatedServiceType

3-RegisterWellKnownClientType

4-RegisterWellKnownServiceType

In these methods Activated means client activation and WellKnown means server activation and Service implies you are registering in server and Client implies you are registering in Client application

Time to Write Remoting code (Download the source Code)

Please follow these steps to write a Remoting code:

1- Create a class library name it Service : in class library you just have a class named Test

namespace Service

{

public class Test:MarshalByRefObject

{

public Test()

{

Console.WriteLine("New Object!");

}

public string PrintYourAddress()

{

string myaddress = AppDomain.CurrentDomain.BaseDirectory;

Console.WriteLine("This is myaddress " + myaddress);

return myaddress;

}

public void WriteInServer()

{

Console.WriteLine("I wrote time in server " + DateTime.Now.ToShortTimeString());

}

}

}

2- Create a console application name it Server: you have to write some code in Main method. You need to add System.Runtime.Remoting to your references. Furthermore you need to add Service library to this project.

using System;

using System.Collections.Generic;

using System.Text;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Http;

namespace Server

{

class Program

{

static void Main(string[] args)

{

HttpChannel ch = new HttpChannel(4000);

ChannelServices.RegisterChannel(ch);

//because this is written in server so we need to use Service type methods

RemotingConfiguration.RegisterWellKnownServiceType(typeof(Service.Test), "ServiceURI", WellKnownObjectMode.Singleton);

Console.WriteLine("Server is Started...");

Console.ReadLine();

}

}

}

3- Create a windows application name it Client: First of all you need to add reference service. Add two buttons and in button clicks add these code also you need to add some code in FormLoad event

Test t;

private void Form1_Load(object sender, EventArgs e)

{

System.Runtime.Remoting.RemotingConfiguration.RegisterWellKnownClientType(typeof(Test), "http://localhost:4000/ServiceURI");

t= new Test();

}

private void button1_Click(object sender, EventArgs e)

{

t.WriteInServer();

}

private void button2_Click(object sender, EventArgs e)

{

string str = t.PrintYourAddress();

MessageBox.Show(str);

}

4- First run client application if you click on any of buttons you should see an error because the server is not running. So you need run server then client that should be fine for more detail information please see the movie

See Clip

Learn more about .Net Remoting (Activator sample)