public static void UseDelegate() { var photoProc = new PhotoProcessor(); var filters = new PhotoFilters(); Action <Photo> filterHandler = filters.ApplyBrightness; filterHandler += filters.ApplyContrast; filterHandler += RemoveRedEye; photoProc.Process("photo.jpg", filterHandler); }
static void UsingDelegates() { var processor = new PhotoProcessor(); var filters = new PhotoFilters(); Action <Photo> filterHandler = filters.ApplyBrightness; filterHandler += filters.ApplyContrast; filterHandler += RemoveRedEyeFilter; processor.Process("photo.jpg", filterHandler); }
static void Main(string[] args) { var processor = new PhotoProcessor(); var photoFilters = new PhotoFilters(); Action <Photo> handler = photoFilters.ApplyBrightness; handler += photoFilters.ApplyContrast; handler += photoFilters.Resize; handler += CustomFilter; processor.Process("photo.jpeg", handler); }
static void Main(string[] args) { var processor = new PhotoProcessor(); var photoFilters = new PhotoFilters(); //PhotoProcessor.PhotoFilterHandler filterHandler = photoFilters.ApplyBrightness; Action <Photo> filterHandler = photoFilters.ApplyBrightness; filterHandler += photoFilters.ApplyContrast; filterHandler += photoFilters.Resize; filterHandler += RemoveRedEyes; processor.Process("photo.jpeg", filterHandler); }
private void Delegates() { /* * DELEGATES : * is object that know how to call a method (or group of method) * is refrence to a function (or pointer to a function) */ var photoProcessor = new PhotoProcessor(); var filter = new FilterHandler(); PhotoProcessor.PhotoFilterHandler delegatedFilter = filter.ApplyContrast; delegatedFilter += filter.ApplyBrightness; delegatedFilter += filter.Resize; photoProcessor.Process("images.jpg", delegatedFilter); }
//public string[] Filter { get; set; } public void Delegates() { var processor = new PhotoProcessor(); var filters = new PhotoFilters(); var p = new Photo(); //p.PhotoMessage = "Applying Filters"; //p.PhotoMessage += _NewLine; TextAreaBody = "Adding Filters to filterHandler Delegate \n"; PhotoProcessor.PhotoFilterHandler filterHandler = filters.AppllyBrightness; filterHandler += filters.ApplyContrast; filterHandler += RemoveRedEyeFilter; TextAreaBody += p.PhotoMessage; TextAreaBody += "Running Photo Processor to process filters \n"; TextAreaBody = processor.Process("photo.jpg", filterHandler, TextAreaBody); }
//LD TEST007 - delegates private static void Test007() { //STEP001 this in a class with methods var filters = new photoFilter(); //STEP002 as a first step I'm assigning the method "ApplyBrightness" to the delegate "Action<Photo>". They both have the same signature. //note that "ApplyBrightness" takes in input the same type specified in the delegate Action <Photo> filterHandler = filters.ApplyBrightness; //STEP003 adding to the delegate a second method with identical signature filterHandler += filters.ApplyContrast; //STEP004 then I pass to an instance to a dummy class my delegate var aPhotoProcessorInstance = new PhotoProcessor(); aPhotoProcessorInstance.Process(filterHandler); }
public static void RunDelegate() { var processor = new PhotoProcessor(); PhotoFilters filters = new PhotoFilters(); // these are like callback functions that will be passed // on the filterHandler call inside the process function // similar to js callback functions Action <Photo> filterHandler = filters.ApplyBrightness; // add another delegate filterHandler += filters.ApplyContrast; filterHandler += RemoveRedEyeFilter; processor.Process("photo.jpeg", filterHandler); }
static void Main(string[] args) { var processor = new PhotoProcessor(); PhotoProcessor.PhotoFilterHandler filterHandler; PhotoFilters filters = new PhotoFilters(); filterHandler = filters.ApplyBrightness; MyCustomFilter myCustomFilter = new MyCustomFilter(); filterHandler += myCustomFilter.MyCustomFilterMethod; processor.Process("path da foto", filterHandler); Console.Read(); }
public void Execute() { /* * An object that knows how to call a method (or a group of methods) * A reference to a function * For designing extensible and flexible applications */ var processor = new PhotoProcessor(); var filters = new PhotoFilters(); PhotoProcessor.PhotoFilterHandler filterHandler = filters.ApplyBrightness; filterHandler += filters.Resize; filterHandler += FilterOutsidePhotoFilter; processor.Process("C:\\Photos\\phot.jpg", filterHandler); Action <Photo> actionFilterHanlder = filters.ApplyContrast; processor.ProcessGenericDelegate("picture.jpg", actionFilterHanlder); }
public async void ProcessPhotoFiles() { await PhotoProcessor.Process().ConfigureAwait(false); }
public static void Main(string[] args) { #region Generics Console.WriteLine("------- Starting Generics ---------"); var number = new Nullable <int>(0); Console.WriteLine("Has Value: " + number.HasValue); Console.WriteLine("Value: " + number.GetValueOrDefault()); #endregion #region Delegates Console.WriteLine("------- Starting Delegates ---------"); // Use for extesibility and flexibility var processor = new PhotoProcessor(); var photoFilters = new PhotoFilters(); Action <Photo> filterHandler = photoFilters.ApplyBrightness; filterHandler += photoFilters.ApplyContrast; filterHandler += RemoveRedEye; processor.Process("Photos.jpg", filterHandler); #endregion #region Lambda Expressions Console.WriteLine("------- Starting Lambda Expressions ---------"); const int factor = 5; Func <int, int> multiplier = num => num * factor; Console.WriteLine("The result after multiplication: " + multiplier(50)); var books = new BookRepository().GetBooks(); var cheapBooks = books.FindAll(b => b.Price <= 35); Console.WriteLine("Books having the price less than 35: "); foreach (var book in cheapBooks) { Console.WriteLine(book.Title); } #endregion #region Extension Methods Console.WriteLine("------- Starting Extension Methods ---------"); string post = "This is supposed to be a very long post blah blah blah"; //Our extension method var shortenedPost = post.Shorten(5); Console.WriteLine(shortenedPost); //Pre-defined extension method IEnumerable <int> numbers = new List <int>() { 1, 5, 3, 10, 18, 9, 34, 12 }; Console.WriteLine("The maximum number from the list:" + numbers.Max()); #endregion #region LINQ Console.WriteLine("------- Starting LINQ ---------"); // LINQ Query Operators var cheapBooksAgain = from b in books where b.Price < 30 orderby b.Title select b.Title; // LINQ Extension Methods cheapBooksAgain = books .Where(b => b.Price < 30) .OrderBy(b => b.Title) .Select(b => b.Title); Console.WriteLine("Books having price less than 30$: "); foreach (var book in cheapBooksAgain) { Console.WriteLine(book); } var lastThreeBooks = books.Skip(2).Take(3); Console.WriteLine("Last three books: "); foreach (var book in lastThreeBooks) { Console.WriteLine(book.Title); } #endregion #region Events and Delegates Console.WriteLine("------- Starting Events and Delegates ---------"); var video = new Video() { Title = "Video 1" }; var videoEncoder = new VideoEncoder(); // Publisher var mailService = new MailService(); // Subscriber var messageService = new MessageService(); // Subscriber videoEncoder.VideoEncoded += mailService.OnVideoEncoded; // Binding the event videoEncoder.VideoEncoded += messageService.OnVideoEncoded; // Binding the event videoEncoder.Encode(video); #endregion #region Dynamic Console.WriteLine("------- Starting Dynamic ---------"); //Normal way object obj = "Ubaid"; //With Reflection //var methodInfo = obj.GetType().GetMethod("GetHashCode"); //methodInfo.Invoke(null, null); //With Dynamic dynamic testInt = 10; //Although optimize is not defined, still no compile time error if you uncomment //excelObject.Optimize(); dynamic testSecondInt = 20; object result = testInt + testSecondInt; Console.WriteLine("The result: " + result.GetType()); #endregion #region Exception Handling Console.WriteLine("------- Starting Exception Handling ---------"); try { var a = 1; var b = 0; //var answer = a / b; var api = new YoutubeApi(); var videos = api.GetVideos(); } catch (DivideByZeroException ex) { Console.WriteLine("You can't divide by 0"); } catch (ArgumentOutOfRangeException ex) { Console.WriteLine("Argument is out of range."); } catch (Exception ex) { Console.WriteLine("Exception Message: " + ex.Message); Console.WriteLine("Inner Exception Message: " + ex.InnerException.Message); } #endregion #region Async and Await var download = new Download(); download.DownloadHtml("https://msdn.microsoft.com"); #endregion }
static void Main(string[] args) { //Exception Hnadeling StreamReader streamReader = null; try { streamReader = new StreamReader(@"c:\test.zip"); var content = streamReader.ReadToEnd(); throw new Exception("!"); } catch (Exception ex) { Console.WriteLine("Error Occurred!"); } finally { if (streamReader != null) { streamReader.Dispose(); } } ///Or /// StreamReader streamReader = null; try { //using (var StreamReader = new StreamReader(@"c:\test.zip")) //{ // var content = streamReader.ReadToEnd(); //} var youtube = new YouTubeApi(); var vids = youtube.GetVideos("user"); } catch (Exception ex) { Console.WriteLine(ex.Message); } //Dynamics dynamic dynamic = "test"; dynamic = 10; dynamic a = 10; dynamic bbb = 5; var c = a + bbb; int d = a; long e = d; //Nullables DateTime?date = null; Console.WriteLine(date.GetValueOrDefault()); Console.WriteLine(date.HasValue); //Console.WriteLine(date.Value); DateTime date2 = date.GetValueOrDefault(); DateTime?date3 = date2; ///Linq Extension Methods var books1 = new BookRepository().GetBooks(); var cheapBooks1 = books1.Where(x => x.Price < 10).OrderBy(x => x.Title); //Linq Query Operator var cheaperBooks = from b in books1 where b.Price < 10 orderby b.Title select b.Title; //Extensions string post = "this is long long long post..."; var shortenedPost = post.Shorten(3); Console.WriteLine(shortenedPost); //Events var video = new Video() { Title = "Video Title 1" }; var videoEncoder = new VideoEncoder(); /// Publisher var mailService = new MailService(); // subscriber var messageService = new MessageService(); videoEncoder.videoEncoded += mailService.OnVideoEncoded; videoEncoder.videoEncoded += messageService.OnVideoEncoded; videoEncoder.Encode(video); // => const int factor = 5; Func <int, int> multipler = n => n * factor; Console.WriteLine(multipler(5)); var books = new BookRepository().GetBooks(); //var cheapBooks = books.FindAll(IsCheaperThan10Dollars); var cheapBooks = books.FindAll(b => b.Price < 10); foreach (var book in cheapBooks) { Console.WriteLine(book.Title); } //Delegates var photo = new PhotoProcessor(); var filters = new PhotoFilters(); //PhotoProcessor.PhotoFilterHandler filterHandler = filters.ApplyBrightness; Action <Photo> filterHandler = filters.ApplyBrightness; filterHandler += filters.ApplyContrast; filterHandler += RemoveRedEyeFilter; photo.Process("test", filterHandler); //Generics var numbers = new Generic <int>(); numbers.Add(10); var dictionary = new GenericDictionary <string, Book>(); dictionary.Add("1", new Book()); var NUMBER = new AdvancedTopics.Nullable <int>(); Console.WriteLine("Has Value? " + NUMBER.HasValue); Console.WriteLine("Value: " + NUMBER.GetValueOrDefault()); //Or You can use System.Nullable for this purpose. }
static void Main(string[] args) { Console.Write("Enter a Number: "); string userInput = Console.ReadLine(); Console.WriteLine("Your Number is: {0}", userInput); var dictionary = new Dictionary <string, string>(); dictionary["apple"] = "A fruit or a computer company"; Console.WriteLine(dictionary["apple"]); var someList = new List <int>(); someList.Add(1); someList.Add(2); someList.Add(3); someList.Add(5); someList.Add(8); someList.Add(11); someList.RemoveAt(0); someList.RemoveAt(2); for (int i = 0; i < someList.Count; i++) { Console.WriteLine(someList[i]); } foreach (int number in someList) { Console.WriteLine(number); } someList.ForEach(number => Console.WriteLine(number)); someList.ForEach(Console.WriteLine); string[] names = { "John", "Daryl", "Mike", "Sarah", "Michele" }; string[] moreNames = new string[5]; moreNames[0] = "John"; moreNames[1] = "Daryl"; Console.WriteLine("Size of names: {0}\nSize of moreNames: {1}", names.Length, moreNames.Length); // and so on string student = "John Smith"; char firstCharacter = student[1]; // ---- Exercise for loops ---- var animals = new List <string>(); animals.Add("Lion"); animals.Add("Tiger"); animals.Add("Bird"); animals.Add("Cat"); animals.Add("Dog"); animals.Add("Leopard"); string favoriteAnimal = "Bird"; foreach (string animal in animals) { Console.WriteLine(animal); } if (animals.Contains(favoriteAnimal)) { Console.WriteLine("I love {0} and also every other animal, including {1}", favoriteAnimal, animals[2]); // same as the above line, but without the placeholder Console.WriteLine("I love " + favoriteAnimal + "and also every other animal, including " + animals[2]); } else { Console.WriteLine("No, I don't care for those"); } // dictionary looping var person = new Dictionary <string, int>(); person.Add("Joan", 22); person.Add("Daniel", 42); person.Add("Anna", 34); // person = {Joan=22, Daniel=42, Anna=34} // loop through the hash map and return each key/value pair for (int i = 0; i < person.Count; i++) { Console.WriteLine("Key: {0}, Value: {1}", person.Keys.ElementAt(i), person[person.Keys.ElementAt(i)]); } foreach (var peep in person) { // print out the key (their name) and their value Console.WriteLine("Name: {0}, Age: {1}", peep.Key, peep.Value); } var studentData = new Dictionary <string, string>(); studentData["name"] = "Fred"; studentData["age"] = "20"; studentData["hometown"] = "Seattle"; studentData["favorite_food"] = "Pizza"; Console.WriteLine("This is {0}", studentData["name"]); Console.WriteLine("They are {0} years old", studentData["age"]); Console.WriteLine("from {0}", studentData["hometown"]); Console.WriteLine("and their favorite food is {0}", studentData["favorite_food"]); var students = new Dictionary <string, Dictionary <string, string> >(); students["Fred"] = new Dictionary <string, string>(); students["Fred"].Add("name", "Fred"); students["Fred"].Add("age", "20"); students["Fred"].Add("hometown", "Seattle"); students["Fred"].Add("favorite_food", "Pizza"); Console.WriteLine("This is {0}", students["Fred"]["name"]); var students2 = new Dictionary <string, Student>(); var someStudent = new Student("Fred", 20, "Seattle", "Pizza"); students2.Add("Fred", someStudent); var anotherStudent = new Student("Sally", 21, "Columbus", "Pasta"); students2.Add("Sally", anotherStudent); var studentWithNoData = new Student(); var sedan = new Car("blue", 4); sedan.Start(); sedan.Stop(); sedan.Drive(); Console.WriteLine("Car color: {0}", sedan.Color); Console.WriteLine("Number of Doors: {0}", sedan.NumberOfDoors); var coup = new Car("red", 2); var compact = new Car("blue"); Car.Compare(sedan, new Car()); int maxDoors = Car.MAX_DOORS; coup.Type = CarType.SPORTY; coup.NumberOfDoors = 4; if (coup == sedan) { Console.WriteLine("not sure how, but a coup and sedan are the same?"); } if (coup.Equals(sedan)) { Console.WriteLine(""); } Console.WriteLine(coup.ToString()); var vehicle = new Vehicle(); var genericAnimal = new Animal(0, "amoeba"); genericAnimal.Announce(); var bear = new Bear(1, "Yogi", 9999); bear.Announce(); var vehicles = new List <Vehicle>(); vehicles.Add(new Truck()); vehicles.Add(sedan); vehicles.Add(coup); vehicles.Add(compact); var vehicles2 = new List <IVehicle>(); var rallyCar = new RallyCar(); vehicles2.Add(new Truck()); vehicles2.Add(new Motorcycle()); vehicles2.Add(sedan); vehicles2.Add(coup); vehicles2.Add(compact); vehicles2.Add(rallyCar); var crossOver = new CrossOver(); // this won't work, because crossover doesn't implement // the IVehicle interface //vehicles2.Add(crossOver); foreach (var v in vehicles2) { v.Accelerate(10); } Drive(rallyCar); Drive(sedan); Drive(new Truck()); var pupil = new Student("John Smith", 19, "Columbus", "Pizza"); var teacher = new Teacher("Jane Doe", 31); PrintInfo(pupil); PrintInfo(teacher); // Page 21 in interfaces and extension methods example Console.WriteLine("-----------------------"); var dbMigrator = new DbMigrator(new ConsoleLogger()); var dbMigrator2 = new DbMigrator(new FileLogger("migrator.log")); dbMigrator.Migrate(); dbMigrator2.Migrate(); Console.WriteLine("-----------------------"); // event stuff (week 6 day 2) ProcessBusinessLogic bl = new ProcessBusinessLogic(); bl.ProcessCompleted += bl_ProcessCompleted; // register with an event bl.ProcessCompleted += bl_ProcessUpdated; bl.StartProcess(); var myProcess = new PhotoProcessor(); var filters = new PhotoFilters(); Action <Photo> filterHandler = filters.ApplyContrast; filterHandler += filters.ApplyBrightness; filterHandler += RemoveRedEyeFilter; myProcess.Process("pic.jpg", filterHandler); // lambda function takes in a number and then squares it Func <int, int> squareFunction = num => num * num; // in our case, it passes in 3 and returns 9 Console.WriteLine(squareFunction(3)); const int factor = 5; Func <int, int> multiplier = num => num * factor; int result = multiplier(10); Console.WriteLine(multiplier(6)); Console.WriteLine(result); Func <int, int, int, double> pythagoreanTheorem = (a, b, c) => Math.Pow(a, 2) + Math.Pow(b, 2) + Math.Pow(c, 2); double result2 = pythagoreanTheorem(1, 2, 3); Console.WriteLine(pythagoreanTheorem(2, 3, 4)); Console.WriteLine(result2); var library = new BookRepository(); List <Book> books = library.Books; List <Book> cheapBooks = books.FindAll(book => book.Price < 10); foreach (var book in cheapBooks) { Console.WriteLine(book.Title); } Console.ReadKey(); }