Monday, March 1, 2010

Multi Layers Application Development

=============================================
How to develop Multi layer Application
=============================================

Below example to create five layers of application

1.Data Access Object Layer
2.Business Component Layer
3.WCF Service Layer
4.Business Data Transaction Object Layer
5.UI Layer


---------------------------------------------------------------
Using Technologies : c#, Enterprise Library, SP's in sql server
---------------------------------------------------------------

Database connection string
--------------------------
1.Server or Data Source
2.Initial Catalog or Database
3.Userid
4.Password
5.ProviderName = "System.Data.SqlClient"

Example :-
connectionString="Data Source=--;Initial Catalog=--;User ID=--;Password=--" providerName="System.Data.SqlClient"


In Web.Config
-------------

< connectionStrings >
< add name="conName" connectionString="Data Source=--;Initial Catalog=--;User ID=--;Password=--" providerName="System.Data.SqlClient"/ >
< /connectionStrings >
< appSettings/ >


1. Create Dao project with class (Data Access Layer)
====================================================
using System;
using System.Text;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using System.ComponentModel;
using PjtDac.DACHelper;
using PjtDacBDto.1;

// Get List method

public BindingList< BDto1 > GetList(Int32 UnicId)
{

IDataReader dRead1 = null;
Database db = null;
DbCommand dbcmd1 = null;

BindingList< BDto1 > objBdto1List = new BindingList< BDto1 > ();
db = DatabaseFactory.CreateDatabase("conName");
dbcmd1 = db.GetStoredProcCommand("StoredProcedureName");
dRead1 = db.ExecuteReader(dbcmd1);
while (dRead1.Read())
{

BDto1 obj1BDto = new BDto1();
if (dRead1["UserId"] != DBNull.Value)
obj1BDto.UserId= Convert.ToInt32(dRead1["UserId"]);
if (dRead1["Name"] != DBNull.Value)
obj1BDto.Name = dRead1["Name"].ToString();
objBdto1List.Add(obj1BDto);
}
return objBdto1List

}


// Insert or Update method

public BindingList< BDto1 > InsertMethod(BDto1 obj1BDto)
{

IDataReader dRead1 = null;
Database db = null;
DbCommand dbcmd1 = null;

BindingList< BDto1 > objBdto1List = new BindingList< BDto1 > ();
db = DatabaseFactory.CreateDatabase("conName");
dbcmd1 = db.GetStoredProcCommand("StoredProcedureName");

db.AddInParameter(dbcmd1, "@Id", DbType.Int32, obj1BDto.Id);
db.AddInParameter(dbcmd1, "@Name", DbType.String, obj1BDto.Name);
db.AddOutParameter(dbcmd1, "@isExists", DbType.Int32, Int32.MaxValue);
db.ExecuteNonQuery(dbcmd1);

if (db.GetParameterValue(dbcmd1, "@isExists") != DBNull.Value)
isExists = Convert.ToInt32(db.GetParameterValue(dbcmd1, "@isExists"));
if (isExists == 0)
return true; // SUCCESSFUL INSERTION RETURN TRUE
else
return false; // UNSUCCESSFUL INSERTION RETUN FALSE ( ALREADY EXISTS )
}



// Delete method


public Int32 DeleteMethod(BDto1 obj1BDto)
{
Database db = null;
DbCommand dbcmd1 = null;
int objerror = 0;

db = DatabaseFactory.CreateDatabase("conName");

dbcmd1 = db.GetStoredProcCommand("StoredProcedureName");

db.AddInParameter(dbcmd1, "@Id", DbType.Int32, obj1BDto.Id);
db.AddOutParameter(dbcmd1, "@errorCode", DbType.Int32, 4);
db.ExecuteNonQuery(dbcmd1);
if (db.GetParameterValue(dbcmd1, "@errorCode") != DBNull.Value)
objerror = Convert.ToInt32(db.GetParameterValue(dbcmd1, "@errorCode"));
return objerror;

}




// Idisposiable

public class ClsDao : IDisposable
{
public void Dispose()
{
GC.Collect();
}

}




// Exception Handling
=====================

try
{
---------
---------
}
catch(Exception ex)
{
bool rethrow = ExceptionPolicy.HandleException(ex,"DataAccess Layer Exception Policy")
if (rethrow)
{
throw ex;
}
}

finally
{
Destroy(ref dbcmdSubject);
}




// Method to call in the Finally block
---------------------------------------

public static void Destroy(ref DbCommand dbCmd)
{
if (dbCmd != null)
{
if (dbCmd.Connection.State == ConnectionState.Open)
{
dbCmd.Connection.Close();
}
}

dbCmd = null;
}




StoredProcedudres
==================

// 1. Insert or Update

Create Procedure spInsertUpdate
(
@ id tinyint,
@ Name nvarchar(50)
@isExist int=0 output
)
AS
BEGIN

if exists(select id from tblUser where id=@id Name=@Name)
BEGIN
Set @IsExists = 1
return
END

if NOT EXISTS(select id from tbluser where id=@id OR Name=@Name)
BEGIN
Insert into tbluser (name) values (@Name)
END
ELSE IF NOT EXISTS(select id from tbluser where id< > @id and Name=@Name)
BEGIN
update tbluser set Name=@Name where id=@id
END
ELSE
BEGIN
SET @IsExists =1
return
END
END



// Get list Stored procedure

CREATE PROCEDURE SpGetList
AS
BEGIN
select Id,LTRIM(RTRIM(Name)As Name from tbluser
END


// Delete storedprocedure

create procedure SpDelete
(
@id tinyint,
@errorCode int=0 output
)
as
begin try
delete from tbluser where id in (select [value] from dbo.udf_SplitBy(@id,','))
end try

begin catch
select @errorCode = ERROR_NUMBER()
end catch
return @errorCode

// if error than it returns = 547




2. Create BC project with class (Business Component Layer)
==========================================================
using System;
using System.Text;
using System.Data;
using System.ComponentModel;
using PjtDao;
using PjtBc;
using PjtBDto;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;


public class clsBC : IDisposable
{

// Get list method

public BindingList< BDto1 > GetList(Int32 Unicid)
{
using(Dao1 objDao1=new Dao1())
{
return objDao1.GetList(Unicid);
}
return null;
}


// Insert or Update method
public bool InsertUpdate(BDto1 objBDto)
{
using(Dao1 objDao1=new Dao1())
{
return objDao1.InsertUpdate(objBDto)
}
return false;
}

// Delete method

public Int32 Del1(BDto1 objBDto1)
{
int objreturn = 0;
using (dao1 objdao1 = new dao1())
{
objreturn = objdao1.Del(objBDto1);
}
return objreturn;
}


// Idisposiable
public void Dispose()
{
GC.Collect();
}



}


3. WCF Service Layer
=====================
// Interface

using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using PjtBDto1;
using System.ComponentModel;

[ServiceContract]
public interface Iuser
{

[OperationContract]
[FaultContract(typeof(ExceptionClass))]
BindingList< BDto1 > GettList(Int32 unicId);

[OperationContract]
[FaultContract(typeof(ExceptionClass))]
bool InsertUpdate(BDto1 obj1BDto);

[OperationContract]
[FaultContract(typeof(ExceptionClass))]
BindingList< BDto1 > GettList(Int32 unicId);

[OperationContract]
[FaultContract(typeof(ExceptionClass))]
Int32 Del1(BDto1 obj1BDto);

}

//ExceptionFields is an enum containing two members
//“ERROR” and “INCORRECT_OPERATION”.
[DataContract]
public class ExceptionClass
{
[DataMember]
public ExceptionFields errorcode;
[DataMember]
public string message;
[DataMember]
public string details;
}
// Used for holding exception fields
public enum ExceptionFields
{
[EnumMember]
ERROR,
[EnumMember]
INCORRECT_OPERATION
}



// Service class


using System;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data;
using System.Collections.Generic;
using System.ComponentModel;
using PjtDao;
using PjtBc;
using PjtBDto;

public class Service1 : IService1
{
public BindingList< BDto1 > GetList(Int32 UnicId)
{
using(BC1 ObjBc1=new BC1)
{
return objBc1.GetList(UnicId);
}
return null;
}


}


// Exception Handling in WCF Service Layer
try

{

}

catch(Exception ex)
{
ExceptionClass error=new ExceptionClass();
error.errorcode = ExceptionFields.ERROR;
error.message = "General Exception"
error.details = ex.StackTrace;
throw new FaultException< ExceptionClass > (error);

}

// Service Exceptions in class of Catch block

ActionNotSupportedException
AddressAccessDeniedException
AddressAlreadyInUseException
ChannelTerminatedException
CommunicaitonException
Exception

// Handling same in all catch block
--------
ExceptionClass error=new ExceptionClass();
error.errorcode = ExceptionFields.ERROR;
error.message = "General Exception"
error.details = ex.StackTrace;
throw new FaultException< ExceptionClass > (error);






4. Create BDto Project with class (Business Data Transaction Layer)
====================================================================


-------------------
How to create BDto
-------------------

// Create BTto to decleare properties.
// also we can write Individual like for Contants,Address etc in different class

using System;

[Serializable]
public class BDto1
{


private String m_firstName = String.Empty;
private String m_middleName = String.Empty;
private String m_lastName = String.Empty;
private String m_fullName = String.Empty;


#region FirstName

public String FirstName
{
get
{
return m_firstName;
}
set
{
m_firstName = value;
}
}
#endregion

#region MiddleName

public String MiddleName
{
get
{
return m_middleName;
}
set
{
m_middleName = value;
}
}
#endregion

#region LastName
public String LastName
{
get
{
return m_lastName;
}
set
{
m_lastName = value;
}
}
#endregion

#region FullName
public String FullName
{
get
{
return m_fullName;
}
set
{
m_fullName = value;
}
}
#endregion



}




5. Create UI Project with class (User interface layer)
======================================================

using System;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using System.Web.UI;
using System.ServiceModel;
using PjtBDto.BDto1;
using PjtService1;
using System.web;



// Get List in Teleric DataGrid binding


public void Bind_DataGrid()
{

dg1.DataSource = null;
dg1.DataBind();

// Calling service to Grid Popup operation
int UnicId = 1;
service1.ServiceClient objSerice1=new service1.ServiceClient();
System.ComponentModel.BindingList< BDto1 > objBL = new System.ComponentModel.BindingList< BDto1 >
objBL = objService1.GetList(UnicId);
objService1.close();

if(objBL != null)
{
dg1.DataService =objBL;
ViewState["v1"] = objBL;
dg1.DataBind();

}

}



// Get List in Teleric radCombo (DropdownList) binding

public void radCOMBO1Popup()
{
int UnicId = 1;
service1.ServiceClient objSerice1=new service1.ServiceClient();
System.ComponentModel.BindingList< BDto1 > objBL = new System.ComponentModel.BindingList< BDto1 >
objBL = objService1.GetList(UnicId);
objService1.Close();
ViewState["V2"] = objBL;
radCombo1.DataSource = objBL;
radCombo1.DataTextField = "Name";
radCombo1.DataValueField = "id";
radCombo1.DataBind();
radCombo1.Item.Insert(0,new RadCOmboBoxItem("-Select-"));
}

No comments:

Post a Comment