Kullandığım genişletme metotlarım

Programlarımda, web sitelerimde kullandığım genişletme metotlarım (extension methods)

Sizlerle web sitelerimde kullandığım Genişletme Metotlarımı paylaşmak istedim.

Genişletme metotları (Extension methods), C# 3.0 ile hayatımıza giren güzel bir özelliktir. En yalın olarak, var olan tiplerin/nesnelerin yapısını bozmadan bunlara ek özellik kazandırmaktadır.

Örnek vermek gerekirse, programlarımızda yoğun olarak kullandığımız bir metot vardır: Convert.ToInt32(). Biz bir stringi ne zaman sayıya çevirmek istesek şunun gibi bir kod kullanırız:

int sayi = Convert.ToIn32(txtSayi.Text);

İşte Genişletme metotları bu gibi durumlarda devreye giriyor, yukarıdaki kodu aşağıdaki gibi kim yazmak istemez ki?

int sayi = txtSayi.Text.ToInt32();

Genişletme metodunun hazırlanması da bir o kadar kolay, static bir sınıf içerisine, statik bir metod ekliyorsunuz, metodun ilk parametresini this ile işaretliyorsunuz (bu parametre, metodun hangi tip/nesne üzerinde çalışacağını belirtir)

Hemen ToInt32() metodunu göstereyim:

public static class GenelIslemler
{
  public static int ToInt32(this object sayi)
    {
        try
        {
            if (sayi == null) throw new Exception();
            int x = Convert.ToInt32(sayi);
            return x;
        }
        catch (Exception)
        {
            return 0;
        }
    }
}

Diğer Genişletme metotlarımı da teker teker göstereyim, merak etmeyin sayfanın altında download linkini bulacaksınız :)

1) Bir stringin içerisinde a-z, A-Z,0-9 hariç diğer tüm karakterleri temizleme:

 public static string ToOnlyCharacters(this string s)
    {
        s = s.Trim();
        if (string.IsNullOrEmpty(s)) return "";
        Regex r = new Regex("[^a-zA-Z0-9]");
        s = r.Replace(s, "");
        return s;
    }

2) Akıllı URL üretmek için bir stringi URL formatına dönüştürme:

public static string ToURL(this string s)
    {
        if (string.IsNullOrEmpty(s)) return "";
        if (s.Length > 80)
            s = s.Substring(0, 80);
        s = s.Replace("ş", "s");
        s = s.Replace("Ş", "S");
        s = s.Replace("ğ", "g");
        s = s.Replace("Ğ", "G");
        s = s.Replace("İ", "I");
        s = s.Replace("ı", "i");
        s = s.Replace("ç", "c");
        s = s.Replace("Ç", "C");
        s = s.Replace("ö", "o");
        s = s.Replace("Ö", "O");
        s = s.Replace("ü", "u");
        s = s.Replace("Ü", "U");
        s = s.Replace("'", "");
        s = s.Replace("\"", "");
        Regex r = new Regex("[^a-zA-Z0-9_-]");
        s = r.Replace(s, "-");
        if (!string.IsNullOrEmpty(s))
            while (s.IndexOf("--") > -1)
                s = s.Replace("--", "-");
        if (s.StartsWith("-")) s = s.Substring(1);
        if (s.EndsWith("-")) s = s.Substring(0, s.Length - 1);
        return s;
    }

3) Bir stringi verilen miktarda karakterler barındıracak şekilde satırlara bölme:

public static string ToMultiLineString(this string str,int adet)
    {
        string yeni = "";
        for (int i = 0; i < str.Length; i += adet)
        {
            if (i > 0)
                yeni += "<br/>";
            if (i + adet < str.Length)
                yeni += str.Substring(i, adet);
            else
                yeni += str.Substring(i);
        }
        return yeni;
    }

4) Bir bilginin sayı olup olmadığını test etme:

 public static bool IsInteger(this Object sayi)
    {
        try
        {
            if (sayi == null) throw new Exception();
            Convert.ToInt32(sayi);
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }

5) Bir bilgiyi sayıya çevirme: 

(Siz isterseneniz catch'te hata fırlatabilirsiniz)

 public static int ToInt32(this object sayi)
    {
        try
        {
            if (sayi == null) throw new Exception();
            int x = Convert.ToInt32(sayi);
            return x;
        }
        catch (Exception)
        {
            return 0;
        }
    }

6) Tarihi formatlı bir stringe çevirme:

  public static String TarihYaz(DateTime tarih, bool full)
    {
        if (full) return TarihYaz(tarih);
        //DateTime tarih = Convert.ToDateTime(obj);
        DateTime simdi = DateTime.Now;
        String s;

        if (simdi.Date == tarih.Date)
            s = "Bugün";
        else if (tarih.Date.AddDays(1.0).Date == simdi.Date)
            s = "Dün";
        else
            s = String.Format("{0:00}.{1:00}.{2}", tarih.Day, tarih.Month, tarih.Year);

        return s.ToString();
    }

 

 public static String TarihYaz(DateTime tarih)
    {
        //DateTime tarih = Convert.ToDateTime(obj);
        DateTime simdi = DateTime.Now;
        String s;
        if (tarih.Hour == 0 && tarih.Minute == 0 && tarih.Second == 0)
        {
            if (simdi.Date == tarih.Date)
                s = "Bugün";
            else if (tarih.Date.AddDays(1.0).Day == simdi.Date.Day)
                s = "Dün";
            else
                s = String.Format("{0:00}.{1:00}.{2}", tarih.Day, tarih.Month, tarih.Year);
        }
        else
        {
            if (simdi.Date == tarih.Date)
                s = String.Format("Bugün {0:00}:{1:00}", tarih.Hour, tarih.Minute);
            else if (tarih.Date.AddDays(1.0).Day == simdi.Date.Day)
                s = String.Format("Dün {0:00}:{1:00}", tarih.Hour, tarih.Minute);
            else
                s = String.Format("{0:00}.{1:00}.{2} {3:00}:{4:00}", tarih.Day, tarih.Month, tarih.Year, tarih.Hour, tarih.Minute);
        }
        return s.ToString();
    }

7) Textboxlardan alınan bilgileri temizleme

 public static String ToClearText(this String s, bool satirSonu)
    {
        s = s.Replace("<", "&lt;");
        s = s.Replace(">", "&gt;");
        s = s.Replace("script", "scr_ipt");
        s = s.Replace("'", "`");
        s = s.Replace("\"", "`");

        if (satirSonu)
            s = s.Replace(Environment.NewLine, SatirSonu);
        s = s.Trim();
        return s;
    }

 

 public static String ToClearText(this String s)
    {
        s = ToClearText(s, false);
        return s;
    }

8) Bir stringteki html satır sonlarını (<br/> <=> EOL) dosya satır sonuna çevirme:

(ve tersi)

public const string SATIRSONU = "<br />";

public static String NewLine2BR(this String s)
    {
        s = s.Replace(Environment.NewLine, SATIRSONU);
        return s;
    }
public static String BR2NewLine(this String s)
    {
        s = s.Replace(SATIRSONU, Environment.NewLine);
        return s;
    }

9) Bilgileri tarih be bool tiplerine dönüştürme:

public static DateTime ToDateTime(this string s)
    {
        try
        {
            return Convert.ToDateTime(s);
        }
        catch (Exception)
        {
            return DateTime.MinValue;
        }
    }

public static bool ToBoolean(this object s)
    {
        try
        {
            return Convert.ToBoolean(s);
        }
        catch (Exception)
        {
            return false;
        }
    }

10) Image nesnelerini orantılı bir şekilde küçültme: 

Favorimdir :)

public static void Boyutlandir(this System.Web.UI.WebControls.Image image, int MaxWidth, int MaxHeight)
    {
        System.Drawing.Image img = null;
        try
        {
            if (image.ImageUrl.StartsWith("http://") || image.ImageUrl.StartsWith("https://"))
                img = System.Drawing.Image.FromStream(new System.Net.WebClient().OpenRead(image.ImageUrl));
            else
                img = System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Server.MapPath(image.ImageUrl));

            if (img.Width > MaxWidth || img.Height > MaxHeight)
            {
                double widthRatio = 1.0;
                if ((int)MaxWidth > 0)
                    widthRatio = (double)img.Width / (double)MaxWidth;

                double heightRatio = 1.0;
                if ((int)MaxHeight > 0)
                    heightRatio = (double)img.Height / (double)MaxHeight;

                double ratio = Math.Max(widthRatio, heightRatio);
                int newWidth = (int)(img.Width / ratio);
                int newHeight = (int)(img.Height / ratio);

                image.Width = Unit.Pixel(newWidth);
                image.Height = Unit.Pixel(newHeight);
            }
        }
        catch (Exception)
        {

        }
        finally
        {
            if (img != null)
                img.Dispose();
        }

    }

11) Bir stringin solundan X adet karakter alma:

public static string SoldanMetinAl(this string metin, int uzunluk)
    {
        if (metin.Length < uzunluk)
            return metin;
        else
            return metin.Substring(0, uzunluk) + "..";
    }

12) Bir bilginin tarih olup olmadığının testi:

public static bool IsDate(this string tarih)
    {
        try
        {
            if (tarih == null) throw new Exception();
            Convert.ToDateTime(tarih);
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }

13) Bir bilginin geçerli bir email adresi / URL olup olmadığıın testi:

public static bool IsEmail(this string inputEmail)
    {
        if (string.IsNullOrEmpty(inputEmail)) return false;
        string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                          @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                          @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
        Regex re = new Regex(strRegex);
        if (re.IsMatch(inputEmail))
            return (true);
        else
            return (false);
    }

 

public static bool IsURL(this string str)
    {
        Regex r = new Regex(@"(ftp|http|https)://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?");
        return r.IsMatch(str);
    }

 


Yukarıdaki tüm metotları ve bonus birkaç metodu daha indirmek için tıklayınız.

Herkese kolay gelsin :)