Aklımda Kalası Kelimeler

* давайте работать вместе
* Zarf ve Mazruf, Zerafet(xHoyratlık) ile aynı kökten(za-ra-fe) gelir
* Bedesten
* Suç subuta ermiştir - Suç sabit olmuştur
C# etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
C# etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

1 Nisan 2011 Cuma

C# Delegate

Önce aşağıdaki ekran çıktısına bakarak neler çıkarabildiğimize bakalım:
  1. System isim uzayında (System.Delegate)
  2. ICloneable arayüzünü implement etmiş. Demek ki public object Clone() imzalı bir metodu implement etmiş.İlk metot olan Clone() ICloneable arayüzünden geliyor
  3. ISerializable arayüzünü implement etmiş. Demek ki kendine has bir serileştirme yapısı kurulmak istenmiş.

İsimsiz metotlar C# 2.0 ile gelmiş, delegate ile kullanılabiliyorlardı. Delegate, fonksiyon işaretçisi olarak kullanmamız için önemli bir araç. Delegate türünde yeni bir tür tanımlayarak, bu türümüzün örneklerine metotları değer olarak verebiliyoruz. Bu sayede bu fonksiyon işaretçilerimizi herhangi bir zaman çağırabiliriz.

Bir metodun dönüş türü ya void ya da belirli bir tipte örneği olabilir. Void dönüşlü metotlar için C# 3.0 ile gelen Action'ı kullanabiliriz(void dönüşlü metotlar için olup parametre listesini generic verebiliriz Action<int,bool,OyuncuSinifi>).
Bir de dönüş türü bir tipin örneği olacak metodlar için Func'ı kullanabiliriz. Buraya kadar her şey yolunda değil mi?

using System;
using System.IO;

namespace CSharp_Orneklerim.Delegate_Event
{
    /*
     *  delegate Bir tip tanımlamasıdır, değişken deklarasyonu değildir. 
     *  Hiçbir tip tanımlaması metot içinde tanımlanmaya müsade edilmez. 
     *  Tip tanımlamaları sadece sınıf(class) ve isim uzayı kapsamında yapılabilir
     */

    partial class Delegate_01
    {
        static void Calis()
        {
            // 1. Kısımda DELEGATE nasıl çalışır
            Birinci_Kisim();

            // 2. Kısımda COvariance ve CONTRAvariance örneği olacak
            Ikinci_Kisim();

            // 3. Kısımda lambda ifadeleriyle delegate tanımlanması
            Ucuncu_Kisim();

            // 4. Kısımda Action ve Func tanımlamalarıyla delegate tanımlanması
            Dorduncu_Kisim();

            // 5. Kısımda delegate tiplerin GENERIC hallerini yazalım
            Besinci_Kisim();
        }


        #region *********************** 1. KISIM - DELEGATE Nasıl Çalışır? *******
        // Önce bir delegate tanımlayacağız(Tıpkı sınıf tanımladığımız gibi). 
        // delegate'imizin adı DelegateTipi olacak(tıpkı Kisi adında class tanımlar gibi). 
        // Void dönecek ve parametre almayacak(tıpkı property, field, metotlar tanımladığımız classlar gibi)
        public delegate void DelegateTipi();
        private static void Birinci_Kisim()
        {
            // Yukarıda tanımladığımız DelegateTipi'nden f örneğini(tıpkı cenkGonen nesnesini Oyuncu sınıfından türetir gibi) tanımlayalım.
            // f nesnemize(Delegate tipi referans tiptir)
            // A delegate is a reference type that can be used to encapsulate a named or an anonymous method.
            DelegateTipi f = null;
            DelegateTipi f1 = null;
            f1 = delegate { Console.WriteLine("f1 yaz bişi"); };
            f1 += delegate { Console.WriteLine("f1 yaz bişi daha"); };

            f += delegate { Console.WriteLine("bu da yaz"); };
            f += f1;
            Console.WriteLine(f.GetInvocationList().Length);
            f -= (DelegateTipi)f1.GetInvocationList()[1];
            Console.WriteLine(f.GetInvocationList().Length);
            f();


            //--------------------------------- STATIC tip olarak Delegate tanımlama --------------------------------------
            // STATIC_VAR:
            // 
            // TekParametreliIntDonuslu tipini tanımlıyoruz
            // static TekParametreliIntDonuslu static_delegate_degisken : ile sınıfa bağlı bir field tanımlıyoruz
            // ve hemen aşağıdaki satırlarda bir metodu bu değişkene değer olarak atayıp delegate üstünden metodu ateşliyoruz.
            Delegate_01.static_delegate_degisken = new TekParametreliIntDonuslu(delegate(int a) { return a += 1; });
            Delegate_01.static_delegate_degisken(3); // 4 dönecektir
        }
        // STATIC değişken olarak deklare edeceğimiz değişkenin türetileceği tip olan delegate tanımlaması
        public delegate int TekParametreliIntDonuslu(int _i);
        // delegate tipler static tanımlanamaz ancak delegate tipten static bir değişken tanımlanabilir (STATIC_VAR)
        public static TekParametreliIntDonuslu static_delegate_degisken;

        // Hatta delegate tiplerinin get ve set metotları olabildiği için property olarak da tanımlayabiliyoruz ***
        public DelegateTipi budaPropertyOlsun { get; set; }
        #endregion

        #region *********************** 2. KISIM - CO-CONTRA_variance ************
        // delegate nesneleri, delegate'in imzasındaki dönüş tipinden türeyen nesneleri döndüren metotları işaret ederse
        public delegate Stream Delegate_Covariance_tipi();

        // delegate nesneleri, delegate'in imzasındaki parametrelerin türeyen nesnelerini parametre olarak alan metotları işaret ederse
        public delegate void Delegate_Contravariance_tipi(StreamWriter _sw);
        private static void Ikinci_Kisim()
        {
            // Metodumuz FileStream(Stream'den türemiş), TextReader parametresi aldığı için
            // Covariance delegate kullanılmış diyebiliriz
            Delegate_Covariance_tipi del_co = delegate()
                                                        {
                                                            // Dönüş nesnesi de Stream sayılır ;)
                                                            return new FileStream("dosyaYolu.txt", FileMode.OpenOrCreate);
                                                        };

            // f_contra metodu TextWriter türünden alıyor. Bu da StreamWriter'da türetildiği için contravariance oluyor
            Delegate_Contravariance_tipi del_contra = f_contra;
        }

        static void f_contra(TextWriter tw) { }
        #endregion

        #region *********************** 3. KISIM - LAMBA EXPRESSIONS *************

        public delegate void Del_Donussuz_Parametreli(int _a, byte _b);
        public delegate TextWriter Del_DonusTipli_Parametreli(string _dosyaYolu);
        private static void Ucuncu_Kisim()
        {
            //----------------------- DÖNÜŞSÜZ(void)
            // İsimsiz fonksiyon olarak delegate ile şöyle yazılır:
            Del_Donussuz_Parametreli delegate1 = delegate(int a, byte b)
                                               {
                                                   Console.WriteLine("Ben dönüşsüz bir metodum");
                                                   Console.WriteLine("{0} ve {1} değerinde 2parametre aldım", a, b);
                                               };

            // Lambda ifadesiyle şöyle yazılır:
            Del_Donussuz_Parametreli lambda1 = (a, b) =>
                                               {
                                                   Console.WriteLine("Ben dönüşsüz bir metodum");
                                                   Console.WriteLine("{0} ve {1} değerinde 2parametre aldım", a, b);
                                               };

            //----------------------- DÖNÜŞLÜ

            // İsimsiz fonksiyon olarak delegate ile şöyle yazılır:
            Del_DonusTipli_Parametreli delegate2 = delegate(string dosyaAdresi)
                                                   {
                                                       TextWriter tw = File.CreateText(dosyaAdresi);
                                                       return tw;
                                                   };

            // Lambda ifadesiyle şöyle yazılır:
            // Tek parametre olduğu için parantez içine almaya gerek yok "_dosyaninAdresi" parametresini
            Del_DonusTipli_Parametreli lambda2 = _dosyaninAdresi =>
                                                 {
                                                     // Parametreyi kullanmadık ama StreamWriter türünde bir nesne dönmeden edemeyeceğim
                                                     TextWriter tw = Console.Out;
                                                     tw.WriteLine("Ekrana gitmeden merhaba diyeyim");
                                                     return tw;
                                                 };
        }
        #endregion

        #region *********************** 4. KISIM - Action & Func *****************
        private static void Dorduncu_Kisim()
        {
            //----------------------- DÖNÜŞSÜZ (void)
            /* Action ve Func zaten Delegate'ten türetilmiş oldukları için 
             * Action ya da Func tipinden bir nesne yaratmak 
             * Delegate tipinde bir nesne yaratmakla aynı anlama geliyor.
             */
            Action<int, byte> donussuz_2_parametreli_metot = delegate(int a, byte b)
                                                        {
                                                            Console.WriteLine("Dönüşsüz demiştik. Parametreler:");
                                                            Console.WriteLine("{0} ile {1} değerlerini içeriyor", a, b);
                                                        };
            // Doğrudan örnek türettiğimiz bir tip tanımı olarak kullandık Action'ı
            donussuz_2_parametreli_metot(1, 2);

            // Başka bir Action'a atayabiliriz
            Action<int, byte> donussuz_parametreli_metod = new Action<int, byte>(donussuz_2_parametreli_metot);
            donussuz_parametreli_metod(3, 4);

            // delegate ile sınıf veya namespace kapsamında tip oluşturmadan, 
            // void dönen metodu doğrudan nesne yaratarak çağırmak için 
            // delegate(){} kısmını Action<>(...) içine alıyoruz.
            Action<int, byte> tip_olusturmadan_delegate_ile_donussuz_metot_tanimlamak = new Action<int, byte>(delegate(int a, byte b) { });

            //*********** DÖNÜŞLÜ
            // delegate ile sınıf veya namespace kapsamında tip oluşturmadan, 
            // değer dönen metodu doğrudan nesne yaratarak çağırmak için 
            // delegate(){} kısmını Func<>(...) içine alıyoruz.
            Func<int, string> tip_olusturmadan_delegate_ile_metot_yazmak = new Func<int, string>(delegate(int a) { return a.ToString(); });
            tip_olusturmadan_delegate_ile_metot_yazmak(211);

            // Func<int,string> : int tipinde 1 parametre alıyor string dönüyor
            // tek parametreyi paranteze sarmaya gerek yok
            // birden çok satırda işlem yapmadığı için gövdeyi {...} sarmaya da gerek yok
            Func<int, string> string_donuslu_int_parametreli = i => i.ToString();
            string_donuslu_int_parametreli(114); // 114 yazacak ekrana
        }

        #endregion

        #region *********************** 5. KISIM - Generic Delegates *************

        public delegate S jenerikFunc<T, K, S>(T t, K k);
        public delegate void jenerikAction<T, K>(T t, K k);
        private static void Besinci_Kisim()
        {
            jenerikFunc<int, byte, string> jenerikFuncNesnesi = (i, b) => (i + b).ToString();
            string toplam = jenerikFuncNesnesi(3, 4);// toplam = "7" 

            jenerikAction<int,byte> jenerikActionNesnesi = delegate(int i, byte b)
                                                           {
                                                               Console.WriteLine("dönüşsüz metot!");
                                                               Console.WriteLine(i+b);
                                                           };
            jenerikActionNesnesi(4, 5);// Ekrana iki satır yazacak > 
            // 1. satır: "dönüşsüz metot!", 
            // 2. satır: "9"
        }
        #endregion
    }
}

Action

Action ve Func makalesi için buraya tıklayabilirsiniz

Func

16 Ocak 2011 Pazar

.Net: İstisna fırlatırken dikkat edilecek hususlar 1

Aslında başka bir durumu araştırmak için baktım ama o kadar ekran yakalama boşa gitmesin :)
Basit ama yapılan hatalardan.
İstisna fırlatılırken yeni bir istisna fırlatmamak ve istisnaya neden olan durumu örtmemek gerek.



9 Ocak 2011 Pazar

C# ile Thread lenmiş İstemci-Sunucu


Ref: http://www.switchonthecode.com/tutorials/csharp-tutorial-simple-threaded-tcp-server

Sunucu



using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace newServer
{
public partial class FrmServer : Form
{
public FrmServer()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}

private TcpListener tcpListener;
private Thread mainThread;
private void Form1_Load(object sender, EventArgs e)
{
tcpListener = new TcpListener(IPAddress.Any, 3000);
mainThread = new Thread(ListenMainThread);
mainThread.Start(tcpListener);
}

public void ListenMainThread(object listener)
{
tcpListener.Start();
while (true)
{
TcpClient client = tcpListener.AcceptTcpClient();
lbLog.Items.Add("Bağlantı geldi");
Thread clientThread = new Thread(HandleClientComm);
clientThread.Start(client);
}
}

public void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient) client;
NetworkStream clientStream = tcpClient.GetStream();

byte[] message = new byte[4096];
int bytesRead;

while (true)
{
bytesRead = 0;

try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
break;
}

if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}

//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
string okunan = encoder.GetString(message, 0, bytesRead);
lbLog.Items.Add("Okundu: " + okunan);
}

tcpClient.Close();
}
}
}


İstemci



using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace NewClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
TcpClient client = new TcpClient();
client.Connect("127.0.0.1", 3000);
NetworkStream nsClient = client.GetStream();
for (int i = 0; i < 10; i++)
{
string sMesaj = "Merhaba " + i;
byte[] barrMesaj = Encoding.ASCII.GetBytes(sMesaj);
int iLen = barrMesaj.Length;
nsClient.Write(barrMesaj,0,iLen);
Thread.Sleep(1000);
}
}
}
}

3 Nisan 2010 Cumartesi

break ve continue farkı


int[] arr = new[] {1,2,3,4,5,6};

foreach (int j in arr)
{
foreach (int i in arr)
{
if (i == 3)
{
// i for unu kırıp j forundan devam eder.
break;
}
}
}


foreach (int j in arr)
{
foreach (int i in arr)
{
if (i == 3)
{
// if içini işlemeden i forunun bir
// sonraki elemanından devam eder
continue;
}
}
}

14 Şubat 2010 Pazar

Dizinleri TreeView içinde göstermek



<asp:TreeView ID="tvKlasorler" runat="server" ImageSet="Arrows" PathSeparator="|"
ShowCheckBoxes="Leaf" >
<HoverNodeStyle Font-Underline="True" ForeColor="#5555DD" />
<SelectedNodeStyle Font-Underline="True" ForeColor="#5555DD" HorizontalPadding="0px"
VerticalPadding="0px" />
<NodeStyle Font-Names="Verdana" ForeColor="Black" HorizontalPadding="5px"
NodeSpacing="0px" VerticalPadding="0px" />
</asp:TreeView>


CODE BEHIND:

protected void Page_Load(object sender, EventArgs e)
{
TreeNode root = new TreeNode("KÖK-Root"); // EN ÜST TUTUCU

DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/"));
foreach (DirectoryInfo g in dir.GetDirectories())
{
//SVN ne Resharper klasörleri hariç
if (!f_SVNDizinimi(g) && !f_ResharperDizinimi(g) )
{
// Bu klasörü ve altındaki klasörleri Root Node'a ekle
root.ChildNodes.Add(f_GetNode(g));
}
}
tvKlasorler.Nodes.Add(root);
}

private TreeNode f_GetNode(DirectoryInfo altDizin)
{
//Bu klasörü NODE olarak oluşturalım. (Ağacın bir dalı olsun)
TreeNode tn = new TreeNode(altDizin.Name);

//Bu dalın alt dalları(klasörleri) varmı? Varsa, SVN ve RESHARPER olmayanları çekelim
DirectoryInfo[] yeniDizi = f_AltDizinleriGetir(altDizin.GetDirectories());

//Eğer alt dalları yoksa bir üst dala eklenmek üzere geri gönderelim
if (yeniDizi.Count() == 0)
{
return new TreeNode(altDizin.Name);
}
else //Eğer alt dalları varsa
{
//Alt dalların(klasörlerin) herbirini dolaşalım ve bulunduğumuz dala ekleyelim
foreach (DirectoryInfo info in yeniDizi)
{
tn.ChildNodes.Add(f_GetNode(info));
}
return tn;
}
}

private DirectoryInfo[] f_AltDizinleriGetir(DirectoryInfo[] dirs)
{
return dirs.Where(d => ((f_Dizinmi(d) && !f_Gizlimi(d) && !f_SVNDizinimi(d) && !f_ResharperDizinimi(d)))).Select(p => p).ToArray();
}

private bool f_Dizinmi(DirectoryInfo g)
{
return ((g.Attributes & FileAttributes.Directory) == FileAttributes.Directory);
}

private bool f_Gizlimi(DirectoryInfo g)
{
return ((g.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden);
}

private bool f_SVNDizinimi(DirectoryInfo g)
{
return g.Name.Equals(".svn");
}

private bool f_ResharperDizinimi(DirectoryInfo g)
{
return g.Name.Equals("_ReSharper");
}

2 Ocak 2010 Cumartesi

VS ve Java Generic Metot

Visual Studio 2008 de generic parametre alan bir metot şu şekilde:

vs

Çıktısı:

vsOut

Java’da :

java

javaout


Peki birden fazla generic tipte parametre alan metot nasıl olur?

Visual Studio 2008:

vsParam

Java’da:

javaParam

javaParam1

Java da T generic parametreleri derleme zamanında Object tipine çeviriliyor. Buna “erasure” deniyor. Hadi bir kayak:

http://java.sun.com/docs/books/tutorial/java/generics/erasure.html

Ama VS da durum bu değil. Peki ne? Bende bilmiyorum. Bilen olursa yazsın :)

Hadi birazda çıktılarına bakalım.

javaErasure vsErasure

29 Aralık 2009 Salı

Bir web sayfasının dom yapısının TreeView da gösterimi


Form1.cs

using System;
using System.Linq;
using System.Windows.Forms;

namespace wfTreeWebBrowser
{
public partial class Form1 : Form
{
public Form1() { InitializeComponent(); }

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { }

private void fTamamlandi()
{
treeView1.Nodes.Add("0", "ROOT");
for (int i = 0; i < wb.Document.All.Count; i++)
{
treeView1.Nodes["0"].Nodes.Add((++count).ToString(), wb.Document.All[i].TagName);
if (wb.Document.All[i].All.Count>0)
{
fParse(wb.Document.All[i], count.ToString());
}
}
}

private int count;
private void fParse(HtmlElement he, string key)
{
for (int i = 0; i < he.All.Count; i++)
{
if (he.All[i].All.Count>0)
{
treeView1.Nodes.Find(key,true).First().Nodes.Add((++count).ToString(), count + " * " + he.All[i].TagName);
fParse(he.All[i], count.ToString());
}
else
{
treeView1.Nodes.Find(key,true).First().Nodes.Add((++count).ToString(), count + " - " + he.All[i].OuterHtml);
}

}
}

private void button1_Click(object sender, EventArgs e)
{
fTamamlandi();
}
}
}




Form1.Designer.cs

namespace wfTreeWebBrowser
{
partial class Form1
{
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}

#region Windows Form Designer generated code
private void InitializeComponent()
{
this.wb = new System.Windows.Forms.WebBrowser();
this.treeView1 = new System.Windows.Forms.TreeView();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// wb
//
this.wb.Location = new System.Drawing.Point(12, 62);
this.wb.MinimumSize = new System.Drawing.Size(20, 20);
this.wb.Name = "wb";
this.wb.Size = new System.Drawing.Size(250, 250);
this.wb.TabIndex = 0;
this.wb.Url = new System.Uri("http://localhost/", System.UriKind.Absolute);
this.wb.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.webBrowser1_DocumentCompleted);
//
// treeView1
//
this.treeView1.Location = new System.Drawing.Point(268, 12);
this.treeView1.Name = "treeView1";
this.treeView1.Size = new System.Drawing.Size(290, 300);
this.treeView1.TabIndex = 1;
//
// button1
//
this.button1.Location = new System.Drawing.Point(12, 12);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(250, 23);
this.button1.TabIndex = 2;
this.button1.Text = "Ağaç yapısını çıkar";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(570, 464);
this.Controls.Add(this.button1);
this.Controls.Add(this.treeView1);
this.Controls.Add(this.wb);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);

}

#endregion

private System.Windows.Forms.WebBrowser wb;
private System.Windows.Forms.TreeView treeView1;
private System.Windows.Forms.Button button1;
}
}

25 Aralık 2009 Cuma

23 Aralık 2009 Çarşamba

C# Lookup ile gruplama





using System;
using System.Linq;

namespace caCop
{
class Program
{
static void Main(string[] args)
{
Ogrenci[] arrOgrenci = new Ogrenci[5];
arrOgrenci[0] = new Ogrenci() { adi = "ali", yas = 30 };
arrOgrenci[1] = new Ogrenci() { adi = "veli", yas = 30 };
arrOgrenci[2] = new Ogrenci() { adi = "mehmet", yas = 33 };
arrOgrenci[3] = new Ogrenci() { adi = "selim", yas = 33 };
arrOgrenci[4] = new Ogrenci() { adi = "yakup", yas = 33 };
foreach (Ogrenci ogrenci in arrOgrenci)
{
Console.WriteLine(ogrenci);
}

Console.WriteLine("-----");

Lookup lookup = (Lookup) (arrOgrenci.ToLookup(ob => ob.yas));
foreach (Ogrenci ogrenci in lookup[30])
{
Console.WriteLine(ogrenci);
}
}
}

class Ogrenci
{
public int yas { get; set; }
public string adi { get; set; }
public override string ToString()
{
return adi + " \t-> " + yas;
}
}
}

4 Ekim 2009 Pazar

Javada Interface

JAVA:

interface ii{
// public yazmaya gerek yok
void sayma();

// public yazabilirsinizde
public int say();

// java da interface içine
// sabit tanımlanabilir.
final int yas = 10;
}

class cc implements ii{
public int say() {
return yas; // 10 doner
}

public void sayma() {
}
}


C#:

interface ii
{
// The modifier 'public' is not valid
// for this item
public int say(); // HATALI

void sayma();

// Interfaces cannot contain fields
const int yas = 10; // HATALI
}

class cc : ii
{

public void sayma()
{
}

public int say()
{
// interface içinde field tanımlanamayacağı
// için erişilemez
return 4444;
}
}

12 Mayıs 2009 Salı

C# ile Rakamı Yazıya Çevirme

class RakamiYaziyaCevir
{
public string YaziyaCevirENG(int _iSayi, string _sAyrac)
{
if (_sAyrac == null || _iSayi.ToString().IndexOf(_sAyrac.ToCharArray()[0]) == -1)
{
return YaziyaCevirTR(_iSayi);
}

string[] sSayilar = _iSayi.ToString().Split(_sAyrac.ToCharArray());
return YaziyaCevirTR(Convert.ToInt32(sSayilar[0])) + YaziyaCevirTR(Convert.ToInt32(sSayilar[1]));

}


public string YaziyaCevirENG(int _iSayi)
{
string[] Birler = { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
string[] Onlar = { "", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
string[] Yuzler = { "", "OneHundred", "TwoHundred", "ThreeHundred", "FourHundred", "FiveHundred", "SixHundred", "SevenHundred", "EigthHundred", "NineHundred" };
string[] Binler = { "Trilyon", "Milyar", "Milyon", "Thousand", "" };

string[] Dizi = new string[15];
string[] Uc_hane = new string[3];
string Yazi = "";
string Sonuc = "";

string Sayi_str;
Sayi_str = _iSayi.ToString();
Sayi_str = "000000000000000" + Sayi_str;
Sayi_str = Sayi_str.Substring(_iSayi.ToString().Length, 15);

for (int i = 0; i < Sayi_str.Length; i++)
{
Dizi[i] = Sayi_str[i].ToString();
}

for (int i = 0; i < 5; i++)
{
Uc_hane[0] = Dizi[(i * 3) + 0];
Uc_hane[1] = Dizi[(i * 3) + 1];
Uc_hane[2] = Dizi[(i * 3) + 2];

if (Uc_hane[0] == "0")
{
Yazi = "";
}
else if (Uc_hane[0] == "1")
{
Yazi = "OneHundred";
}
else
{
Yazi = Birler[Convert.ToInt16(Uc_hane[0])] + "Hundred";
}

Yazi = Yazi + Onlar[Convert.ToInt16(Uc_hane[1])] + Birler[Convert.ToInt16(Uc_hane[2])];

if (Yazi != "")
Yazi = Yazi + Binler[i];

if ((i == 2) && (Yazi == "OneThousand"))
{
Yazi = "Thousand";
}

Sonuc += Yazi;

}

return Sonuc;
}

//-------------------------------------------------------

public string YaziyaCevirTR(int _iSayi, string _sAyrac)
{
if (_sAyrac == null || _iSayi.ToString().IndexOf(_sAyrac.ToCharArray()[0]) == -1)
{
return YaziyaCevirTR(_iSayi);
}

string[] sSayilar = _iSayi.ToString().Split(_sAyrac.ToCharArray());
return YaziyaCevirTR(Convert.ToInt32(sSayilar[0])) + YaziyaCevirTR(Convert.ToInt32(sSayilar[1]));

}

public string YaziyaCevirTR(int _iSayi)
{
string[] Birler = { "", "Bir", "İki", "Üç", "Dört", "Beş", "Altı", "Yedi", "Sekiz", "Dokuz" };
string[] Onlar = { "", "On", "Yirmi", "Otuz", "Kırk", "Elli", "Altmış", "Yetmiş", "Seksen", "Doksan" };
string[] Yuzler = { "", "Yüz", "İkiYüz", "ÜçYüz", "DörtYüz", "BeşYüz", "AltıYüz", "YediYüz", "SekizYüz", "DokuzYüz" };
string[] Binler = { "Trilyon", "Milyar", "Milyon", "Bin", "" };

string[] Dizi = new string[15];
string[] Uc_hane = new string[3];
string Yazi = "";
string Sonuc = "";

string Sayi_str;
Sayi_str = _iSayi.ToString();
Sayi_str = "000000000000000" + Sayi_str;
Sayi_str = Sayi_str.Substring(_iSayi.ToString().Length, 15);

for (int i = 0; i < Sayi_str.Length; i++)
{
Dizi[i] = Sayi_str[i].ToString();
}

for (int i = 0; i < 5; i++)
{
Uc_hane[0] = Dizi[(i * 3) + 0];
Uc_hane[1] = Dizi[(i * 3) + 1];
Uc_hane[2] = Dizi[(i * 3) + 2];

if (Uc_hane[0] == "0")
{
Yazi = "";
}
else if (Uc_hane[0] == "1")
{
Yazi = "Yüz";
}
else
{
Yazi = Birler[Convert.ToInt16(Uc_hane[0])] + "Yüz";
}

Yazi = Yazi + Onlar[Convert.ToInt16(Uc_hane[1])] + Birler[Convert.ToInt16(Uc_hane[2])];

if (Yazi != "")
Yazi = Yazi + Binler[i];

if ((i == 2) && (Yazi == "BirBin"))
{
Yazi = "Bin";
}

Sonuc += Yazi;

}

return Sonuc;
}
}

15 Aralık 2008 Pazartesi

Visual Studio Debugger özellikleri

'DebuggerDisplay' is not valid on this declaration type. It is only valid on 'assembly, class, struct, enum, property, indexer, field, delegate' declarations.

'DebuggerHidden' is not valid on this declaration type. It is only valid on 'constructor, method, property, indexer' declarations.

'Debuggable' is not valid on this declaration type. It is only valid on 'assembly, module' declarations.

'DebuggerNonUserCode' is not valid on this declaration type. It is only valid on 'class, struct, constructor, method, property, indexer' declarations.

VS.NET içinden hızlıca google araması yapabilmek


ref:http://www.codinghorror.com/blog/archives/000429.html

    1 Imports System


    2 Imports EnvDTE


    3 Imports EnvDTE80


    4 Imports EnvDTE90


    5 Imports System.Diagnostics


    6 Imports System.Web


    7 


    8 


    9 Public Module Module1


   10 


   11     Public Sub SearchGoogleForSelectedText()


   12         Dim s As String = ActiveWindowSelection().Trim()


   13         If s.Length > 0 Then


   14             DTE.ItemOperations.Navigate("http://www.google.com/search?q=" & _


   15                 Web.HttpUtility.UrlEncode(s))


   16         End If


   17     End Sub


   18 


   19     Private Function ActiveWindowSelection() As String


   20         If DTE.ActiveWindow.ObjectKind = EnvDTE.Constants.vsWindowKindOutput Then


   21             Return OutputWindowSelection()


   22         End If


   23         If DTE.ActiveWindow.ObjectKind = "{57312C73-6202-49E9-B1E1-40EA1A6DC1F6}" Then


   24             Return HTMLEditorSelection()


   25         End If


   26         Return SelectionText(DTE.ActiveWindow.Selection)


   27     End Function


   28 


   29     Private Function HTMLEditorSelection() As String


   30         Dim hw As HTMLWindow = ActiveDocument.ActiveWindow.Object


   31         Dim tw As TextWindow = hw.CurrentTabObject


   32         Return SelectionText(tw.Selection)


   33     End Function


   34 


   35     Private Function OutputWindowSelection() As String


   36         Dim w As Window = DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput)


   37         Dim ow As OutputWindow = w.Object


   38         Dim owp As OutputWindowPane = ow.OutputWindowPanes.Item(ow.ActivePane.Name)


   39         Return SelectionText(owp.TextDocument.Selection)


   40     End Function


   41 


   42     Private Function SelectionText(ByVal sel As EnvDTE.TextSelection) As String


   43         If sel Is Nothing Then


   44             Return ""


   45         End If


   46         If sel.Text.Length = 0 Then


   47             SelectWord(sel)


   48         End If


   49         If sel.Text.Length <= 2 Then


   50             Return ""


   51         End If


   52         Return sel.Text


   53     End Function


   54 


   55     Private Sub SelectWord(ByVal sel As EnvDTE.TextSelection)


   56         Dim leftPos As Integer


   57         Dim line As Integer


   58         Dim pt As EnvDTE.EditPoint = sel.ActivePoint.CreateEditPoint()


   59 


   60         sel.WordLeft(True, 1)


   61         line = sel.TextRanges.Item(1).StartPoint.Line


   62         leftPos = sel.TextRanges.Item(1).StartPoint.LineCharOffset


   63         pt.MoveToLineAndOffset(line, leftPos)


   64         sel.MoveToPoint(pt)


   65         sel.WordRight(True, 1)


   66     End Sub


   67 


   68 End Module


   69 




Şimdi nasıl yapacağız:
  1. "VS.NET -> Tools -> Macros -> New Macro Project" açılan ekranda herşeyi seçin ve, yukarıdaki kodu yapıştırın
  2. (Yeni modul oluştu ve adı Module1, siz keyfinize göre değiştirin)
  3. "Add References" ile "System.Drawing.dll" ve "System.Web.dll" eklenir ve kaydedilerek bu IDE den çıkılır.
  4. Google da aramalarınıza kısayol eklemek için "Tools -> Options -> Environment -> Keyboard" tıklarından geçip "Show command containing string" alanına "google" yazın gelsin macromuz.
  5. "Shortcut for selected command" altına tıklayıp dilediğiniz kısayol tuşunu oluşturun ve hayrını görün :)

DebuggerNonUserCode



/// <summary>


/// DebuggerNonUserCode : Tüm sınıfın debug edilmesini önler


/// </summary>


[DebuggerNonUserCode]


public class ornekClass


{


    ..


    ...


}


11 Aralık 2007 Salı

DataGrid e kod ile TEMPLATECOLUMN eklemek

Bu aslında hafif bir çeviri olacak.Ama önemli ve geyik olmayan yerler için zamanım var.
Adresimiz: http://www.tek-tips.com/faqs.cfm?fid=4868

ITemplate Interface Hakkında...

Template kolonu çalışma zamanında oluşturmak çok kolaydır. Genel şekli aşağıdaki gibidir:
------------------
TemplateColumn tc = new TemplateColumn();
tc.HeaderText = [Text of column header];
tc.ItemTemplate = [ITemplate type];
// dg is the DataGrid control
dg.Columns.Add(tc);
------------------

Yukarıda da gördüğünüz gibi, basitçe TemplateColumn değişkeni üretebilir, Text ve ItemTemplate özelliklerini verebiliriz.Devam edelim.Önemli kısmı ItemTemplate özelliğidir. Gördğünüz gibi bir sınıf tanımlamalı ItemTemplate Interface inden türeyen.Böylece template column u üretip gride eklemek mümkün olacaktır.Thus, adding a template column to a grid at run time will consist of creating a class that implements the ITemplate interface. Bu sınıfın nasıl olduğunu şimdi göreceğiz.

Şimdi, ITempalte interface'nin sadece bir tane metodu vardır, InstantieateIn adında.Bu metod yeni bir örnek template kolon üretildiğinde çalışacaktır.System.Web.UI.Control tipinde bir parametre alır . Böylece bu metodu ile örneklediğiniz nesneyi oluşturduğunuz yerde template column create olmuş olur.(cümle berbat oldu ama idare edin). Benim durumumda bir check box a ihtiyacım olacak template columnun içinde ve sınıfım şöyle görünecek:

private class CheckBoxTemplate : ITemplate
{
// Implementation of ITemplate
public void InstantiateIn(System.Web.UI.Control container)
{
// Create a check box
CheckBox cb = new CheckBox();
// Make the check box appear in the column
container.Controls.Add(cb);
}
}


Hepsi bu! Bu template column oluşturmak için ihtiyacınız olan kod. Düşündüğünüz gibi, sizde text box ın özelliklerini set ettiğiniz gibi her ne kontrol oluşturuyorsanız template column içinde, onunda özelliklerini dilediğiniz gibi set edebilirsiniz. Yanı sıra, sadece bir kontrol kullanmaklada sınırlı değilsiniz. Dilediğiniz sayıda Template Column içine nesneler create edebilirsiniz(create etmek ne demekse) ...


Data Biding (veri bağlama)
Fakat hepsi bu değil! InstantiateIn metodu içinde veri çekmek ve kontrolonüze bağlamak mümkün. Veri bağlamayı uyarlamak, create ettiğiniz kontrolünüzün DataBinding olayına kod yazmakla mümkün olacak. Event handling(olaylarla başa çıkma) mekanizması Web ve Windows formlarındakiyle aynıdır: Bir metod create edersiniz aynı olayın temsilcisinin imzasıyla(isaretiyle) ve sonra temsilciye metodu eklersiniz. Sınıfınızın son hali kalın kısımla gösterilmiş:
[Yani diyorki bir metodu oluşturup DataBinding metoduymuş gibi sınıfınıza eklersiz. İşte yeni metodunuz,BindCheckBox ve bunu DataBinding işlemi halinde çalışması için sınıfınıza ekliyorsunuz...]

CODE

private class CheckBoxTemplate : ITemplate
{
public void InstantiateIn(System.Web.UI.Control
container)
{
// Create a check box
CheckBox cb = new CheckBox();
//Attach method to delegate
cb.DataBinding += new System.EventHandler(this.BindCheckBox);
container.Controls.Add(cb);
}

//Method that responds to the
DataBinding event

private void BindCheckBox(object sender, System.EventArgs e)
{
CheckBox cb = (CheckBox)sender;
DataGridItem container = (DataGridItem)cb.NamingContainer;
cb.Checked = [Data binding expression];
}
}
Gördüğünüz gibi, InstantiateIn metoduna yeni bir satır kod eklendi:

cb.DataBinding += new System.EventHandler(this.BindCheckBox);

Tüm bu eklemeler checkbox kontrolümüzün DataBinding event ında BindCheckBox methodunu çalıştırmak içindi. DataBinding event temsilcisinin iki parametresi vardır: object tipinde sender, ve EventArgs tipinde e,(Gerçekten bir databinding e ihtiyacımız yok). sender, harektin başladığı check box nesnesini gösterir , ve bu yüzden aşağıdaki koda ihtiyacımız vardır:

CheckBox cb = (CheckBox)sender;

Basitçe CheckBox gibi bir referansı getirir. Şimdi check boxın NamingContainer özelliği CheckBox kontrolünün olduğu DataGridItem(diğer bir değişle, satır(row)) u gösterir. Böylece Böylece aşağıdaki satırda grid içinde CheckBox ın olduğu satıra ulaşabiliriz:

DataGridItem container = (DataGridItem)cb.NamingContainer;

Sonuçta, &quot;ItemID&quot; adında bir veri kaynağından çektiği veriyi gösteren bir DataGrid imiz olduğunu farzedersek, veri bağlama ifadesini DataBinder.Eval metodunu kullanarak yazabiliriz. Aşağıdaki satırda(yukarıdaki kod olmayan) CheckBox ın Checked özelliğini, eper "ItemId" veri kaynağında 10 ise True olarak set edecektir.


cb.Checked = (DataBinder.Eval(container.DataItem, "ItemID").ToString() == "10";);

Bu durumda Eval metodunun ne olduğunu bilmiyorsunuz.DataGridItem(DataGrid içinde bir row demektir DataGridItem) içerisinde row içerisindeki bir alanın değerini, object tipinde döndüren bir metoddur. Elbette verilerinizi bağlayan ifadeniz daha karmaşık olabilir.Bu metodda dilediğiniz şeyi yapabilirsiniz...

Son olarak kalın ile yazılmış hali ile ItemTemplate inizi Template Column kısmına ekleyebilirsiniz.

TemplateColumn tc = new TemplateColumn();
tc.HeaderText = [Text of column header];
//Isn't this beautiful?
tc.ItemTemplate = new CheckBoxTemplate();
// dg is the DataGrid control
dg.Columns.Add(tc);

Cool, eh?