• DbFactory Class ÖrneÄŸi

    Uzun Bir Aradan Sonra Herkese Merhabalar,
    Sözü Fazla Uzatmadan Makalemize Başlayabiliriz,
    Bugünkü Makalemizin Konusu DbFactory Class Yapısı,
    Biraz Daha Açacak Olursak,
    Uygulamamızda İlk Önce Entity Kısmını Oluşturacağız,
    Daha Sonra Facade Kısmına Geçeceğiz,
    Son Olarak’da Presentation Layer Kısmını GerçekleÅŸtireceÄŸiz.

    Peki Ne İşimize Yarayacak Bu DbFactory Class Derseniz,
    Alışık OlduÄŸumuz ADO.NET’in Farklı Bir Yapısına Göz Atacağız,
    Malum Bir İşi Yapmanın Birden Fazla Yolu Var Bizde Klasik Yapıdan Biraz Farklı Olarak DbFactory Yapısını Kullanacağız Bugün.

    O Zaman Hiç Vakit Kaybetmeden İlk Olarak Visual Studio İle Bir ASP.NET Proseji Oluşturalım Benim Projemin Adı DB_FACTORY Siz Farklı Bir İsim Verebilirsiniz.
    Hemen web.config Dosyasında Bağlantımızı Tanımlayalım.

    <connectionStrings>
    <add name=”North” connectionString=”Data Source=.; Initial Catalog=Northwind; Integrated Security=true”
    providerName=”System.Data.SqlClient”/>
    </connectionStrings>

    Daha Sonra Projemize Sağ Click App_Code Klasörümüzü Ekleyelim İçerisine Db_Factory_Connection.cs Adlı Bir Class Oluşturalım.
    Ve Class’ımızı AÅŸağıdaki Gibi DeÄŸiÅŸtirelim.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    using c_Manager = System.Web.Configuration.WebConfigurationManager;

    namespace Silo.Db_Factory_Connection
    {
    public class Db_Factory_Connection
    {
    private static string _ConnectionString;
    private static string _ProviderName;

    static Db_Factory_Connection()
    {
    _ConnectionString = c_Manager.ConnectionStrings["North"].ConnectionString;
    _ProviderName = c_Manager.ConnectionStrings["North"].ProviderName;
    }

    public static string ConnectionString
    { get { return _ConnectionString; } }

    public static string ProviderName
    { get { return _ProviderName; } }
    }
    }

    Hemen Arkasından App_Code İçerisine Db_Factory_Entity.cs Class’ımızı OluÅŸturalım.Ve AÅŸağıdaki Gibi Tasarlayalım.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    using cp = Silo.Db_Factory_Connection.Db_Factory_Connection;
    using System.Data.Common;
    using System.Data;

    namespace Silo.Db_Factory_Entity
    {
    public static class Db_Factory_Entity
    {
    static Db_Factory_Entity() { }

    // İstersek Store Procedure Olarak Oluşturabiliriz.
    public static DbCommand CreateCommand_Procedure()
    {
    string connectionString = cp.ConnectionString;
    string providerName = cp.ProviderName;

    DbProviderFactory factory = DbProviderFactories.GetFactory(providerName);
    DbCommand command = factory.CreateCommand();

    command.Connection = factory.CreateConnection();
    command.Connection.ConnectionString = connectionString;
    command.CommandType = System.Data.CommandType.StoredProcedure;

    return command;
    }

    // İstersek Text Olarak Oluşturabiliriz Tamame Size Kalmış.
    public static DbCommand CreateCommand_Text()
    {
    string connectionString = cp.ConnectionString;
    string providerName = cp.ProviderName;

    DbProviderFactory factory = DbProviderFactories.GetFactory(providerName);
    DbCommand command = factory.CreateCommand();

    command.Connection = factory.CreateConnection();
    command.Connection.ConnectionString = connectionString;
    command.CommandType = System.Data.CommandType.Text;

    return command;
    }

    public static int ExecuteNonQuery(DbCommand command)
    {
    int affected = 0;

    try
    {
    command.Connection.Open();
    affected = command.ExecuteNonQuery();
    }
    catch { throw new Exception(“ExecuteNonQuery  Hatası OluÅŸtu !”); }
    finally { command.Connection.Close(); }

    return affected;
    }

    public static DataTable ExecuteSelectCommand(DbCommand command)
    {
    DataTable dt = null;

    try
    {
    command.Connection.Open();
    DbDataReader dr = command.ExecuteReader(CommandBehavior.CloseConnection);
    dt = new DataTable();
    dt.Load(dr);
    }
    catch { throw new Exception(“ExecuteSelectCommand  Hatası OluÅŸtu !”); }

    return dt;
    }

    public static object ExecuteScalar(DbCommand command)
    {
    object affected = null;

    try
    {
    command.Connection.Open();
    affected = command.ExecuteScalar();
    }
    catch { throw new Exception(“ExecuteScalar  Hatası OluÅŸtu !”); }
    finally { command.Connection.Close(); }

    return affected;
    }

    public static DbDataReader ExecuteReader(DbCommand command)
    { return command.ExecuteReader(); }
    }
    }

    En Son Olarak App_Code İçerisine Db_Factory_Facade.cs Class’ımızı OluÅŸturalım Ve AÅŸağıdaki Gibi Tasarlayalım.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Data;
    using System.Data.Common;

    using com = Silo.Db_Factory_Entity.Db_Factory_Entity;

    // Uygulamamız’da Inheritance Kullanmadığımız İçin,
    // Uygulamamız Çok Kapsamlı Olmadığı İçin,
    // struct Kullanmak Daha Mantıklı.
    // struct’lar  DeÄŸer Tipli Nesneler OlduÄŸu İçin Referans Tipli Nesnelere Göre Daha Hızlı Çalışır.

    public struct Products
    {
    #region DeÄŸiÅŸkenler

    private int? _productID;
    public int? ProductID
    { get { return _productID; } set { _productID = value; } }

    private string _productName;
    public string ProductName
    { get { return _productName; } set { _productName = value; } }

    private int? _supplierID;
    public int? SupplierID
    { get { return _supplierID; } set { _supplierID = value; } }

    private int? _categoryID;
    public int? CategoryID
    { get { return _categoryID; } set { _categoryID = value; } }

    private string _quantityPerUnit;
    public string QuantityPerUnit
    { get { return _quantityPerUnit; } set { _quantityPerUnit = value; } }

    private decimal? _unitPrice;
    public decimal? UnitPrice
    { get { return _unitPrice; } set { _unitPrice = value; } }

    private short? _unitsInStock;
    public short? UnitsInStock
    { get { return _unitsInStock; } set { _unitsInStock = value; } }

    private short? _unitsOnOrder;
    public short? UnitsOnOrder
    { get { return _unitsOnOrder; } set { _unitsOnOrder = value; } }

    private short? _reorderLevel;
    public short? ReorderLevel
    { get { return _reorderLevel; } set { _reorderLevel = value; } }

    private bool _discontinued;
    public bool Discontinued
    { get { return _discontinued; } set { _discontinued = value; } }

    private string _picture;
    public string Picture
    { get { return _picture; } set { _picture = value; } }

    #endregion

    #region Constructor

    public Products(int? ProductID, string ProductName, int? SupplierID, int? CategoryID, string QuantityPerUnit, decimal? UnitPrice, short? UnitsInStock, short? UnitsOnOrder, short? ReorderLevel, bool Discontinued, string Picture)
    {
    this._productID = ProductID;
    this._productName = ProductName;
    this._supplierID = SupplierID;
    this._categoryID = CategoryID;
    this._quantityPerUnit = QuantityPerUnit;
    this._unitPrice = UnitPrice;
    this._unitsInStock = UnitsInStock;
    this._unitsOnOrder = UnitsOnOrder;
    this._reorderLevel = ReorderLevel;
    this._discontinued = Discontinued;
    this._picture = Picture;
    }

    #endregion
    }

    public struct Categories
    {
    #region DeÄŸiÅŸkenler

    private int? _categoryID;
    public int? CategoryID
    { get { return _categoryID; } set { _categoryID = value; } }

    private string _categoryName;
    public string CategoryName
    { get { return _categoryName; } set { _categoryName = value; } }

    private string _description;
    public string Description
    { get { return _description; } set { _description = value; } }

    private byte?[] _picture;
    public byte?[] Picture
    { get { return _picture; } set { _picture = value; } }

    #endregion

    #region Constructor

    public Categories(int? CategoryID, string CategoryName, string Description, byte?[] Picture)
    {
    this._categoryID = CategoryID;
    this._categoryName = CategoryName;
    this._description = Description;
    this._picture = Picture;
    }

    #endregion
    }

    namespace Silo.Db_Factory_Facade
    {
    public static class Db_Factory_Facade
    {
    static Db_Factory_Facade() { }

    public static DataTable GetCategories()
    {
    DbCommand command = com.CreateCommand_Text();
    // Gördüğünüz Üzere Ben Text Olarak Kullandım Dilerseniz Siz SQL Tarafında Oluşturacağınız Store Procedure Çağırarak Daha
    // Profesyonel Bir Kullanım Gerçekleştirebilirsiniz. Text Yada Store Procedure Kullanımı Tamamen Size Kalmış.
    string strSELECT = “SELECT CategoryID, CategoryName FROM Categories”;
    command.CommandText = strSELECT;

    DataTable dt = com.ExecuteSelectCommand(command);

    return dt;
    }

    public static DataTable GetProductsByCategoryID(int? CategoryID)
    {
    DbCommand command = com.CreateCommand_Text();
    string strSELECT =
    “SELECT ProductID, ProductName, UnitPrice, UnitsInStock, Picture FROM Products ” +
    “WHERE Products.CategoryID=@CategoryID”;
    command.CommandText = strSELECT;

    DbParameter param = command.CreateParameter();
    param.ParameterName = “@CategoryID”;
    param.Value = CategoryID;
    param.DbType = DbType.Int32;

    command.Parameters.Add(param);

    DataTable dt = com.ExecuteSelectCommand(command);

    return dt;
    }

    public static DataTable GetProducts()
    {
    DbCommand command = com.CreateCommand_Text();
    string strSELECT =
    “SELECT ProductID, ProductName, UnitPrice, UnitsInStock, Picture FROM Products”;
    command.CommandText = strSELECT;

    DataTable dt = com.ExecuteSelectCommand(command);

    return dt;
    }
    }
    }

    Artık Code Kısmını Bitirdiğimize Göre Tasarım Kısmına Geçebilirz Aşağıdaki Gibi Tasarlayalım.

    <table align=”center”>

    <tr>
    <td>
    <asp:DropDownList
    ID=”DropDownList1″
    runat=”server”
    Width=”200″
    DataTextField=”CategoryName”
    DataValueField=”CategoryID”
    AutoPostBack=”true”
    onselectedindexchanged=”DropDownList1_SelectedIndexChanged” />
    </td>
    </tr>

    <tr>
    <td></td>
    </tr>

    <tr>
    <td>
    <asp:Repeater
    ID=”Repeater1″
    runat=”server”>
    <ItemTemplate>
    <table>
    <tr>
    <td><b>Product ID</b></td>
    <td><%#Eval(“ProductID”) %></td>
    </tr>

    <tr>
    <td><b>Product Name</b></td>
    <td><%#Eval(“ProductName”) %></td>
    </tr>

    <tr>
    <td><b>Unit Price</b></td>
    <td><%#Eval(“UnitPrice”,”{0:C}”) %></td>
    </tr>

    <tr>
    <td><b>Units In Stock</b></td>
    <td><%#Eval(“UnitsInStock”,”{0:} ADET”) %></td>
    </tr>

    <tr>
    <td valign=”top”><b>Picture</b></td>
    <td>
    <asp:Image ID=”Image1″ runat=”server” Width=”100″ Height=”100″ ToolTip=”Güzel Resimler” ImageUrl=’<%#Eval(“Picture”,”~/Images/{0}”) %>’ />
    </td>
    </tr>

    </table>
    </ItemTemplate>

    <SeparatorTemplate>
    <br />
    </SeparatorTemplate>
    </asp:Repeater>
    </td>
    </tr>

    </table>

    Sayfamızın CodeBehind Kısmına Geçmeden Önce Resim Olayını Açıklayalım Ben Veritabanı Olarak Northwind Kullandım Ve Products Tablosuna Picture Diye Bir Kolon Daha Ekledim,
    Kolon Tipini NVarchar(75) Olarak Ayarladım Ve Resimlerimi Veritabanına Yol Olarak Kaydettim ( CP1.jpg, CP2.jpg) Gibi Ve ASP.NET Projemin İçerisine Images Diye Bir Klasör Oluşturup,
    Resimlerimi Bu Klasörün İçerisinde Sakladım,Bilemeyen Arkadaşlarımıza Kolaylık Olması Açısından Biraz Ayrıntılı Anlattım Ki ? İşareti Kalmasın.
    Artık Code Behind Kısmına Geçebiliriz.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;

    using Silo.Db_Factory_Facade;

    public partial class _Default : System.Web.UI.Page
    {
    protected void Doldur_DropDownList(DropDownList myDropDownList)
    {
    DataTable dt = Db_Factory_Facade.GetCategories();

    myDropDownList.DataSource = dt;
    myDropDownList.DataBind();
    }

    protected void Doldur_Repeater(DropDownList myDropDownList, Repeater myRepeater)
    {
    int CategoryID = int.Parse(myDropDownList.SelectedValue.ToString());

    DataTable dt = Db_Factory_Facade.GetProductsByCategoryID(CategoryID);

    myRepeater.DataSource = dt;
    myRepeater.DataBind();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
    if (!Page.IsPostBack)
    Doldur_DropDownList(DropDownList1);
    }

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
    Doldur_Repeater(DropDownList1, Repeater1);
    }
    }

    Gördüğünüz Gibi Code Behind Kısmında Herhangi Bir Kod Karmaşıklığı Yok
    Asıl İşimizi Arka Tarafda Entity Ve Facade Kısmında Tutarak Uygulamamızı Kod Karmaşıklığından Ve Amatör Bir Code Kullanımından Profesyonel Code Kullanımına Geçirmiş Olduk.

    Artık Projemizi Build Ederek Çalıştırabiliriz.
    Sonucu Aşağıdaki Gibi Olacaktır.

    Proje

    Ben Ayrıyetten Resimde Görüldüğü Gibi CustomPaging Yapmıştım İnÅŸaallah Bunu’da Farklı Bir Makalede Ele Alacağız.
    Geldik Bir Makalemizin Daha Sonuna,
    Umarım Faydalı Olmuştur Arkadaşlar,
    Bir Sonraki Makalede Görüşmek Ümidiyle Hoşçakalın.

    Blog Widget by LinkWithin

    Etiketler:, , , ,

2 Yorum


  1. Umut Sinan Åžirin diyor ki:

    Hoş geldin kardeş uzun bi aradan sonra güzel bi yazı ile başladın süper olmuş. Senin bu yazı ardından bide BLL patlatmak lazım ne dersin:)))?

  2. blu_day1979 diyor ki:

    HoÅŸbulduk Umutum,
    Dediğin Gibi Birde BLL Yaparız İnşaallah Çok Güzel Olur,

Yorum Yapın

You must be logged in to post a comment.