6 Kasım 2020 Cuma

Design Patterns - 1 - Singleton (Türkçe ve İngilizce)

Exported from Notepad++
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestsWithConsoleApp { // Genelde, singleton'lar ilk ihtiyaçları olduğu zaman çağrılırlar // (instantiation ilk ihtiyaç olunan zamanda gerçekleşir). // Generally, singletons are called when they are needed // instantiation occurs when they are needed first time. // It's called lazy construction. // Creating more than one instances can be a problem in terms // of performance. In these circumstances, we use singleton pattern. // How to ensure that one class has one and only instance? // How to use this unique instance easily? // With singleton, we can find solutions to these questions: // How a class can control of it's intantiation? // How to limit the amount of instantiations of given class? // How to prevent other users to instantiate any other instances? // Sırasıyla: // Class'ın constructor'ı gizlenir (private) // public static bir metot oluşturulur; bu // metot class'ın instance'ını oluşturur // Dışarıdan direk constructor kullanılarak bir // initialization yapılamaz. Yani şu yapılamaz: // SingletonClass singletonClass = new SingletonClass(); // Instance ancak bir metot üzerinden çağrılabilir, // çünkü constructor'a direkt erişim yoktur. // Bu pattern'de ana fikir, bir instance'dan // daha fazlasının üretilmesinin önlenmesi ve // üretilen bu tek instance'ın initialization'ının // class içinde kontrol edilmesidir. class Program { public class Singleton { private static Singleton SingletonObject = new Singleton(); public static int Number = 0; private Singleton() { Number++; Console.WriteLine("Constructor çalışıyor. Kaç kez çalıştı? :" + Number); // Constructor'ın sadece 1 kez çalışmış olduğunu görmüş olduk. } // Burada görüldüğü üzere parametre almayan // constructor'ımızı private yaptık. // Artık Singleton class'ı, bu constructor'ı // kullanarak instantiate edilemez. // Yani şunu yapamayız: Singleton singleton = new Singleton(); public static Singleton ReturnSingletonObject() { return SingletonObject; } public void ShowSomething() { Console.WriteLine("Something"); } } static void Main() { var singleton1 = Singleton.ReturnSingletonObject(); var singleton2 = Singleton.ReturnSingletonObject(); var singleton3 = Singleton.ReturnSingletonObject(); // görünüşte üç değişken oluşturup kullanmış olsak da; // aslında toplamda sadece 1 obje ürettik. // constructor'ın 1 kez çalışmış olmasından bunu anlamış olduk. // Bildiğimiz üzere bir class'tan instantiation işlemi // yapılırken constructor çalışıyor. // Singleton'da amacımız en fazla tek bir obje ( // instance of a class) üretmekti. // Birden fazla objenin üretilmesi engellenmeliydi. // (In software engineering, the singleton pattern is a // software design pattern that restricts the instantiation // of a class to one "single" instance. This is useful when // exactly one object is needed to coordinate actions across the system. // The term comes from the mathematical concept of a singleton.) // Biz de bunu yaptık. Constructor sadece // ilk initialization'da çalıştı (singleton1 için). // singleton2 ve singleton3 için herhangi bir şekilde // constructor'a gidilmedi/instance oluşturulmadı. singleton1.ShowSomething(); singleton2.ShowSomething(); singleton3.ShowSomething(); Console.ReadKey(); // Singleton SingletonObject = new Singleton(); // Yukarıda da bahsettiğimiz gibi, parametresiz // constructor'ı private yaptığımız için class'tan // bu şekilde bir instantiation yapamayız. // Singleton'ı anti-pattern olarak addeden developer'lar vardır. // An anti-pattern is a common response to a // recurring problem that is usually ineffective and risks // being highly counterproductive.[1][2] The term, coined in 1995 // by Andrew Koenig,[3] was inspired by a book, Design Patterns, // which highlights a number of design patterns in // software development that its authors considered to be // highly reliable and effective. } } } // Farklı şekilde singleton: // örneklerin birinde metot, birinde property // kullandığımıza dikkat: csharp'ta bu pattern kullanılırken // instance oluşturma işlemi hem property kullanılarak, // hem metot kullanılarak uygulanmaktadır, ikisinden birisi seçilebilir) public class Singleton { private static Singleton _instance; // initialization'u görüldüğü gibi yukarıdaki satırda yapmıyoruz. // if statement içinde yapıyoruz; // şayet daha öncesinde initialization yapılmamışsa tabi... public int Number { get; set; } private Singleton() { Number++; Console.WriteLine("Constructor çalışıyor. Kaç kez çalıştı? :" + Number); } public static Singleton GetSingletonInstance { get { if (_instance == null) { _instance = new Singleton(); return _instance; } return _instance; } } public void ShowSomething() { Console.WriteLine("Something"); } } static void Main() { var singleton1 = Singleton.GetSingletonInstance; var singleton2 = Singleton.GetSingletonInstance; var singleton3 = Singleton.GetSingletonInstance; singleton1.ShowSomething(); singleton2.ShowSomething(); singleton3.ShowSomething(); Console.ReadKey(); }

3 Kasım 2020 Salı

Data Annotations Örnek Kod Parçası


using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace ConsoleAppErenOzten { public class Kisi { [Required(ErrorMessage = "{0} gereklidir.")] [StringLength(50, MinimumLength = 3, ErrorMessage = "Minimum 3, maksimum 50 karakter giriniz.")] [DataType(DataType.Text)] public string Ad { get; set; } [Required(ErrorMessage = "{0} gereklidir.")] [StringLength(50, MinimumLength = 3, ErrorMessage = "Minimum 3, maksimum 50 karakter giriniz.")] [DataType(DataType.Text)] public string Soyad { get; set; } [DataType(DataType.PhoneNumber)] [Phone] public string Telefon { get; set; } [DataType(DataType.EmailAddress)] [EmailAddress] public string Email { get; set; } } class Program { static void Main(string[] args) { var kisi = new Kisi(); kisi.Ad = "Eren"; // Boş bir string değeri atanıyor: kisi.Soyad = ""; kisi.Telefon = "3652978130"; kisi.Email = "eren@gmail.com"; ValidationContext context = new ValidationContext(kisi, null, null); var validationResults = new List<ValidationResult>(); // Aşağıdaki satırda, eğer hatalar oluşmuşsa, // bu hatalar validationResults listesine ekleniyor. // Üçüncü parametreyi inceleyiniz: bool valid = Validator.TryValidateObject(kisi, context, validationResults, true); if (!valid) { foreach (ValidationResult validationResult in validationResults) { Console.WriteLine("{0}", validationResult.ErrorMessage); } } Console.ReadKey(); } } }

27 Ekim 2020 Salı

SortedList kullanımı - C#

using System; using System.Collections; namespace CodeInConsole { public class Solution { public static void Main() { Console.WriteLine(""); Console.WriteLine("---"); Console.WriteLine("SortedList1 örneği"); Console.WriteLine("---"); Console.WriteLine(""); // Creates and initializes a new SortedList. SortedList sortedList = new SortedList(); sortedList.Add("Third", "!"); sortedList.Add("Second", "World"); sortedList.Add("First", "Hello"); // Displays the properties and values of the SortedList. Console.WriteLine(" Count: {0}", sortedList.Count); Console.WriteLine(" Capacity: {0}", sortedList.Capacity); Console.WriteLine(" Keys and Values:"); PrintKeysAndValues(sortedList); } public static void PrintKeysAndValues(SortedList myList) { // \t --> empty space yapıyor, tab'a basılıp yazmaya başlanmış gibi. Console.WriteLine("\t-KEY-\t-VALUE-"); for (int i = 0; i < myList.Count; i++) { Console.WriteLine("\t{0}:\t{1}", myList.GetKey(i), myList.GetByIndex(i)); } Console.WriteLine(""); Console.WriteLine("---"); Console.WriteLine("SortedList2 örneği"); Console.WriteLine("---"); Console.WriteLine(""); SortedList sortedList2 = new SortedList(); // sortedList kapasitesi şu an 0 Console.WriteLine("Capacity: " + sortedList2.Capacity); sortedList2.Add("key1", "val1"); sortedList2.Add("key2", "val2"); sortedList2.Add("key3", "val3"); // sortedlist kapasitesi şu an 16 (veri eklendikten // sonra otomatik olarak 16'ya çıktı) Console.WriteLine("Capacity: " + sortedList2.Capacity); // System.InvalidOperationException: 'Failed to compare two // elements in the array.' ArgumentException: Object must be of type String. // sortedList2.Add(2, 5); // System.InvalidOperationException: 'Failed to compare // two elements in the array.' ArgumentException: Object must be of type String. //sortedList2.Add(true, false); // Ayrıca: key'ler özel olmalıdır. Aynı isimde // iki key değeri girilemiyor, hata veriyor. for (int i = 0; i < sortedList2.Count; i++){ Console.WriteLine("Key: " + sortedList2.GetKey(i) + "\t" + "Value: " + sortedList2.GetByIndex(i)); } Console.WriteLine(""); Console.WriteLine("---"); Console.WriteLine("SortedList3 örneği"); Console.WriteLine("---"); Console.WriteLine(""); SortedList sortedList3 = new SortedList(); sortedList3.Add(true, false); sortedList3.Add(false, true); // Yukarıda bool type'lar eklendi sortedList3'e. // Aşağıda ise aynı listeye string eklendiğinde hata oluşuyor: // System.InvalidOperationException: // 'Failed to compare two elements in the array.' //sortedList3.Add("text1", "text2"); for (int i = 0; i < sortedList3.Count; i++) { Console.WriteLine("Key: " + sortedList3.GetKey(i) + "\t" + "Value: " + sortedList3.GetByIndex(i)); } } } }