static void Main (string [] args) { DateTime start = DateTime.Now; HttpChannel chnl = new HttpChannel (); #if NET_2_0 ChannelServices.RegisterChannel (chnl, false); #else ChannelServices.RegisterChannel (chnl); #endif BaseRemoteObject obj = (BaseRemoteObject) Activator.GetObject (typeof (BaseRemoteObject), "http://localhost:1237/MyRemoteObject.soap"); Test test = new Test (); test.t = "test"; obj.test = test; SetValueDelegate svd = new SetValueDelegate (obj.setValue); IAsyncResult arValSet = svd.BeginInvoke (625, null, null); svd.EndInvoke (arValSet); GetValueDelegate gvd = new GetValueDelegate (obj.getValue); IAsyncResult arValGet = gvd.BeginInvoke (null, null); GetTextDelegate gtd = new GetTextDelegate (obj.getText); IAsyncResult arTxt = gtd.BeginInvoke (null, null); int iVal = gvd.EndInvoke (arValGet); string str = gtd.EndInvoke (arTxt); TimeSpan elapsed = DateTime.Now - start; Assert.AreEqual (625, iVal, "#A1"); Assert.AreEqual ("Narendra", str, "#A2"); Assert.IsTrue (elapsed.TotalMilliseconds > 9000, "#B1:" + elapsed.TotalMilliseconds); Assert.IsTrue (elapsed.TotalMilliseconds < 12000, "#B2:" + elapsed.TotalMilliseconds); }
static void Main(string[] args) { // Anonymous method, aka in-line delegate GetTextDelegate getTextDelegate = delegate(string name) { return("Hello from the GetTextDelegate made by " + name); }; // Expression Lambda GetTextDelegate getHelloText = (string name) => { return("Hello, " + name); }; // Statement Lambda GetTextDelegate getGoodbyeText = (string name) => { Console.WriteLine("I'm inside of a statement Lambda"); return("Goodbye, " + name); }; // Real used Lambda's, shortened Lambda GetTextDelegate getWelcomeText = name => "Welcome, to real Lambdas " + name; GetResultDelegate getSum = (a, b) => a + b; GetResultDelegate getProduct = (c, d) => c * d; DisplaySum(getSum); DisplaySum(getProduct); Console.WriteLine(getWelcomeText("Rob")); }
static void Main(string[] args) { GetTextDelegate getTextDelegate = delegate(string name) { return("Hello, " + name); }; //Lambda expression GetTextDelegate getHelloText = (string name) => { return("Hello, " + name); }; GetTextDelegate getGoodbyText = (string name) => { Console.WriteLine("I'm inside of an statement lambda"); return("Goodby, " + name); }; GetTextDelegate getWelcomeText = name => "Welecome " + name; GetResultDelegate getSum = (a, b) => a + b; GetResultDelegate getProduct = (a, b) => a * b; Display(getTextDelegate); DisplayNum(getSum); DisplayNum(getProduct); Console.WriteLine(getWelcomeText("Yuko")); }
static void Main(string[] args) { // Creating an anonymous method GetTextDelegate getTextDelegate = delegate(string name) { return("Hello, " + name); }; // Lambda expression GetTextDelegate getHelloText = (string name) => { return("Hello, " + name); }; // Statement lambda GetTextDelegate getGoodbyeText = (string name) => { Console.WriteLine("I'm inside of a lambda statement"); return("Goodbye, " + name); }; // even nicer lambda expression, also it only works because it's just one variable the "name" variable GetTextDelegate getWelcomeText = name => "Welcome, " + name; // lambda expression with various variables GetResultDelegate getSum = (a, b) => a + b; GetResultDelegate getProduct = (a, b) => a * b; DisplayNum(getSum); DisplayNum(getProduct); Console.WriteLine(getWelcomeText("Denis")); //Display(getTextDelegate); SayHello(); Console.ReadKey(); }
static void Main(string[] args) { PerformCalculation getSum = Addition; //getSum(5.0, 5.0); PerformCalculation getQuotient = Division; //getQuotient(5.0, 5.0); PerformCalculation multiCal = getSum + getQuotient; multiCal += Subtraction; multiCal(3.2, 3.2); GetTextDelegate getTextDelegate = delegate(string name) { return("Hello, " + name); }; GetTextDelegate getHelloText = (string name) => { return("Hello, " + name); }; // Statement lamda GetTextDelegate getGoodbyeText = (string name) => { Console.WriteLine("I'm inside of an statment lambda"); return("Goodbye, " + name); }; GetTextDelegate getWelcomeText = name => "Welcom, " + name; Console.WriteLine(getHelloText("Denis")); }
static void Main(string[] args) { /* * PerformCalculation getSum = Addition; * PerformCalculation getDiv = Division; * PerformCalculation multCast = getSum + getDiv; * multCast(5f, 6f); */ //Anonymous delegate GetTextDelegate getTextDelegate = delegate(string name) { return("Hello, " + name); }; // Expression lambda GetTextDelegate getTextDelegate1 = name => "Luis Carlos"; // Statement lambda GetTextDelegate getTextDelegate2 = (string name) => { Console.WriteLine("I'm inside lambda"); return("Hi"); }; Console.WriteLine(getTextDelegate("Luis Santos")); Display(getTextDelegate); }
static void Main(string[] args) { GetTextDelegate getTextDelegate = delegate(string name) { return("Hello, " + name); }; Console.WriteLine(getTextDelegate("Phong")); Display(getTextDelegate); }
public string GetText() { if (control.IsDisposed) return string.Empty; if (control.InvokeRequired) { GetTextDelegate del = new GetTextDelegate(GetText); return (string)control.Invoke(del); } else return control.Text; }
public static void ExplainAnonymousMethod() { GetTextDelegate getTextDelegate = delegate(string name) { return("Hello " + name); }; Console.WriteLine(getTextDelegate("Bhavik")); Display(getTextDelegate); }
static void Main(string[] args) { // Anonymous method, aka in-line delegate GetTextDelegate getTextDelegate = delegate(string name) { return("Hello from the GetTextDelegate made by " + name); }; Console.WriteLine(getTextDelegate("Rob.")); Display(getTextDelegate); }
private string currentText() { if (this.textBox_recevied.InvokeRequired) { GetTextDelegate d = new GetTextDelegate(currentText); return((string)this.Invoke(d)); } else { return(this.textBox_recevied.Text); } }
/// <summary> /// 初始化线程安全类 /// </summary> /// <param name="ctrl">需要进行线程安全的控件</param> public ThreadSafeSetter(Control ctrl) { target = ctrl; setText = SetText; setAppendText = SetAppendText; getText = GetText; add = Add; remove = Remove; removeAll = RemoveAll; setEnabled = SetEnabled; getEnabled = GetEnabled; getSelectedItem = GetSelectedItem; }
static public void run() { // Anonymous method is defined with the delegate keyword; GetTextDelegate getTextDelegate = delegate(string name) { return("Hello, " + name); }; Console.WriteLine(getTextDelegate("Rayleigh")); Display(getTextDelegate); SayHello(); return; }
public string GetText() { if (control.IsDisposed) { return(string.Empty); } if (control.InvokeRequired) { GetTextDelegate del = new GetTextDelegate(GetText); return((string)control.Invoke(del)); } else { return(control.Text); } }
public static void ExplainLambdaExpressions() { //Expression Lambda GetTextDelegate getTextDelegate = (string name) => { return("Hello " + name); }; //Statement Lambda GetTextDelegate getTextDelegate1 = (string name) => { string value = "Hello " + name + " Good morning"; return(value); }; Console.WriteLine(getTextDelegate("Raj")); PerformCalculation performCalculation = (a, b) => (a + b); Console.WriteLine(performCalculation(10, 20)); }
static void Main(string[] args) { // Anonymous method / Inline Delegate GetTextDelegate getTextDelegate = delegate(string name) { return("Hello, " + name); }; Console.WriteLine(getTextDelegate("Philip")); // method compiles first SayHello(); // pass anonymous method Display(getTextDelegate); // Lambda expression GetTextDelegate getHelloText = (string name) => { return("Hello from LBD, " + name); }; Console.WriteLine(getHelloText("Gurender")); // Statement Lambda GetTextDelegate getGoodbyeText = (string name) => { Console.WriteLine("I'm inside of a statement Lambda"); return("Goodbye, " + name); }; Console.WriteLine(getGoodbyeText("Philip")); GetTextDelegate getWelcomeText = name => "Welcome, " + name; Console.WriteLine(getWelcomeText("Gurender")); GetResultDelegate addNumbers = (a, b) => a + b; Console.WriteLine("Addition of 5 and 17 is: " + addNumbers(5, 17)); GetResultDelegate multiplyNumbers = (a, b) => a * b; Console.WriteLine("Multiplication of 5 and 7 is: " + multiplyNumbers(5, 7)); //using function DisplayNum(addNumbers); DisplayNum(multiplyNumbers); }
public static void AnonymousMain(string[] args) { //Creating an anonymous method GetTextDelegate getTextDelegate = delegate(string abc) { return("Hello ," + abc); }; Console.WriteLine(getTextDelegate("Aman")); //Expression lambda GetTextDelegate getHello = (string name) => { return("Hello, " + name); }; Console.WriteLine(getHello("How are you")); //Statement lambda GetTextDelegate getGoodbyetext = (string name) => { Console.WriteLine("I'm inside of an statement"); return("Goodbye, " + name); }; Console.WriteLine(getGoodbyetext("Raj")); //Powerful lambda expression... GetTextDelegate getWelcomeText = name_ => "Welcome, " + name_; Console.WriteLine(getWelcomeText("New members")); GetResultDelegate getSum = (a, b) => a + b; DisplayNum(getSum); Display(getTextDelegate); Console.ReadKey(); }
static void Main(string[] args) { // Anonymous method GetTextDelegate getTextDelegate = delegate(string name) { return("Hello, " + name); }; //expression Lambda GetTextDelegate getHelloText = (string name) => { return("Hello " + name); }; // Statement lambda GetTextDelegate getGoodbyText = (string name) => { return("Goodby" + name); }; // Shorter expression lambda GetTextDelegate getWelcomeText = name => "Welcome, " + name; Console.WriteLine(getWelcomeText("Bjorn")); }
static void Display(GetTextDelegate getTextDelegate) { System.Console.WriteLine(getTextDelegate("hi")); }
static void Main(string[] args) { // set up pointers PerformCalculation getSum = Addition; getSum(5.0, 5.0); PerformCalculation getQuotient = Division; Division(5.0, 5.0); // can set many pointers PerformCalculation multiCalc = getSum + getQuotient; multiCalc += Subtraction; multiCalc -= getSum; // fire pointers once multiCalc(5.0, 5.0); Game game1; game1.name = "Pokemon"; game1.developer = "Niantic"; game1.rating = 4.7; game1.releaseDate = "Mar 21 2019"; game1.Display(); //enums Day fr = Day.Fri; Day su = Day.Sun; Day a = Day.Fri; System.Console.WriteLine(fr == a); System.Console.WriteLine("the day is {0}", Day.Mon); System.Console.WriteLine((int)Day.Mon); System.Console.WriteLine((int)Months.Aug); // create a new instance // Human jon = new Human("John", "Smith", "Blue", 30); // //assign member variable // // jon.firstName = "Jon"; // // jon.lastName = "Smith"; // //call method duh // jon.IntroduceMyself(); Human michael = new Human("Michael", "Richards", "Brown"); // michael.firstName = "Michael"; // michael.lastName = "Richards"; michael.IntroduceMyself(); michael.findMatches(); // Human basic = new Human(); // basic.IntroduceMyself(); // Human sarah = new Human("sarah", "Richards"); // sarah.IntroduceMyself(); // Human tim = new Human("Tim"); // tim.IntroduceMyself(); // Box box1 = new Box(10, 10, 10); // box1.Width = 20; // System.Console.WriteLine("Box volume is {0}", box1.Volume); // box1.DisplayInfo(); // System.Console.WriteLine(box1.FrontSurface); // Members member1 = new Members(); // member1.Introducing(true); // creating arrays // int[] grades = new int[5]; // grades[0] = 20; // grades[1] = 15; // grades[2] = 10; // grades[3] = 20; // grades[4] = 10; // System.Console.WriteLine(grades[3]); // // string input = Console.ReadLine(); // // grades[3] = int.Parse(input); // // System.Console.WriteLine(grades[3]); // // int[] mathStudentsGrades = {20, 13, 21, 50, 9, 10}; // // int[] mathStudentsGradesB = new int[] {20, 10, 6, 7, 30 }; // // System.Console.WriteLine("Length of studen grades {0}", mathStudentsGrades.Length); // int[] nums = new int[10]; // for(int i = 0; i < nums.Length; i++){ // nums[i] = i; // } // for(int j = 0; j < nums.Length; j++){ // System.Console.WriteLine(nums[j]); // } // //use counter to get index // int counter = 0; // foreach(int k in nums){ // counter = k; // System.Console.WriteLine("element {0} = {1}", counter, k); // } // string[] friends = new string[5]; // friends[0] = "Brax"; // friends[1] = "Chris"; // friends[2] = "Erika"; // friends[3] = "Tyler"; // friends[4] = "Mike"; // foreach(string x in friends){ // System.Console.WriteLine("Hey there, {0}!", x); // } // // declare 2d array // string[,] matrix; // // doesnt work // // matrix = { // // {"1", "2"}, // // {"3", "4"} // // } // //3d array // int[,,] threeD; // //2d array // int[,] array2D = new int[,] { // { // 1, 2, 3 // row 0 // }, // { // 4, 5, 6 //row 1 // }, // { // 7, 8, 9 //row 2 // } // }; // System.Console.WriteLine("central value is {0}", array2D[1,1]); // //3d array must have same amount of rows in both // string[,,] array3D = new string[,,] { // { // { // "1", "2", "3" // }, // { // "4", "5", "6" // }, // { // "Hello!", "Hi", "what's up!" // } // }, // { // { // "10", "11", "12" // }, // { // "13", "14", "15" // }, // { // "Goodbye!", "see ya!", "Later!" // } // } // }; // System.Console.WriteLine("to get the 5 is {0}", array3D[0,1,1]); // System.Console.WriteLine("to get the 11 is {0}", array3D[1,0,1]); // System.Console.WriteLine("Say {0}!", array3D[0,2,0]); // System.Console.WriteLine("and now say {0}!", array3D[1,2,0]); // //specify demensions of matrix // string[,] array2D2 = new string[3,2]{ // { // "1", "2" // }, // { // "3", "4" // }, // { // "5", "6" // } // }; // array2D2[1,1] = "Chicken!"; // System.Console.WriteLine(array2D2[1,1]); // //find matrix dimensions // int demensions = array2D2.Rank; // System.Console.WriteLine("Dementions are {0}", demensions); // string[,] array2D3 = { // { // "1", "2" // }, // { // "3", "4" // }, // { // "5", "6" // } // }; int[][] jaggedArr = new int[3][]; jaggedArr[0] = new int [5]; jaggedArr[1] = new int [3]; jaggedArr[2] = new int [1]; //initalizer jaggedArr[0] = new int[] { 2, 4, 5, 6, 7 }; jaggedArr[1] = new int[] { 6, 7, 8 }; jaggedArr[2] = new int[] { 1 }; //alt way int[][] jaggedarr2 = new int[][] { new int[] { 2, 4, 5, 6, 7 }, new int[] { 10, 100, -7 } }; // System.Console.WriteLine("the value of the middle element in the second array is {0}", jaggedarr2[1][1]); foreach (int [] array in jaggedarr2) { foreach (int ele in array) { System.Console.WriteLine(ele); } } // for(int i = 0; i < jaggedarr2.Length; i++){ // System.Console.WriteLine("ARRAY NUM: {0}", i); // for(int j = 0; j < jaggedarr2[i].Length; j++){ // System.Console.WriteLine("ELE VALUE: {0}", jaggedarr2[i][j]); // } // } // string[][] jaggedarr3 = new string[][]{ // new string[] {"Derek", "Doug", "Mrs. Maynard"}, // new string[] {"Chris", "Mr. Hellickson", "Mrs. Hellickson"}, // new string[] {"Mike", "Mr. Smith", "Mrs. Smith"} // }; // for(int i = 0; i < jaggedarr3.Length; i++){ // System.Console.WriteLine("My name is {0}", jaggedarr3[i][i]); // for(int j = 0; j < jaggedarr3[i].Length; j++){ // System.Console.WriteLine("Hey! My name is {0}", jaggedarr3[j][j]); // } // } int[] grades = new int[] { 15, 13, 6, 12, 6, 16 }; foreach (int grade in grades) { System.Console.WriteLine(" {0} ", grade); } double results = GetAverage(grades); System.Console.WriteLine("average is {0}", results); int[] happiness = new int[] { 1, 2, 3, 4, 5 }; // getHappiness(happiness); // foreach(int stage in happiness){ // System.Console.WriteLine("Stage of happiness: {0}", stage); // } //declaring an arrayList with undefined amount of objs ArrayList myArrayList = new ArrayList(); //defined amount of objs ArrayList myArrayList2 = new ArrayList(100); myArrayList.Add(25); myArrayList.Add("Hello"); myArrayList.Add(25); myArrayList.Add(13); myArrayList.Add(6.7453); myArrayList.Add("Bye"); myArrayList.Add(13); // delete element by pass passing value to Remove myArrayList.Remove(13); //delete ele at specific index myArrayList.RemoveAt(0); System.Console.WriteLine("COUNT: {0}", myArrayList.Count); double sum = 0; // use object class type for array lists // foreach(object obj in myArrayList){ // if(obj is int){ // sum += Convert.ToDouble(obj); // } else if (obj is double) { // sum += (double)obj; // } else if (obj is string){ // System.Console.WriteLine("STR {0}", obj); // } // } // System.Console.WriteLine("SUM {0}", sum); //list // List<int> list = new List<int> {1,2,3,4,5}; // //adds to end of the list // list.Add(0); // list.Add(6); // list.Sort(); // list.RemoveRange(0,2); // foreach(int i in list){ // System.Console.WriteLine("Num: {0}", i); // } // System.Console.WriteLine(list.Contains(4)); // // find index of element matching expression, ie what index is the num 4 located at // int index = list.FindIndex(x => x == 4); // System.Console.WriteLine(list[index]); // list.RemoveAt(index); // list.ForEach(i => System.Console.WriteLine(i)); // //array list // ArrayList arrayList4 = new ArrayList(); // arrayList4.Add(1); // arrayList4.Add(10); // arrayList4.Add("3"); // arrayList4.Add(new Number {n = 4} ); // foreach(object o in arrayList4){ // System.Console.WriteLine(o); // } // Post post1 = new Post("New Post", true, "Anon"); // System.Console.WriteLine(post1.ToString()); // ImagePost post2 = new ImagePost("Image", "anon", "Image url" ,true ); // System.Console.WriteLine(post2.ToString()); // VideoPost post3 = new VideoPost("video", "Youtube", "google.com", 2000, true); // //System.Console.WriteLine(post3.ToString()); // post3.PlayVideo(); // System.Console.WriteLine("Press any key to pause"); // string input = Console.ReadLine(); // post3.StopVideo(); // if (input.ToLower().Equals("play")){ // post3.PlayVideo(); // } //call employee Employee employee = new Employee("Derek", "Sims", 20000); employee.Work(); Boss boss = new Boss("Sally", "Sims", 2000000, "Bently"); boss.Lead(); Trainee trainee = new Trainee("Chris", "Cross", 5000, "9-12", "12-8"); trainee.Work(); Notification note = new Notification("Denny", "Sup?", DateTime.Now.ToString()); Notification note2 = new Notification("Sarah", "Hi", DateTime.Now.ToString()); note.showNotification(); note2.showNotification(); // Car car = new Car(300, "black"); // car.ShowDetails(); // Audi audi = new Audi(300, "blue", "R8"); // audi.ShowDetails(); // Bmw bmw = new Bmw(550, "White", "780i"); // bmw.ShowDetails(); // polymorph - use virtual on method in base to allow inherited classes modify the method. // in this list these cars are seen as all Car objs // using virtual and override allow us to display different showdetails() below var cars = new List <Car> { new Car(300, "black"), new Audi(300, "blue", "R8"), new Bmw(550, "White", "780i") }; foreach (var car in cars) { car.ShowDetails(); } Car bmw2 = new Bmw(300, "green", "3 series"); Car audi2 = new Audi(500, "Purple", "r6"); bmw2.Repair(); audi2.Repair(); // if you build a new instance by telling its type is the inheriting class no need to override/virutal methods Bmw bmw3 = new Bmw(245, "white", "compressor"); bmw3.Repair(); // can cast a inherited obj back to its base class Car car2 = (Car)bmw3; car2.Repair(); M3 myM3 = new M3(300, "red", "M3"); myM3.Repair(); bmw2.SetCarIDInfo(11, "John"); audi2.SetCarIDInfo(123, "Sally"); bmw2.GetCarIDInfo(); audi2.GetCarIDInfo(); //access mod, private means unable to be used outside the class // public avail everywhere in project // protected avail by class and all classes inheriting from that class //internal acessable from own assembly(project) // start with most restrictive and relax until the use is available //gives full control over app, via variables and methods // math class //round up System.Console.WriteLine("Cealing: {0}", Math.Ceiling(15.2)); System.Console.WriteLine("floor: {0}", Math.Floor(15.3)); int num1 = 1; int num2 = 12; System.Console.WriteLine("Lower of nums is {0}", Math.Min(num1, num2)); System.Console.WriteLine("Higher num is {0}", Math.Max(num1, num2)); System.Console.WriteLine("3 to the power of 5 is {0}", Math.Pow(3, 5)); System.Console.WriteLine("pi is {0}", Math.PI); System.Console.WriteLine("square root of 25 is {0}", Math.Sqrt(25)); System.Console.WriteLine("Absolute val of -1000 is {0}", Math.Abs(-1000)); System.Console.WriteLine("Cos of 1 is {0}", Math.Cos(1)); // random class Random dice = new Random(); int numEyes; for (int i = 0; i < 10; i++) { // next takes in a min and max numEyes = dice.Next(1, 7); System.Console.WriteLine("die roll is {0}", numEyes); } // fortune teller Random fortuneTeller = new Random(); int fortune; for (int j = 0; j < 10; j++) { fortune = fortuneTeller.Next(1, 4); switch (fortune) { case 1: System.Console.WriteLine("Yes"); break; case 2: System.Console.WriteLine("No"); break; case 3: System.Console.WriteLine("Maybe"); break; default: break; } } Human testMatch = new Human(); //regex // phone num select //\d{3}[.#-]\d{3}[.#-]\d{4} //german numbers // \+\d{5}\/\d{8}|^\d{4}[\/]\d{8}|^\d{7}\/\d{8} testMatch.findMatches(); //date time DateTime dateTime = new DateTime(2018, 4, 9); System.Console.WriteLine("My favorite day is {0}", DateTime.Today); DateTime tomorrow = GetTomorrow(); System.Console.WriteLine(GetFirstDayOfYear(1990)); System.Console.WriteLine("tomorrow is {0}", dateTime.DayOfWeek); int days = DateTime.DaysInMonth(2000, 2); System.Console.WriteLine(days); DateTime now = DateTime.Now; System.Console.WriteLine("the minute is {0}", now.Minute); System.Console.WriteLine("Current time is: {0} o'clock {1} minutes, and {2} seconds", now.Hour, now.Minute, now.Second); // System.Console.WriteLine("write the date in this format yyyy-mm-dd"); // string input = Console.ReadLine(); // if(DateTime.TryParse(input, out dateTime)){ // System.Console.WriteLine(dateTime); // TimeSpan daysPassed = now.Subtract(dateTime); // System.Console.WriteLine("days passed {0}", daysPassed.Days); // } else { // System.Console.WriteLine("wrong format"); // } //nullables int?nullNum = null; int?nullNum2 = 1234; double?nullDouble = new Double(); double?nullDouble2 = 1234.4353543; bool?isPerson = null; if (isPerson == true) { System.Console.WriteLine("Hello person"); } else if (isPerson == false) { System.Console.WriteLine("Are you a robot?"); } else { System.Console.WriteLine("Im not sure what you are"); } double?num20 = 2.6; double?num21 = null; double num22 = 20.6; if (num20 == null) { num22 = 0.0; } else { num22 = (double)num20; } System.Console.WriteLine(num22); // null coalescing operator - converts non nullable to nullable if left of ?? is null assigns right side, like ||= in ruby num22 = num20 ?? 8.11; System.Console.WriteLine(num22); // garbage collector auto with .net // abstract cant create abstract objs // Shape shape1 = new Shape(); Shape[] shapes = { new Sphere(10), new Cube(5) }; // Sphere sphere = new Sphere(10); // sphere.GetInfo(); foreach (Shape shape in shapes) { shape.GetInfo(); // as tries to perform cast, if it cant, it will return null, here cube and sphere are different data types so it wont cast them to each other // is returns a bool, checks data type for what you want it to be Cube iceCube = shape as Cube; if (iceCube == null) { System.Console.WriteLine("this shape is no cube!"); } if (shape is Cube) { System.Console.WriteLine("now this is a cube!"); } } // can cast object type to any other object type object cube1 = new Cube(7); Cube cube2 = (Cube)cube1; System.Console.WriteLine("Has a volume of {0}", cube2.Volume()); // delagates !! type based // accepts methods as params // used to define callbacks // can be changed - important for events // allow for use of anon functions // covariance, using a very simlar class instead of expected type //ex. using FileStream where Stream was expected //Contravariance // use base type where inherited type was expected //ex. using Stream where FileStream was expected //anon functions only ran/compiled once required GetTextDelegate getTextDelegate = delegate(string name){ return("Hello, " + name); }; System.Console.WriteLine(getTextDelegate("Tim")); Display(getTextDelegate); //methods are ran first sayHello(); //expression lambda (single thing executes) GetTextDelegate getHelloText = (string name) => { return("hello, " + name); }; //statement lambda (multi things execute) GetTextDelegate getGoodbyeText = (string name) => { System.Console.WriteLine("Inside statement"); // return optional return("goodbye"); }; // shorthand expression lambda, only works with single argument expressions GetTextDelegate getWelcomeText = name => "welcome, " + name; // use performCalc because it expects 2 args PerformCalculation lambdaSum = (a, b) => a + b; PerformCalculation lambdaProduct = (a, b) => a * b; System.Console.WriteLine(getWelcomeText("Tim")); DisplayNum(lambdaSum); DisplayNum(lambdaProduct); //events // enables comms between objs // cleaner code // enables subscribver to listen to sender // delegate is a contract between publisher and subscriber // delegate determines signature of event // can hold multiple method pointers //var file = new File() {Title = "File stuff"}; //var downloadHelper = new Download(); //PUBLISHER (creating event) //var unpackService = new UnpackService(); // receiver //var notification = new NotificationService(); //receiver //downloadHelper.FileDownloaded += unpackService.OnFileDownloaded; //(subscribe to event) when publisher event fires, fires all subscriber events subscribed to event //downloadHelper.FileDownloaded += notification.OnFileDownloaded; //downloadHelper.DownloadFile(file); //int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; //OddNumbers(numbers); UniversityManager universityManager = new UniversityManager(); //universityManager.MaleStudents(); //universityManager.SortStudentsByAge(); //universityManager.AllStudentsFromOsu(); //Console.WriteLine("Please enter a school id"); //string input = Console.ReadLine(); //// can convert int here ////int id = Convert.ToInt32(input) //universityManager.FindStudentsBySchoolId(input); //universityManager.StudentAndUniversityCollection(); //int[] SomeInt = { 30, 15, 12, 10, 6 }; //// asc //IEnumerable<int> sortedInts = from i in SomeInt orderby i select i; ////desc //IEnumerable<int> Descsort = from i in SomeInt orderby i descending select i; //Console.WriteLine("desc"); //foreach(int i in Descsort) //{ // Console.WriteLine(i); //} // xml string string studentXml = @"<Students> <Student> <Name>Jon</Name> <Age>20</Age> <University>OSU</University> <Major>CS</Major> </Student> <Student> <Name>Sally</Name> <Age>30</Age> <University>Yale</University> <Major>Medicine</Major> </Student> <Student> <Name>Terry</Name> <Age>25</Age> <University>OSU</University> <Major>Business</Major> </Student> <Student> <Name>Kyle</Name> <Age>21</Age> <University>Yale</University> <Major>Welding Engineering</Major> </Student> </Students>" ; XDocument studentXdoc = new XDocument(); studentXdoc = XDocument.Parse(studentXml); var students = from student in studentXdoc.Descendants("Student") select new { Name = student.Element("Name").Value, Age = student.Element("Age").Value, University = student.Element("University").Value, Major = student.Element("Major").Value }; foreach (var student in students) { Console.WriteLine("Name {0}, age {1}, uni {2} major {3}", student.Name, student.Age, student.University, student.Major); } var sortedStudents = from student in students orderby student.Age select student; foreach (var student in sortedStudents) { Console.WriteLine("Name {0}, age {1}, uni {2}", student.Name, student.Age, student.University); } } //</main>
unsafe public void ProcessMessages(int APEPID, string AppDomainToLoadInto) { m_ManagedThreadId = Thread.CurrentThread.ManagedThreadId; try { AUTProcess = Process.GetCurrentProcess(); string AUTProcessId = AUTProcess.Id.ToString(); string APEProcessId = APEPID.ToString(); // Set the thread name so its easy to find in the debugger Thread.CurrentThread.Name = "APE_" + APEProcessId + "_" + AppDomainToLoadInto + "_" + AUTProcessId; m_HandleMemoryMappedFileStringStore = NM.CreateFileMapping((IntPtr)(NM.INVALID_HANDLE_VALUE), (IntPtr)0, NM.FileMapProtection.PageReadWrite, 0, StringSpaceBytes, APEProcessId + "_String_" + AppDomainToLoadInto + "_" + AUTProcessId); m_IntPtrMemoryMappedFileViewStringStore = NM.MapViewOfFile(m_HandleMemoryMappedFileStringStore, NM.FileMapAccess.FileMapAllAccess, 0, 0, (UIntPtr)StringSpaceBytes); m_HandleMemoryMappedFileMessageStore = NM.CreateFileMapping((IntPtr)(NM.INVALID_HANDLE_VALUE), (IntPtr)0, NM.FileMapProtection.PageReadWrite, 0, (uint)sizeof(MessageStore), APEProcessId + "_Message_" + AppDomainToLoadInto + "_" + AUTProcessId); m_IntPtrMemoryMappedFileViewMessageStore = NM.MapViewOfFile(m_HandleMemoryMappedFileMessageStore, NM.FileMapAccess.FileMapAllAccess, 0, 0, (UIntPtr)sizeof(MessageStore)); m_PtrMessageStore = (MessageStore *)m_IntPtrMemoryMappedFileViewMessageStore.ToPointer(); m_eventIPC = new EventWaitHandle(false, EventResetMode.AutoReset, APEProcessId + "_EventIPC_" + AppDomainToLoadInto + "_" + AUTProcessId); Side = EventSet.AUT; try { ApeProcess = Process.GetProcessById(APEPID); } catch { } // Setup the hook procedures SetupmouseHelperHooks(); EnumThreadProcedue = new NM.EnumWindow(EnumThreadCallback); // Setup the delegates m_GetWPFHandleAndNameAndTitleDelegater = new GetWPFHandleAndNameAndTitleDelegate(GetWPFHandleAndNameAndTitle); m_ConvertTypeDelegater = new ConvertTypeDelegate(Cast); m_GetTextDelegater = new GetTextDelegate(GetText); m_GetAccessibilityObjectNameDelegater = new GetAccessibilityObjectNameDelegate(GetAccessibilityObjectName); SetupSentinelGridsHelperDelegates(); SetupFlexgridHelperDelegates(); SetupComHelperDelegates(); SetupGridControlHelperDelegates(); SetupFormHelperDelegates(); SetupDictionaryHelperDelegates(); SetupDataGridViewHelperDelegates(); //Process all the messages while (true) { WaitForMessages(EventSet.AUT); if (m_Abort) { RemoveFileMapping(); break; } string result = null; int messageNumber = -1; int numberOfMessages = -1; try { numberOfMessages = m_PtrMessageStore->NumberOfMessages; m_PtrMessageStore->NumberOfMessages = 0; m_StringStoreOffset = 0; for (messageNumber = 1; messageNumber <= numberOfMessages; messageNumber++) { Message *ptrMessage = (Message *)(m_IntPtrMemoryMappedFileViewMessageStore + ((messageNumber - 1) * m_SizeOfMessage)); DebugLogging.WriteLog("Processing message " + ptrMessage->Action.ToString()); //get the message action: switch (ptrMessage->Action) { case MessageAction.GetListViewGroupRectangle: GetListViewGroupRectangle(messageNumber); break; case MessageAction.GetListViewItemRectangle: GetListViewItemRectangle(messageNumber); break; case MessageAction.ControlExists: string findText = Find(messageNumber, 0); if (findText != null) { ControlIdentifier newIdentifier = new ControlIdentifier(); AddIdentifierMessage(newIdentifier); } break; case MessageAction.Find: result = Find(messageNumber, m_TimeOut); break; case MessageAction.RefindByHandle: RefindByHandle(messageNumber); break; case MessageAction.RefindByUniqueId: RefindByUniqueId(messageNumber); break; case MessageAction.ReflectGet: Reflect(messageNumber); break; case MessageAction.ConvertType: ConvertType(messageNumber); break; case MessageAction.SentinelGridsGetUnderlyingGrid: SentinelGridsGetUnderlyingGrid(ptrMessage); break; case MessageAction.ReflectPoll: ReflectPoll(messageNumber); break; case MessageAction.GetResult: GetResult(messageNumber); break; case MessageAction.AddMouseHook: AddMouseHook(ptrMessage, messageNumber); break; case MessageAction.RemoveMouseHook: RemoveMouseHook(ptrMessage, messageNumber); break; case MessageAction.WaitForMouseState: WaitForMouseState(ptrMessage, messageNumber); break; case MessageAction.SetTimeOuts: SetTimeOuts(messageNumber); break; case MessageAction.GetTitleBarItemRectangle: GetTitleBarItemRectangle(ptrMessage, messageNumber); break; case MessageAction.GarbageCollect: GarbageCollect(ptrMessage, messageNumber); break; case MessageAction.GetContextMenuStrip: GetContextMenuStrip(messageNumber); break; case MessageAction.GetAppDomains: GetAppDomains(messageNumber); break; case MessageAction.GetRecognisedType: GetRecognisedType(messageNumber); break; case MessageAction.GetApeTypeFromType: GetApeTypeFromType(messageNumber); break; case MessageAction.GetApeTypeFromObject: GetApeTypeFromObject(messageNumber); break; // Flexgrid helper methods case MessageAction.FlexgridGetCellRangeBackColourName: FlexgridGetCellRange(ptrMessage, CellProperty.BackColourName); break; case MessageAction.FlexgridGetCellRangeForeColourName: FlexgridGetCellRange(ptrMessage, CellProperty.ForeColourName); break; case MessageAction.FlexgridGetCellRangeDataType: FlexgridGetCellRange(ptrMessage, CellProperty.DataType); break; case MessageAction.FlexgridGetCellRangeCheckBox: FlexgridGetCellRange(ptrMessage, CellProperty.CheckBox); break; case MessageAction.FlexgridGetCellRangeImage: FlexgridGetCellRange(ptrMessage, CellProperty.Image); break; case MessageAction.FlexgridGetCellRangeBackgroundImage: FlexgridGetCellRange(ptrMessage, CellProperty.BackgroundImage); break; case MessageAction.FlexgridGetAllColumnsHidden: FlexgridGetAllColumnsHidden(ptrMessage); break; case MessageAction.FlexgridGetAllRowsHidden: FlexgridGetAllRowsHidden(ptrMessage); break; case MessageAction.FlexgridGetAllColumnsWidth: FlexgridGetAllColumnsWidth(ptrMessage); break; case MessageAction.FlexgridGetAllRowsHeight: FlexgridGetAllRowsHeight(ptrMessage); break; case MessageAction.GridControlGetTitleRows: GridControlGetTitleRows(ptrMessage); break; case MessageAction.GridControlGetTitleRowCount: GridControlGetTitleRowCount(ptrMessage); break; case MessageAction.GridControlGetAllColumnsHidden: GridControlGetAllColumnsVisible(ptrMessage); break; case MessageAction.GetDateTimePickerCheckboxRectangle: GetDateTimePickerCheckboxRectangle(ptrMessage, messageNumber); break; case MessageAction.GetDateTimePickerButtonRectangle: GetDateTimePickerButtonRectangle(ptrMessage, messageNumber); break; case MessageAction.ScrollControlIntoView: ScrollControlIntoView(ptrMessage, messageNumber); break; case MessageAction.PeakMessage: PeakMessage(ptrMessage, messageNumber); break; case MessageAction.SetFocus: SetFocus(ptrMessage, messageNumber); break; case MessageAction.SetFocusAsync: SetFocusAsync(ptrMessage, messageNumber); break; case MessageAction.GridControlEnsureTitleCellVisible: GridControlEnsureTitleCellVisible(ptrMessage); break; case MessageAction.DictionaryContainsKey: DictionaryContainsKey(ptrMessage); break; case MessageAction.AddMouseClickHandler: AddMouseClickHandler(ptrMessage); break; case MessageAction.WaitForAndRemoveMouseClickHandler: WaitForAndRemoveMouseClickHandler(ptrMessage); break; case MessageAction.RemoveMouseClickHandler: RemoveMouseClickHandler(ptrMessage); break; case MessageAction.AddFlexgridCellChangedHandler: AddFlexgridCellChangedHandler(ptrMessage); break; case MessageAction.WaitForAndRemoveFlexgridCellChangedHandler: WaitForAndRemoveFlexgridCellChangedHandler(ptrMessage); break; case MessageAction.AddFlexgridAfterRowColChangeHandler: AddFlexgridAfterRowColChangeHandler(ptrMessage); break; case MessageAction.WaitForAndRemoveFlexgridAfterRowColChangeHandler: WaitForAndRemoveFlexgridAfterRowColChangeHandler(ptrMessage); break; case MessageAction.RemoveFlexgridAfterRowColChangeHandler: RemoveFlexgridAfterRowColChangeHandler(ptrMessage); break; case MessageAction.AddGenericWalkerSelectedHandler: AddGenericWalkerSelectedHandler(ptrMessage); break; case MessageAction.WaitForAndRemoveGenericWalkerSelectedHandler: WaitForAndRemoveGenericWalkerSelectedHandler(ptrMessage); break; case MessageAction.RemoveGenericWalkerSelectedHandler: RemoveGenericWalkerSelectedHandler(ptrMessage); break; case MessageAction.VisualStyleSupported: VisualStyleSupported(ptrMessage, messageNumber); break; case MessageAction.DataGridViewShowCell: DataGridViewShowCell(ptrMessage); break; case MessageAction.GetToolTip: GetToolTip(ptrMessage, messageNumber); break; case MessageAction.DumpActiveX: DumpActiveX(ptrMessage, messageNumber); break; case MessageAction.FlexgridGetNodeCollapsedState: FlexgridGetNodeCollapsedState(ptrMessage); break; case MessageAction.GetTypeInformationActiveX: GetTypeInformationActiveX(ptrMessage); break; case MessageAction.GetTabRect: GetTabRect(ptrMessage); break; case MessageAction.GetInvokeFormActiveX: GetInvokeFormActiveX(ptrMessage, messageNumber); break; case MessageAction.GetComboBoxExItemText: GetComboBoxExItemText(ptrMessage, messageNumber); break; case MessageAction.WaitForMouseMove: WaitForMouseMove(ptrMessage, messageNumber); break; case MessageAction.AddToolStripItemEnteredHandler: AddToolStripItemEnteredHandler(ptrMessage); break; case MessageAction.WaitForAndRemoveToolStripItemEnteredHandler: WaitForAndRemoveToolStripItemEnteredHandler(ptrMessage); break; case MessageAction.DumpControl: DumpControl(ptrMessage, messageNumber); break; case MessageAction.FlexgridGetCellRangeTextDisplay: FlexgridGetCellRange(ptrMessage, CellProperty.TextDisplay); break; case MessageAction.FlexgridGetCellRangeFontStyle: FlexgridGetCellRange(ptrMessage, CellProperty.FontStyle); break; case MessageAction.FlexgridGetCellBackgroundImage: FlexgridGetCellBackgroundImage(ptrMessage); break; default: throw new Exception("Unknown action for message " + messageNumber.ToString() + " : " + ptrMessage->Action.ToString()); } if (result != null) { break; } } if (result == null) { AddResultMessage(MessageResult.Success); } } catch (Exception ex) { result = "Message " + messageNumber.ToString() + " of " + numberOfMessages + " failed:\r\n"; result += ex.GetType().Name + " " + ex.Message + "\r\n" + ex.StackTrace; if (ex.InnerException != null) { //TODO make this better? result += "\r\n" + ex.InnerException.GetType().Name + " " + ex.InnerException.Message + "\r\n" + ex.InnerException.StackTrace; } } if (result != null) { //clean up all the messages for (messageNumber = 1; messageNumber <= MessageStore.MaxMessages; messageNumber++) { Message *ptrMessage = (Message *)(m_IntPtrMemoryMappedFileViewMessageStore + ((messageNumber - 1) * m_SizeOfMessage)); CleanUpMessage(ptrMessage); } m_PtrMessageStore->NumberOfMessages = 0; m_StringStoreOffset = 0; AddResultMessage(MessageResult.Failure, result); } //clear the data stores so we don't hold any references to objects in the AUT //which would stop them being garbage collected if (tempStore0ReleaseComObject) { Marshal.ReleaseComObject(tempStore0); tempStore0ReleaseComObject = false; } tempStore0 = null; if (tempStore1ReleaseComObject) { Marshal.ReleaseComObject(tempStore1); tempStore1ReleaseComObject = false; } tempStore1 = null; if (tempStore2ReleaseComObject) { Marshal.ReleaseComObject(tempStore2); tempStore2ReleaseComObject = false; } tempStore2 = null; if (tempStore3ReleaseComObject) { Marshal.ReleaseComObject(tempStore3); tempStore3ReleaseComObject = false; } tempStore3 = null; if (tempStore4ReleaseComObject) { Marshal.ReleaseComObject(tempStore4); tempStore4ReleaseComObject = false; } tempStore4 = null; if (tempStore5ReleaseComObject) { Marshal.ReleaseComObject(tempStore5); tempStore5ReleaseComObject = false; } tempStore5 = null; if (tempStore6ReleaseComObject) { Marshal.ReleaseComObject(tempStore6); tempStore6ReleaseComObject = false; } tempStore6 = null; if (tempStore7ReleaseComObject) { Marshal.ReleaseComObject(tempStore7); tempStore7ReleaseComObject = false; } tempStore7 = null; if (tempStore8ReleaseComObject) { Marshal.ReleaseComObject(tempStore8); tempStore8ReleaseComObject = false; } tempStore8 = null; if (tempStore9ReleaseComObject) { Marshal.ReleaseComObject(tempStore9); tempStore9ReleaseComObject = false; } tempStore9 = null; //send back our response SendMessages(EventSet.AUT); } } catch (Exception ex) { TextWriter log = File.AppendText(Environment.GetEnvironmentVariable("TEMP") + @"\critical.log"); log.WriteLine(DateTime.Now.ToString() + "\t" + ex.Message); log.WriteLine(DateTime.Now.ToString() + "\t" + ex.StackTrace); log.Close(); throw; } }
// It is important that anonymous methods do not use jump statements // like goto, break, and continue. public static void Display(GetTextDelegate textDelegate) { Console.WriteLine(textDelegate("World")); }
static void Display(GetTextDelegate getTextDelegate) { Console.WriteLine(getTextDelegate("Another Rob!")); }
public static void DelegateExercises() { // Delegates // Covariance enables to pass a derived type where a base type is expected // e.g. FileStream where Stream is expected // Contravariance enables to pass a bass type where a derived type is expected // e.g. Stream where FileStream is expected PerformCalculation getSum = Addition; Console.WriteLine("The sum of 123 and 9 is {0}.", getSum(123, 9)); PerformCalculation getDifference = Subtraction; Console.WriteLine("The difference of 123 and 9 is {0}.", getDifference(123, 9)); PerformCalculation getQuotient = Division; Console.WriteLine("The quotient of 123 divided by 9 is {0}.", getQuotient(123, 9)); PerformCalculation getMulti = getSum + getQuotient; Console.WriteLine("The sum + quotient of 123 and 9 is {0}. [{1}]", getMulti(123, 9), getSum(123, 9) + getQuotient(123, 9)); getMulti += Subtraction; getMulti -= getQuotient; Console.WriteLine("The sum + difference of 123 and 9 is now {0}. [{1}]", getMulti(123, 9), getSum(123, 9) + getDifference(123, 9)); Console.WriteLine(); // A different option for implementation // Anonymous methods GetTextDelegate getText = delegate(string name) { return("Hello, " + name); }; Console.WriteLine(getText("Sierra")); Console.WriteLine(); // Another option (best option!) // Lambda expressions // Expression lambda // Good for one line GetTextDelegate getHello = (string name) => { return("Hello, " + name); }; Console.WriteLine(getHello("world!")); // Statement lambda // Necessary if more than one line GetTextDelegate getWassup = (string name) => { Console.WriteLine("WASSUP!!!"); Console.WriteLine("How you been, {0}?", name); return("Wassup, " + name); }; Console.WriteLine(getWassup("Sierra")); GetTextDelegate getWelcome = name => "Welcome, " + name; Console.WriteLine(getWelcome("Sierra")); Console.WriteLine(); }
static void Display(GetTextDelegate getTextDelegate) { Console.WriteLine(getTextDelegate("World")); }
public override void Link(Engine e) { GetText = e.GetUibText; }
public void SetDelegates(GetTextDelegate getFunction, SetTextDelegate setFunction, GetBreakPointsDelegate breakpointFunction) { m_GetSourceCode = getFunction; m_SetSourceCode = setFunction; m_GetBreakPoints = breakpointFunction; }
static void Display(GetTextDelegate del) { Console.WriteLine(del("My World ")); }
public static void Display(GetTextDelegate getTextDelegate) { Console.WriteLine(getTextDelegate("Bhavik")); }