Cấp bậc tác giả:

TRAINING

[TUT .netTiers]Giới thiệu Lớp Business

Được viết bởi webmaster ngày 06/06/2013 lúc 04:29 PM
Bài trước Tôi đã giới thiệu về Lớp Data. Sử dụng cách tiếp cận lớp khi xây dựng framework mang lại cho bạn rất nhiều tính linh hoạt đặc biệt là khi nói đến lớp dữ liệu. Bài này Tôi sẽ giới thiệu về Lớp Business.
  • 0
  • 6781

[TUT .netTiers]Giới thiệu Lớp Business

Bài trước Tôi đã giới thiệu về Lớp Data. Sử dụng cách tiếp cận lớp khi xây dựng framework mang lại cho bạn rất nhiều tính linh hoạt đặc biệt là khi nói đến lớp dữ liệu. Bài này Tôi sẽ giới thiệu về Lớp Business.

Lớp Business

Giới thiệu

Lớp Business là thành phần chính trong ứng dụng của bạn. Nó không phải trường hiệu quả, nhưng bất kỳ yêu cầu nào đều đến API nên đi qua lớp này. Lớp Component, chỉ cần đặt, xác định ranh giới cho toàn bộ logic business và API dữ liệu. 

Lớp Component là nơi bạn sẽ tìm thấy mã điều khiển: quy trình nghiệp vụ, quy trình làm việc, ủy quyền, sức khỏe của ứng dụng, và API dữ liệu. Bạn sẽ thấy nhiều chức năng khác trong lớp này, vì nó không chỉ điều khiển ứng dụng của bạn, mà còn là huyết mạch của toàn bộ ứng dụng của bạn.

Vai trò thành phần lớp:

Sức mạnh - Quan trọng để đảm bảo sức khỏe của ứng dụng của bạn. Nghĩa rằng lớp này chịu trách nhiệm cho việc gọi API của bạn và các dữ liệu hoặc lỗi trả lại ra khỏi vòng đời của ứng dụng. Điều quan trọng là bạn nắm bắt tất cả các lỗi được biết đến và xử lý một cách thích hợp, các hạng mục như trường hợp ngoại lệ không được quản lý gần như không bao giờ quay trở lại lớp consuming mà không có lớp Component không biết về nó đầu tiên. Bạn nên xem xét việc làm, tạo ra một chính sách ngoại lệ mà các bản ghi / email ngoại lệ bất ngờ. Nó rất quan trọng là các lớp Conponent biết về tất cả các ngoại lệ không được quản lý, nó thậm chí còn quan trọng hơn để bạn có thể nhận thức được nó. Một ứng dụng thường không thể mạnh mà không có một số kiểu giám sát của đội ngũ phát triển. 
Ủy quyền - Thời gian chạy ủy quyền là rất quan trọng trong một ứng dụng mà các dữ liệu nhạy cảm. Ví dụ như nếu bạn đang viết một ứng dụng nhân sự, bạn sẽ không muốn tiết lộ thông tin lương của bất kỳ ai trừ khi SecurityPrincipal trong câu hỏi đã được ủy quyền. Giữ quyền của bạn trong điểm vào sẽ giúp giữ cho ứng dụng của bạn an toàn từ thành viên ẩn. 
Quy trình nghiệp vụ và quy trình làm việc - Điểm mấu chốt của bất kỳ ứng dụng để quản lý các quy trình nghiệp vụ và quy trình làm việc một cách chức năng và an toàn. Nhiều nhiều thế hệ công nghệ trước, nhiều ứng dụng được xây dựng với quy trình làm việc ngay trong giao diện người dùng, hoặc các quy trình làm việc sẽ không chiếm quyền, an ninh. 
Nó rất quan trọng để giữ cho các ứng dụng của bạn đủ linh hoạt để thay đổi đột ngột trong quy trình công việc và kinh doanh, trong khi duy trì an toàn thích hợp và ủy quyền.

Lớp Business Component .netTiers

Có hai loại chính của lớp Business Component .netTiers sẽ tạo cho bạn mẫu thường xuyên trong các ứng dụng nghiệp vụ. Các ServiceLayer và DomainModel, hai mẫu thường được sử dụng khi tạo và thao tác các miền đối tượng. Có rất nhiều điều cần lưu ý khi lựa chọn lớp Business Component. 

Điều cần xem xét:

Tại sao phải sử dụng lớp business? Business là gì?

Service Layer

Bạn có thể sử dụng Dịch vụ quản lý tất cả hoạt động Create, Read, Update, Delete, DeepLoad/Save.

AccountService accountsService = new AccountsService();
TList<Accounts> accountList = accountsService.GetAll();

Tiếp theo logic, AccountsService sẽ Ủy quyền yêu cầu bảo mật hiện tại nếu cho phép được kích hoạt. Nó sẽ kiểm tra để xem ConnectionScope hiện tại, để tìm ra nếu Transaction được mở ra và đó dataProvider để sử dụng. Một cách đơn giản để cấu hình provider bạn muốn sử dụng, có thể là các sqlClientProvider với webServiceProvider, nhiều cơ sở dữ liệu cấu hình cho cùng một kiểu provider, hoặc các chuỗi kết nối năng động hơn. Sau đó nó sẽ nhận được các thiết lập hiện tại từ ConnectionScope sử dụng để thực hiện gọi chính xác cho các DataRepository. Lệnh gọi sẽ được gửi vào DataRepository và trả lại cho ServiceLayer. Nếu có một ngoại lệ, HandleException được gọi và kiểm tra để xem nếu bạn đã thực hiện chương trình xử lý ngoại lệ, tức là đăng nhập và rethrow, dừng lại, có xử lý. Tất cả đều được thực hiện thông qua cấu hình trong app/web.config từ khả năng ExceptionHandling trong thư viện nghiệp vụ. Mẫu entlib.config đầy đủ được tạo ra cho bạn khi tạo unittests cho ứng dụng của bạn. 

Cấu hình ExceptionHandling:

<exceptionHandling>
<exceptionPolicies>
<add name="NoneExceptionPolicy">
<exceptionTypes>
<add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" postHandlingAction="None" name="Exception">
<exceptionHandlers>
<add logCategory="Exceptions" eventId="100" severity="Error" title="netTiers.Petshop Exception Handling" formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.XmlExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" priority="0" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" name="Logging Handler" />
</exceptionHandlers>
</add>
</exceptionTypes>

</add>
</exceptionPolicies>
</exceptionHandling>

Đó là dễ nhất để cấu hình thư viện Enterprise đến app/web.config và cấu hình các thiết lập tùy chỉnh của riêng bạn. Bằng cách đó bạn không cần phải lo với các xml. Nếu không có trường hợp ngoại lệ, hoặc bạn muốn tiếp tục xử lý sau khi ngoại lệ, các dữ liệu, thực thể hoặc TList<> được trả.

Ví dụ Dịch vụ API:

 //Create a new Service Workspace object to work with;  
AccountService accountsService = new AccountsService();
    
//Create an entity to use in examples;    
Account accountEntity = new Account();
accountEntity.AccountName = "MyAccountName";
accountEntity.CreatedDate = DateTime.Now;

//GetAll()
TList<Accounts> accountList = accountsService.GetAll();

//Find()
TList<Accounts> accountList = accountsService.Find("IsActive = 1");

//GetPaged()
TList<Accounts> accountList = 
accountsService.GetPaged("IsActive = 1 AND AccountName LIKE 'smi%'");

//GetByFk()
TList<Accounts> accountList = accountsService.GetByCustomerId(25);

//GetIX()
TList<Accounts> accountList = 
accountsService.GetByAccountCreatedDate(new DateTime("1/1/2006"));


//Get()
Accounts account = accountsService.Get(new AccountsKey(23));

//Insert()
accountsService.Insert(accountEntity);
Response.Write(accountEntity.AccountId); // is now populated

//Delete()
bool result = accountsService.Delete(accountEntity);

//Delete()
bool result = accountsService.Delete(23);

//Update()
accountEntity.AccountName = "MyAccountName 2";
accountsService.Update(accountEntity);

//GetByManyToManyl()
TList<Customers> accountList  = accountsService.GetCustomers_From_AccountsReceivable();

//GetCustomProcedureName()
TList<Accounts> accountList = accountsService.GetByAccountMaturationDate();
 
//DeepLoadByIdl() using PK
Account account = accountsService.DeepLoadByAccountId(id, false, DeepLoadType.IncludeChildren, typeof(Customers), typeof(TList<ChartOfAccounts>));

//DeepLoadByIdl() using FK
TList<Account> account = accountsService.DeepLoadByCustomerId(id, false, DeepLoadType.IncludeChildren, typeof(Customers), typeof(TList<ChartOfAccounts>));

//already instatiated objects//DeepLoad
accountsService.DeepLoad(myAccountEntity, false,DeepLoadType.IncludeChildren, typeof(Customers), typeof(TList<ChartOfAccounts>));

// is now filled
Response.Write(accountsService.CustomerIdSource.LastName); 

// is now filled
Response.Write(accountsService.ChartOfAccountsCollection.Count); 

//DeepSave
accountsService.DeepSave(myAccountEntity, false, DeepSaveType.IncludeChildren, typeof(Customers), typeof(TList<ChartOfAccounts>));

Ví dụ Kiến trúc:

Lấy ví dụ B2B và B2C trang web thương mại phức tạp.
Kiểm tra hàng tồn kho,
Xác nhận của nhân viên,
Kiểm tra giá nhân viên
Khám phá và tính toán nhà cung cấp vận chuyển từ bên thứ 3 cho một tập hợp trọng lượng của tất cả các sản phẩm.

Tiến trình:

Tất cả các dịch vụ, là ví dụ dựa trên vùng làm việc để quản lý ứng dụng của bạn. Ví dụ:. OrdersService ordersService = new OrdersService (); Trong vùng làm việc có framework cho bạn thêm nhiều bộ xử lý để thực hiện các đơn vị. 
Mỗi bộ vi xử lý có trách nhiệm cho hành động nghiệp vụ hợp lý duy nhất (đơn vị làm việc) 
Một bộ vi xử lý có thể thực hiện một số kiểm tra để đảm bảo trật tự là hợp lệ. Ví dụ: ValidateInventoryProcessor(Order o)
1. Tìm thấy nếu các sản phẩm theo thứ tự là hàng tồn kho. 
2. Tìm ra kho các mặt hàng thuộc. 
3. Tính toán lộ trình cho chuỗi cung ứng để có được các mặt hàng này. 
4. Bắn ra thông báo đến kho bãi,... 
Bạn sẽ tạo ra bộ vi xử lý khác để ValidateEmployee, Kiểm tra nhân viên xử lý, nhận bán hàng, Vận chuyển thông tin, thanh toán, thông báo. 

Ví dụ

ordersService.ProcessorList.Add(new InventoryProcessor(o));
ordersService.ProcessorList.Add(new VerifyEmployeeProcessor(o.EmployeeIdSource));
ordersService.ProcessorList.Add(new EmployeeOrderProcessor(o));
ordersService.ProcessorList.Add(new BillingProcessor(o));
ordersService.ProcessorList.Add(new ShippingProcessor(o));
ordersService.ProcessorList.Add(new OrderNotificationProcessor(o));

Mỗi xử lý sẽ trả về lớp thực hiện IProcessorResult, trong đó có GenericProcessorResult tạo ra. 
Về cơ bản, lớp này có trách nhiệm theo dõi trạng thái xử lý và tổng hợp tất cả các BrokenRules hoặc là tiến trình tích lũy. 

//Execute Processor List
ServiceResult result = ordersService.Execute();

Tất cả các kết quả xử lý sẽ được tổng hợp thành các lớp ServiceResult. Điều này sẽ cho phép bạn xem tất cả các lỗi đó xảy ra, cũng như bất kỳ trường hợp ngoại lệ. Nếu đã xảy ra ngoại lệ không được quản lý bạn có thể ngừng thực hiện nếu bạn đặt nó vào AbortOnFailure.

if (result.HasErrors)
{
ShowErrors(result.Error);
ShowExceptions(result.Exceptions);
}

Nếu có sai sót, bạn có thể gõ vào thuộc tính Lỗi của ServiceResult là một dòng mới của danh sách tất cả các lỗi từ xác nhận thực thể.

ordersService.GetAll();
ordersService.Save(o);

Ví dụ xử lý:
Mẫu lớp InventoryProcessor

public class InventoryProcessor : ProcessorBase
{
private Entities.Orders order;
private GenericProcessorResult genericProcessorResult;
 
/// <summary>
/// Inventory Processor
/// </summary>
/// <param name="order">Order to process through Inventory</param>

public InventoryProcessor(Entities.Orders order)
{
if (order == null)
throw new ArgumentNullException("order");
 
this.order = order;
}
 
/// <summary>
/// Process the IProcessResult
/// </summary>
/// <returns></returns>
public override IProcessorResult Process()
{
try
{
///Add  custom validation rules for this processor
order.AddInventoryRules();

ProductsService products = new ProductsService();

//check stock
foreach (OrderDetails item in order.OrderDetailsCollection)
{
item.ProductIDSource = 
products.Get(new ProductsKey(item.ProductID));
}

order.Validate();

if (!order.IsValid)
ProcessResult.AddBrokenRulesList(typeof(Entities.Orders),order.BrokenRulesList);
}
catch(Exception exc)
{
if (DomainUtil.HandleException(exc, "NoneExceptionPolicy"))
throw;
}

return ProcessResult;
}
 
/// <summary>
/// ProcessResult of this current process to check Inventory on the Order
/// </summary>
public override IProcessorResult ProcessResult
{
get
{
if (genericProcessorResult == null)
{
genericProcessorResult = new GenericProcessorResult();
}
return genericProcessorResult;
}
}
}

Vai trò Business:
Orders.cs

/// <summary>
/// Add Extra Custom Validation Rules
/// </summary>
public void AddInventoryRules()
{
ValidationRules.AddRule(InventoryRuleCheck, new ValidationRuleArgs("UnitsInStock"));
 }

/// <summary>
/// Check Inventory
/// </summary>
/// <param name="target"></param>
/// <param name="e"></param>
/// <returns></returns>
public bool InventoryRuleCheck(object target, ValidationRuleArgs e)
{
foreach(OrderDetails detail in OrderDetailsCollection)
{
if (detail.ProductIDSource == null)
continue;

if (detail.ProductIDSource.UnitsInStock < detail.Quantity)
{
e.Description = string.Format("{0} - we do not have that much stock for this.",detail.ProductIDSource.ProductName);
return false;
}
}
return true;
}

Program.cs

using System;
using System.Collections.Generic;
using System.Text;
using Northwind.Data;
using Northwind.Entities;
using Northwind.Entities.Validation;
using Northwind.Services;
using Northwind.Services.Processors.Orders;

namespace NorthwindWebConsole
{
  class Program
  {

    static void Main(string[] args)
    {
        ///Create an Orders Workspace 
        OrdersService service = new OrdersService();
 
        ///Create a simulated Order
        Orders o = new Orders();
        ProductsService products = new ProductsService();
        TList<Products> plist = products.GetAll(); 

         ///Create a fake order to test our validation.
        for(int i=0;i<10;i++)
        {
            OrderDetails detail = new OrderDetails();
            detail.ProductID = plist[i].ProductID;
            detail.ProductIDSource = plist[i];
 
            ///Should trigger an invalid quantity on final loops 
            detail.Quantity = Convert.ToInt16(i * i);
            o.OrderDetailsCollection.Add(detail);
        }

        ///For this business process, we want to verify Inventory 
        service.ProcessorList.Add(new InventoryProcessor(o));
        
        ///An object holding the results of the pipeline request.
        ServiceResult result = service.Execute();

        if (result.HasErrors)
            Console.WriteLine(result.Error);

         Console.ReadLine();
     }
  }
}

Bài tiếp theo Chúng ta sẽ cùng nghiên cứu xây dựng tầng Web. Bộ thư viện Web .netTiers là một bộ điều khiển và đối tượng cung cấp công cụ mạnh để thực hiện các dự án Web dễ dàng và hiệu quả hơn

Nguồn bài viết: DOTNET.VN

BÌNH LUẬN BÀI VIẾT

Bài viết mới nhất

LIKE BOX

Bài viết được xem nhiều nhất

HỌC HTML