熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

教你在c#中實現3層架構

2022-06-13   來源: .NET編程 

  這篇文章討論如何在c#中實現層架構使用MS Access數據庫存儲數據在此我在層架構中實現一個小型的可復用的組件保存客戶數據並提供添加更新查找客戶數據的功能

  背景

  首先我介紹一些層架構的理論知識簡單說明什麼是層架構?層架構的優點是什麼?

  什麼是層架構?

  層架構是一種客戶端-服務器架構在此架構中用戶接口商業邏輯數據保存以及數據訪問被設計為獨立的模塊主要有個層面第一層(表現層GUI層)第二層(商業對象商業邏輯層)第三層(數據訪問層)這些層可以單獨開發單獨測試

  為什麼要把程序代碼分為把用戶接口層商業邏輯層數據訪問層分離有許多的優點

  在快速開發中重用商業邏輯組件我們已經在系統中實現添加更新刪除查找客戶數據的組件這個組件已經開發並且測試通過我們可以在其他要保存客戶數據的項目中使用這個組件

  系統比較容易遷移商業邏輯層與數據訪問層是分離的修改數據訪問層不會影響到商業邏輯層系統如果從用SQL Server存儲數據遷移到用Oracle存儲數據並不需要修改商業邏輯層組件和GUI組件

  系統容易修改假如在商業層有一個小小的修改我們不需要在用戶的機器上重裝整個系統我們只需要更新商業邏輯組件就可以了

  應用程序開發人員可以並行獨立的開發單獨的層

  代碼

  這個組件有第一個層或者稱為GUI層用form實現叫做FrmGUI第二層或者稱為商業邏輯層叫做BOCustomer是Bussniess Object Customer的縮寫最後是第三層或者稱為數據層叫做DACustomer是Data Access Customer的縮寫為了方便我把三個層編譯到一個項目中

  用戶接口層

  下面是用戶接口成的一段代碼我只選取了調用商業邏輯層的一部分代碼

    //This function get the details from the user via GUI

  //tier and calls the Add method of business logic layer

  private void cmdAdd_Click(object sender SystemEventArgs e)

  {

  try

  {

  cus = new BOCustomer();

  cuscusID=txtIDTextToString();

  cusLName = txtLNameTextToString();

  cusFName = txtFNameTextToString();

  cusTel= txtTelTextToString();

  cusAddress = txtAddressTextToString();

  cusAdd();

  }

  catch(Exception err)

  {

  MessageBoxShow(errMessageToString());

  }

  }

  //This function gets the ID from the user and finds the

  //customer details and return the details in the form of

  //a dataset via busniss object layer Then it loops through

  //the content of the dataset and fills the controls

  private void cmdFind_Click(object sender SystemEventArgs e)

  {

  try

  {

  String cusID = txtIDTextToString();

  BOCustomer thisCus = new BOCustomer();

  DataSet ds = thisCusFind(cusID);

  DataRow row;

  row = dsTables[]Rows[];

  //via looping

  foreach(DataRow rows in dsTables[]Rows )

  {

  txtFNameText = rows[CUS_F_NAME]ToString();

  txtLNameText = rows[CUS_L_NAME]ToString();

  txtAddressText = rows[CUS_ADDRESS]ToString();

  txtTelText = rows[CUS_TEL]ToString();

  }

  }

  catch (Exception err)

  {

  MessageBoxShow(errMessageToString());

  }

  }

  //this function used to update the customer details

  private void cmdUpdate_Click(object sender SystemEventArgs e)

  {

  try

  {

  cus = new BOCustomer();

  cuscusID=txtIDTextToString();

  cusLName = txtLNameTextToString();

  cusFName = txtFNameTextToString();

  cusTel= txtTelTextToString();

  cusAddress = txtAddressTextToString();

  cusUpdate();

  }

  catch(Exception err)

  {

  MessageBoxShow(errMessageToString());

  }

  }


 商業邏輯層

  下面是商業邏輯層的所有代碼主要包括定義customer對象的屬性但這僅僅是個虛構的customer對象如果需要可以加入其他的屬性商業邏輯層還包括添加更新查找等方法

  商業邏輯層是一個中間層處於GUI層和數據訪問層中間他有一個指向數據訪問層的引用cusData = new DACustomer()而且還引用了SystemData名字空間商業邏輯層使用DataSet返回數據給GUI層

  using System;

  using SystemData;

  namespace _tierarchitecture

  {

  /// <SUMMARY>

  /// Summary description for BOCustomer

  /// </SUMMARY>

  public class BOCustomer

  {

  //Customer properties

  private String fName;

  private String lName;

  private String cusId;

  private String address;

  private String tel;

  private DACustomer cusData;

  public BOCustomer()

  {

  //An instance of the Data access layer!

  cusData = new DACustomer();

  }

  /// <SUMMARY>

  /// Property FirstName (String)

  /// </SUMMARY>

  public String FName

  {

  get

  {

  return thisfName;

  }

  set

  {

  try

  {

  thisfName = value;

  if (thisfName == )

  {

  throw new Exception(

  Please provide first name );

  }

  }

  catch(Exception e)

  {

  throw new Exception(eMessageToString());

  }

  }

  }

  /// <SUMMARY>

  /// Property LastName (String)

  /// </SUMMARY>

  public String LName

  {

  get

  {

  return thislName;

  }

  set

  {

  //could be more checkings here eg revmove chars

  //change to proper case

  //blah blah

  thislName = value;

  if (thisLName == )

  {

  throw new Exception(Please provide name );

  }

  }

  }

  /// <SUMMARY>

  /// Property Customer ID (String)

  /// </SUMMARY>

  public String cusID

  {

  get

  {

  return thiscusId;

  }

  set

  {

  thiscusId = value;

  if (thiscusID == )

  {

  throw new Exception(Please provide ID );

  }

  }

  }

  /// <SUMMARY>

  /// Property Address (String)

  /// </SUMMARY>

  public String Address

  {

  get

  {

  return thisaddress;

  }

  set

  {

  thisaddress = value;

  if (thisAddress == )

  {

  throw new Exception(Please provide address );

  }

  }

  }

  /// <SUMMARY>

  /// Property Telephone (String)

  /// </SUMMARY>

  public String Tel

  {

  get

  {

  return thistel;

  }

  set

  {

  thistel = value;

  if (thisTel == )

  {

  throw new Exception(Please provide Tel );

  }

  }

  }

  /// <SUMMARY>

  /// Function Add new customer Calls

  /// the function in Data layer

  /// </SUMMARY>

  public void Add()

  {

  cusDataAdd(this);

  }

  /// <SUMMARY>

  /// Function Update customer details

  /// Calls the function in Data layer

  /// </SUMMARY>

  public void Update()

  {

  cusDataUpdate(this);

  }

  /// <SUMMARY>

  /// Function Find customer Calls the

  /// function in Data layer

  /// It returns the details of the customer using

  /// customer ID via a Dataset to GUI tier

  /// </SUMMARY>

  public DataSet Find(String str)

  {

  if (str == )

  throw new Exception(Please provide ID to search);

  DataSet data = null;

  data = cusDataFind(str);

  return data;

  }

  }

  }


   數據訪問層

  數據層包括處理MS Access數據庫的細節所有這些細節都是透明的不會影響到商業邏輯層數據訪問層有個指向商業邏輯層的引用BOCustomer cus為了應用方便並且支持其他數據庫

  using System;

  using SystemDataOleDb;

  using SystemData;

  namespace _tierarchitecture

  {

  /// <SUMMARY>

  /// Summary description for DACustomer

  /// </SUMMARY>

  public class DACustomer

  {

  private OleDbConnection cnn;

  //change connection string as per the

  //folder you unzip the files

  private const string CnnStr =

  Provider=MicrosoftJetOLEDB;Data +

  Source= D:\\Rahman_Backup\\Programming\\ +

  Csharp\\tierarchitecture\\customermdb;;

  //local variables

  private String strTable=;

  private String strFields=;

  private String strValues=;

  private String insertStr=;

  //this needs to be changed based on customer

  //table fields Name of the database!

  private const String thisTable = tblCustomer;

  private const String cus_ID = CUS_ID;

  private const String cus_LName = CUS_L_NAME;

  private const String cus_FName = CUS_F_NAME;

  private const String cus_Tel = CUS_TEL;

  private const String cus_Address = CUS_ADDRESS;

  public DACustomer()

  {

  }

  public DACustomer(BOCustomer cus)

  {

  // A reference of the business object class

  }

  //standard dataset function that adds a new customer

  public void Add(BOCustomer cus)

  {

  String str = BuildAddString(cus);

  OpenCnn();

  //Open command option cnn parameter is imporant

  OleDbCommand cmd = new OleDbCommand(strcnn);

  //execute connection

  cmdExecuteNonQuery();

  // close connection

  CloseCnn();

  }

  //standard dataset function that updates

  //details of a customer based on ID

  public void Update(BOCustomer cus)

  {

  OpenCnn();

  String selectStr = UPDATE + thisTable +

   set + cus_LName + = + cusLName + +

   + cus_FName + = + cusFName + +

   + cus_Address + = + cusAddress + +

   + cus_Tel + = + cusTel + +

   where cus_ID = + cuscusID + ;

  OleDbCommand cmd = new OleDbCommand(selectStrcnn);

  cmdExecuteNonQuery();

  CloseCnn();

  }

  //standard dataset function that finds and

  //return the detail of a customer in a dataset

  public DataSet Find(String argStr)

  {

  DataSet ds=null;

  try

  {

  OpenCnn();

  String selectStr = select * from + thisTable +

   where cus_ID = + argStr + ;

  OleDbDataAdapter da =

  new OleDbDataAdapter(selectStrcnn);

  ds = new DataSet();

  daFill(dsthisTable);

  CloseCnn();

  }

  catch(Exception e)

  {

  String Str = eMessage;

  }

  return ds;

  }

  private void OpenCnn()

  {

  // initialise connection

  String cnnStr = CnnStr;

  cnn = new OleDbConnection(cnnStr);

  // open connection

  cnnOpen();

  }

  private void CloseCnn()

  {

  // step five

  cnnClose();

  }

  // just a supporting function that builds

  // and return the insert string for dataset

  private String BuildAddString(BOCustomer cus)

  {

  // these are the constants as

  // set in the top of this module

  strTable=Insert into + thisTable;

  strFields= ( + cus_ID +

   + cus_LName +

   + cus_FName +

   + cus_Address +

   + cus_Tel + );

  //these are the attributes of the

  //customer business object

  strValues= Values ( + cuscusID +

   + cusLName +

   + cusFName +

   + cusAddress +

   + cusTel + );

  insertStr = strTable + strFields + strValues;

  return insertStr;

  }

  }

  }


From:http://tw.wingwit.com/Article/program/net/201311/12043.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.