I'm mentoring a student and he's very much in-love in programming. He showed me his first simple N-Tier application in TDD approach.
It's a very simple application, but I'm sure newbies could learn something from this.
Test Layer:
[Test]
public void DAL_Should_Return_A_List_Of_Kampung()
{
List<Kampung> kampung = KampungData.ListOfKampung();
Assert.IsNotNull(kampung);
}
Data Layer:
public static List<Kampung> ListOfKampung()
{
try
{
var results = new List<Kampung>();
const string connectionString = "Data Source=HACK3R;Initial Catalog=KampungDB;Integrated Security=True";
using (var con = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand("ListOfKampung", con))
{
cmd.CommandType = CommandType.StoredProcedure;
try
{
con.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
results.Add(
new Kampung
{
KampungId = reader.GetInt32(0),
Name = reader.GetString(1),
Age = reader.GetInt32(2),
Salary = reader.GetDecimal(3),
Score = reader.GetDecimal(4),
DateAdded = reader.GetDateTime(5),
DateUpdated = reader.GetDateTime(6)
}
);
}
reader.Close();
}
}
catch (Exception ex)
{
Console.WriteLine("Data Error: {0}", ex.Message);
}
return results;
}
}
}
catch (Exception)
{
throw new ApplicationException("Unable to get data from the database.");
}
}
Business Layer:
using System;
namespace KampungProject.Applications
{
public class Kampung
{
public Kampung()
{ }
public Kampung(int kampungId, string name, int age, decimal salary, decimal score, DateTime dateAdded, DateTime dateUpdated)
{
KampungId = kampungId;
Name = name;
Age = age;
Salary = salary;
Score = score;
DateAdded = dateAdded;
DateUpdated = dateUpdated;
}
public int KampungId { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public decimal Salary { get; set; }
public decimal Score { get; set; }
public DateTime DateAdded { get; set; }
public DateTime DateUpdated { get; set; }
}
}
Presentation Layer:
using System;
using System.Collections.Generic;
using KampungProject.Applications;
namespace KampungProject
{
public partial class WebForm1 : System.Web.UI.Page
{
protected List<Kampung> Kampungs;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewKampungList();
}
}
private void ViewKampungList()
{
Kampungs = KampungData.ListOfKampung();
GridView1.DataSource = Kampungs;
GridView1.DataBind();
}
}
}
No comments:
Post a Comment