Ejemplo n.º 1
0
        static void Delegates()
        {
            // Delegates are objects that knows how to call a method (or a group of methods)
            // It is also a reference to a function
            // We use delegates to achieve extensibility and flexibility (eg.: frameworks)

            // Interfaces or Delegates???
            // Use a Delegate when:
            // - An eventing design pattern is used
            // - The caller doesn't need to access other properties or methods on the object implementing the method

            var processor  = new PhotoProcessor();
            var filters    = new PhotoFilters();
            var newFilters = new NewPhotoFilters();

            // Dotnet has its own delegates. So, we do not need to create ours
            // PhotoProcessor.PhotoFilterHandler filterHandler = filters.ApplyBrightness;
            Action <Photo> filterHandler = filters.ApplyBrightness;

            filterHandler += filters.ApplyContrast;
            filterHandler += filters.Resize;
            filterHandler += newFilters.RemoveRedEye;

            processor.Process("photo.jpg", filterHandler);
        }
Ejemplo n.º 2
0
        public static string Serialize(VCard vcard)
        {
            var builder = new StringBuilder();

            builder.Append(VersionProcessor.Serialize(vcard));
            builder.Append(FormattedNameProcessor.Serialize(vcard));
            builder.Append(NameProcessor.Serialize(vcard));
            builder.Append(BirthDayProcessor.Serialize(vcard));
            builder.Append(MailerProcessor.Serialize(vcard));
            builder.Append(TitleProcessor.Serialize(vcard));
            builder.Append(RoleProcessor.Serialize(vcard));
            builder.Append(TimeZoneInfoProcessor.Serialize(vcard));

            builder.Append(LogoProcessor.Serialize(vcard));
            builder.Append(PhotoProcessor.Serialize(vcard));

            builder.Append(NoteProcessor.Serialize(vcard));
            builder.Append(LastRevisionProcessor.Serialize(vcard));
            builder.Append(UrlProcessor.Serialize(vcard));
            builder.Append(UidProcessor.Serialize(vcard));
            builder.Append(OrganizationProcessor.Serialize(vcard));
            builder.Append(GeographyProcessor.Serialize(vcard));

            builder.Append(AddressesProcessor.Serialize(vcard));
            builder.Append(DeliveryAddressProcessor.Serialize(vcard));
            builder.Append(TelephonesProcessor.Serialize(vcard));
            builder.Append(EmailsProcessor.Serialize(vcard));
            builder.Append(ExtensionsProcessor.Serialize(vcard));

            return(builder.ToString());
        }
Ejemplo n.º 3
0
        // public delegate TResult Func<in T1,in T2, out TResult>(T1 arg1,T2 arg2);
        static void Main(string[] args)
        {
            int number1 = 5;
            // Lamba
            Func <int, int> squareOfNumber = i => number1 * number1;

            Console.WriteLine(squareOfNumber);

            var lambaDemo   = new LambaDemo();
            var listOFBooks = lambaDemo.GetBooks().Where(x => x.Price < 10).ToList();

            Func <int, int, int> add   = Sum;
            Func <int, int, int> minus = Subtract;
            int result = minus(5, 3);

            Console.WriteLine(result);
            var _doorProcessor = new UnlockDoorProcessor();
            var _door          = new Door();

            _door.KeyNumber = "MY121HN";
            Func <Door, string> processor1 = _doorProcessor.UnclockDoor;

            processor1 += OpenDoorWithRemote;
            var dd = processor1(_door);



            Console.ReadLine();



            var            processor     = new PhotoProcessor();
            var            filters       = new PhotoFilters();
            Action <Photo> filterHandler = filters.ApplyBrightness;

            filterHandler += CustomerFilter;
            filterHandler += filters.ApplyContrast;
            filterHandler += filters.Resize;
            processor.Process("hhh", filterHandler);

            var nullable = new Nullables <int>();
            var genericInitializerObject = new GenericInitializerObject <Student>();
            var student = genericInitializerObject.CreateInitializerObjectGeneric();

            student.Name    = "Sazi";
            student.Surname = "Nyathi";
            var results = nullable.GetVaueOrDefault();

            var number = new GenericList <int>();

            number.Add(10);

            var students = new GenericList <Student>();

            students.Add(student);

            var studentDictinary = new GenericDictionary <int, Student>();

            studentDictinary.Add(1, student);
        }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            System.Console.WriteLine("Using Custome Delegates: ");
            Photo photo = new Photo()
            {
                Name = "Sai.jpg"
            };
            PhotoHandler photohand = new PhotoHandler();

            PhotoProcessor.PhotoEventHandler photoehand = photohand.loadPhoto;
            photoehand += photohand.enhancePhoto;

            PhotoProcessor pp = new PhotoProcessor();

            pp.Process(photo, photoehand);

            System.Console.WriteLine("Using Action Delegates: ");
            System.Action <Photo> actionhand = photohand.loadPhoto;
            actionhand += photohand.enhancePhoto;

            pp = new PhotoProcessor();
            pp.Process(photo, actionhand);

            System.Console.ReadLine();
        }
Ejemplo n.º 5
0
        public void ConvertToJPG_JPGPhotoSupplied_ReturnsSamePhoto()
        {
            var   processor = new PhotoProcessor(new FakeLogger());
            Photo photo     = new Photo(PhotoFormat.JPG);
            Photo newPhoto  = processor.ConvertToJPG(photo);

            Assert.AreEqual(photo, newPhoto);
        }
        public void Setup()
        {
            this.filterHandler = null;

            this.filters   = new PhotoFilters {
            };
            this.processor = new PhotoProcessor {
            };
        }
Ejemplo n.º 7
0
//这样简洁了很多,同样Main()中对委托实例化的部分也要改,如
  
static void Main(string[] args)
{
  var processor = new PhotoProcessor();
  var filters = new PhotoFilters();
  
  Action<Photo> filterHandler = filters.ApplyBrightness;  //直接这样就能实例化委托,其他不用改变
    
  filterHandler += filter.ApplyContrast;
  processor.Process("C:\photo.jpg", filterHandler);
}
Ejemplo n.º 8
0
        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);
        }
Ejemplo n.º 9
0
    public void PhotoIDsAndTitlesGroupedByAlbum_Returns_FormattedString()
    {
        List <Photo> testPhotos = new List <Photo>();

        this.GenerateAndAddTestAlbum(ref testPhotos, "1", 1);
        this.GenerateAndAddTestAlbum(ref testPhotos, "2", 1);
        PhotoProcessor photoProc = new PhotoProcessor(testPhotos);
        string         expected  = "> photo-album 1\n[1] title1-1\n\n" + "> photo-album 2\n[1] title2-1\n\n";

        Assert.True(photoProc.PhotoIDsAndTitlesGroupedByAlbum() == expected);
    }
Ejemplo n.º 10
0
        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);
        }
Ejemplo n.º 11
0
        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);
        }
Ejemplo n.º 12
0
        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);
        }
Ejemplo n.º 13
0
        //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);
        }
Ejemplo n.º 14
0
        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);
        }
Ejemplo n.º 15
0
        static void Main(string[] args)
        {
            Book csBook = new Book {
                Isbn = "1212", Title = "C#_Advanced"
            };

            var numbers = new GenericList <int>();

            numbers.Add(10);
            var books = new GenericList <Book>();

            books.Add(new Book());

            var dict = new GenericDictionary <string, Book>();

            dict.Add("1234", new Book());

            var NewNumber = new GenericClasses.Nullable <int>();

            Console.WriteLine("Has Value? " + NewNumber.HasValue);
            Console.WriteLine("The value is: " + NewNumber.GetValueOrDefaultValue());


            string ppath = string.Format("C:\\Users\\Mia\\Desktop\\AspNet_Practice\\Pjs\\C#NextLevel\\c#Generics_Delegate\\Generic-Delegate_solu\\Generic-Delegate\\imgs\\sun.png");
            // Normal way apply filter

            /* PhotoProcessor pp = new PhotoProcessor();
             * pp.ProcessPhoto(ppath); */

            // Delegate Way to do Filter
            PhotoFilters   pf = new PhotoFilters();
            PhotoProcessor pp = new PhotoProcessor();

            // Apply build-in Delegate System.Action<T>
            Action <Photo> FilterHandler = pf.ApplyBrightness;

            FilterHandler += pf.Resize;
            FilterHandler += ApplyNewFilter;

            pp.PhotoProcess(ppath, FilterHandler);


            Console.WriteLine("Press Enter to Quite...");
            while (Console.ReadKey().Key != ConsoleKey.Enter)
            {
            }
        }
Ejemplo n.º 16
0
        //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);
        }
Ejemplo n.º 18
0
        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();
        }
Ejemplo n.º 19
0
        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);
        }
Ejemplo n.º 20
0
        static void Main(string[] args)
        {
            var photo = Photo.LoadPhoto("C:\\photos\\Mypic.jpg");
            //PhotoProcessor.PhotoHandler photoHandler = PhotoFilters.ApplyBrightness;

            // photoHandler += PhotoFilters.ApplyContrast;

            Action <Photo> photoHandler = PhotoFilters.ApplyBrightness;

            photoHandler += PhotoFilters.ApplyContrast;

            PhotoProcessor.ProcessPhoto(photo, photoHandler);
            //declare, use , instantiate, call the holding method



            var photo2 = Photo.LoadPhoto("MyPic");

            photoHandler -= PhotoFilters.ApplyContrast;
            photoHandler += MyOwnFilters.MakeBlackAndWhite;

            PhotoProcessor.ProcessPhoto(photo2, photoHandler);
        }
Ejemplo n.º 21
0
        static void Main(string[] args)
        {
            Console.WriteLine("Enter 1 for Factory Pattern. \n" +
                              "Enter 2 for Observer Pattern.");
            int choice = Convert.ToInt32(Console.ReadLine());

            switch (choice)
            {
            case 1:
                var ef = new EmployeeFactory();
                Console.WriteLine(ef.GetEmployee(1).GetBonus());
                Console.ReadLine();
                break;

            case 2:
                var observable = new TemperatureMonitor();
                var observer   = new TemperatureReporter();
                observer.Subscribe(observable);
                observable.GetTemperature();
                break;

            case 3:
                var editor  = new Editor();
                var history = new Momento.History();

                editor.SetContent("a");
                history.Push(editor.CreateState());
                editor.SetContent("b");
                history.Push(editor.CreateState());
                editor.SetContent("c");
                history.Push(editor.CreateState());
                editor.Restore(history.Pop());
                editor.Restore(history.Pop());

                Console.WriteLine(editor.GetContent());
                break;

            case 4:

                Canvas canvas = new Canvas();
                canvas.SelectTool(new BrushTool());
                canvas.MouseDown();
                canvas.MouseUp();
                break;

            case 5:

                BrowseHistory browseHistory = new BrowseHistory();
                browseHistory.Push("www.google.com");
                browseHistory.Push("www.yahoo.com");
                browseHistory.Push("www.reddif.com");
                browseHistory.Push("www.youtube.com");

                IIterator <string> iterator = browseHistory.CreateIterator();
                while (iterator.HasNext())
                {
                    var url = iterator.Current();
                    Console.WriteLine(url);
                    iterator.next();
                }
                break;

            case 6:
                //The difference between State and Strategy pattern is that in state pattern there is only a single state of the object and the behaviour is determined by the implementation injected.
                //In strategy pattern there could be multiple behaviours in form of multiple properties inside class such as IFilter & ICompression. The implementation injected further changes the behaviour.
                PhotoProcessor photoProcessor = new PhotoProcessor(new BnW(), new JPEG());
                photoProcessor.ProcessPhoto();
                break;

            case 7:     //template
                AbstractPreFlightCheckList flightChecklist = new F16PreFlightCheckList();
                flightChecklist.runChecklist();

                break;

            case 8:     //command
                var service = new CustomerService();
                var command = new AddCustomerCommand(service);
                var button  = new Command.Button(command);
                button.click();

                var composite = new CompositeCommand();
                composite.Add(new ResizeCommand());
                composite.Add(new BlackAndWHiteCommand());
                var button2 = new Command.Button(composite);
                button2.click();

                var commandHisotry = new Command.Undo.History();

                var doc = new Command.Undo.HtmlDocument();
                doc.SetContent("Hello World");
                var boldCommand = new BoldCommand(doc, commandHisotry);
                boldCommand.Execute();
                Console.WriteLine(doc.GetContent());

                var undoCommand = new UndoCommand(commandHisotry);
                undoCommand.Execute();
                Console.WriteLine(doc.GetContent());

                break;

            case 9:     //Observer
                DataSource dataSource = new DataSource();
                dataSource.AddObserver(new Chart());
                dataSource.AddObserver(new SpreadSheet(dataSource));
                dataSource.SetValue("value changed");
                break;

            case 10:     //Mediator //the pattern is applied to encapsulate or centralize the interactions amongst a number of objects
                var dialog = new ArticlesDialogBox();
                dialog.SimulateUsserInteraction();
                break;

            case 11:     //Chain of Responsibility
                //autehnticator --> logger --> compressor --> null
                var compressor    = new Compressor(null);
                var logger        = new Logger(compressor);
                var authenticator = new Authenticator(logger);
                var server        = new WebServer(authenticator);
                server.handle(new HttpRequest()
                {
                    UserName = "******", Password = "******"
                });
                break;

            case 12:     //Visitor
                var document = new Visitor.HtmlDocument();
                document.Add(new HeadingNode());
                document.Add(new AnchorNode());
                document.Execute(new HighlighOperation());
                break;

            case 13:     // Composite
                var shape1 = new Shape();
                var shape2 = new Shape();
                var group1 = new Group();
                group1.Add(shape1);
                group1.Add(shape2);
                var group2 = new Group();
                var shape3 = new Shape();
                group2.Add(shape3);
                group1.Add(group2);
                group1.render();
                break;

            case 14:     //Adapter
                Image       image       = new Image();
                ImageViewer imageViewer = new ImageViewer(image);
                imageViewer.Apply(new SepiaFilter());
                imageViewer.Apply(new FancyAdapter(new FancyFilter()));
                break;

            case 15:     //Decorator
                var cloudStream  = new CloudStream();
                var encryptData  = new EncryptStream(cloudStream);
                var compressData = new CompressStream(encryptData);
                compressData.write("some random data");
                break;

            case 16:     //Facade
                NotificationService notificationService = new NotificationService();
                notificationService.Send("Hello..", "17.0.0.1");
                break;

            case 17:     //Flyweight
                PointService pointService = new PointService(new PointFactory());
                var          points       = pointService.getPoints();
                foreach (var p in points)
                {
                    p.draw();
                }
                break;

            case 18:     //Bridge
                AdvancedRemoteControl remote = new AdvancedRemoteControl(new SonyTv());
                remote.setChannel(1);
                break;

            case 19:     //Proxy
                Library       lib       = new Library();
                List <string> bookNames = new List <string>()
                {
                    "a", "b", "c"
                };
                foreach (var book in bookNames)
                {
                    lib.eBooks.Add(book, new EBookProxy(book));
                }
                lib.OpenEbook("a");
                break;

            case 20:     //Factory Method
                FactoryMethod.Employee emp          = new FactoryMethod.Employee();
                BaseEmployeeFactory    permanentEmp = new PermanentEmployeeFactory(emp);
                permanentEmp.ApplySalary();
                Console.WriteLine(emp.HouseAllowance);
                break;

            case 21:     //Abstract Factory
                AbstractFactory.Employee emp1 = new AbstractFactory.Employee();
                emp1.EmployeeTypeID = 1;
                emp1.JobDescription = "Manager";
                EmployeeSystemFactory esf = new EmployeeSystemFactory();
                var computerFactory       = esf.Create(emp1);
                Console.WriteLine($"{computerFactory.GetType()}, {computerFactory.Processor()}, {computerFactory.SystemType()}, {computerFactory.Brand()}");
                break;

            case 22:     //Builder
                Builder.IToyBuilder toyBuilder  = new Builder.PremiumToyBuilder();
                Builder.ToyDirector toyDirector = new Builder.ToyDirector(toyBuilder);
                toyDirector.CreateFullFledgedToy();
                Console.WriteLine(toyDirector.GetToy());
                break;

            case 23:     //Fluent Builder
                //Difference of implementation is visible in Director class.
                FluentBuilder.IToyBuilder toyBuilder1  = new FluentBuilder.PremiumToyBuilder();
                FluentBuilder.ToyDirector toyDirector1 = new FluentBuilder.ToyDirector(toyBuilder1);
                toyDirector1.CreateFullFledgedToy();
                Console.WriteLine(toyDirector1.GetToy());
                break;

            case 24:    //Object Pool
                ObjectPool <OneExpensiveObjToCreate> objPool = new ObjectPool <OneExpensiveObjToCreate>();
                OneExpensiveObjToCreate obj = objPool.Get();
                objPool.Release(obj);
                break;
            }

            Console.ReadLine();
        }
Ejemplo n.º 22
0
 public async void ProcessPhotoFiles()
 {
     await PhotoProcessor.Process().ConfigureAwait(false);
 }
Ejemplo n.º 23
0
 private void Awake()
 {
     _camera   = GetComponent <Camera>();
     processor = GetComponent <PhotoProcessor>();
 }
Ejemplo n.º 24
0
 void Awake()
 {
     photoProcessor = GetComponent <PhotoProcessor>();
 }
Ejemplo n.º 25
0
        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.
        }
Ejemplo n.º 26
0
        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
        }
Ejemplo n.º 27
0
        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();
        }