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.

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.
2 Yorum to “DbFactory Class Örneği”
Giriş
Kategoriler
Arşivler
Takvim
Son YazIlar
- Mevlit Kandiliniz Mübarek Olsun
- Dünyanın en karanlık kahramanı yeniden sürüyor : HAYALET SÜRÜCÜ 2 İNTİKAM ATEŞİ
- Ya Ben İstanbul’u Alacağım, Ya İstanbul Beni ! : FETİH 1453
- Lost’un yaratıcısı J.J. Abrams’tan yeni dizi :ALCATRAZ
- Gurbetçi Rocky’nin komik hikayesi: BERLİN KAPLANI
- Uluslararası Çok Satan Üçlemeden :EJDERHA DÖVMELİ KIZ
- Hoşgeldin 2012
- Geri sayım başlasın ! : YILBAŞI GECESİ
- Plansız.Desteksiz.Seçimsiz :GÖREVİMİZ TEHLİKE 4
- Akıllı ve karizmatik dedektif Sherlock Holmes, en büyük düşmanı Profesör Moriarty’e karşı : Sherlock Holmes: Gölge Oyunları
Son Yorumlar
- Lost’un yaratıcısı J.J. Abrams’tan yeni dizi :ALCATRAZ için Güray
- Aşkın klişelerine karşı alaycı bir tavır takınmak,sizi gerçek aşka karşı kör mü yapar?: ARKADAŞTAN ÖTE için genceaydin
- Windows 7 Kurulum Sorunu (Çözümü) için Güray
- Windows 7 Kurulum Sorunu (Çözümü) için expert_-_man
- Müzik dinlemenin en hızlı ve en kolay yolu myFizy.com için Güray
- 64 bit İşletim Sisteminde 32 bitlik dll ve ocx Dosyalarını .Net’le(Dotnet) import Etme Sorununun Çözümü için Umut Sinan Şirin
- 64 bit İşletim Sisteminde 32 bitlik dll ve ocx Dosyalarını .Net’le(Dotnet) import Etme Sorununun Çözümü için gurultu12
- 64 bit İşletim Sisteminde 32 bitlik dll ve ocx Dosyalarını .Net’le(Dotnet) import Etme Sorununun Çözümü için Umut Sinan Şirin
- 64 bit İşletim Sisteminde 32 bitlik dll ve ocx Dosyalarını .Net’le(Dotnet) import Etme Sorununun Çözümü için gurultu12
- İhanet Noktası (Dan Brown) için pesimist
En Çok Okunanlar
- Eset Nod32 Antivirüs ekrn.exe Sorunu (Çözümü) - 20.743 kere okundu.
- Windows 7 Kurulum Sorunu (Çözümü) - 15.392 kere okundu.
- Skyfire 4.3.2.1_3001 Hatası (Symbian ve Windows Mobile Çözümü) - 13.043 kere okundu.
- Nokia 5800 Temaları - 11.829 kere okundu.
- Golden Retriever - 11.340 kere okundu.
- Kilyos - 9.613 kere okundu.
- Şemsiye Tarihçesi - 8.578 kere okundu.
- “o” an fotoğrafları - 7.257 kere okundu.
- Prag - 6.747 kere okundu.
- Nokia 5800 Programlar 1 - 5.828 kere okundu.
- IPhone 2 Çıktı ve Satışta.. - 5.163 kere okundu.
- Barış Manço - 4.932 kere okundu.
- Sigarayı İlk Kim Keşfetti? - 4.920 kere okundu.
- BİSİKLET - 4.578 kere okundu.
- Windows XP’nin Ölüm Tarihi Uzatıldı - 4.322 kere okundu.
Etiket Bulutu
WP Cumulus Flash tag cloud by Roy Tanck and Luke Morton requires Flash Player 9 or better.


Bu Yazı 1.154 kere okundu.
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:)))?
Hoşbulduk Umutum,
Dediğin Gibi Birde BLL Yaparız İnşaallah Çok Güzel Olur,