6.2 Scratchpad Learning Activity

Overview

6.2 Scratchpad Learning Activity

This assignments covers Delegates (Funcs, Actions and Predicates) and the Observer Pattern.

Work through the stories in order. Use the acceptance criteria to check each feature, and complete the nested tasks using the specified names, values, and scenarios.

Getting Started
1.Getting Started
A Unzip this file:

Scratchpad 6.2 LastName.zip

Scratchpad 6.2 LastName.zip
B Rename the folder and solution file to include your last name.
C If you want, you can follow along with the instructor-led videos.

6.2 Scratchpad Lab Walkthrough, Part 1 [46:18]

6.2 Scratchpad Lab Walkthrough, Part 1 [46:18]

6.2 Scratchpad Lab Walkthrough, Part 2 [1:03:18]

6.2 Scratchpad Lab Walkthrough, Part 2 [1:03:18]

6.2 Scratchpad Lab Walkthrough, Part 3 [28:34]

6.2 Scratchpad Lab Walkthrough, Part 3 [28:34]
Intro to Delegates
Acceptance Criteria
Acceptance criteria
  • Press F10. The calculateArea variable should now have the Value of a method and the Type of CalculateAreaDelegate.
  • Press F11. The debugger should step into the CalculateArea method assigned to the calculateArea variable.
  • Step through the method and back to the MainWindow. The area variable should be 5538.96
  • F10 over the second call. The area variable should now be 907.46
Instructions
2.Intro to Delegates
A Get the area of a circle.
1 In the directMethodWithDoubleReturnButton_Click:

Call the CalculateArea method, passing in 42 and catching the result in a variable named area.

Call the CalculateArea method again, passing in 17 and assigning it to the area variable.

This is the way of calling methods that you have been used to.

2 Set breakpoints and click the 'Direct method with double return' to ensure the button click works as intended.
B Use a delegate to get the area instead.
1 Add a new class to the project named Delegates.
2 Remove the public class Delegates and the curly braces associated with it.

We aren't really going to be making a class.

3 Define a delegate by pasting the code below:
public delegate double CalculateAreaDelegate(int radius);

While this looks like a method it is not. It is a TYPE of delegate. Delegates do not define a method body. Delegates only define TYPES (return and parameters). In this case a return of type double and a parameter of type int.

4 In the delegateButton_Click:

Define a delegate of type CalculateAreaDelegate named calculateArea.

Assign the calculateArea variable to the method CalculateArea.

CalculateAreaDelegate calculateArea = this.CalculateArea;

There are no parenthesis after CalculateArea because we are not calling it; we are saying make the calculateArea variable a reference to the CalculateArea method.

Change the CalculateAreaDelegate to have an int return instead of a double return.

Return to the MainWindow. Note that now the method cannot be assigned to the delegate because the return type no longer matches CalculateArea.

Snip: Delegate Type Error for 6.2 Scratchpad Learning Activity (NEW). Use the adjacent task instructions to identify the required controls, output, or debugger values.
Snip: Delegate Type Error

Change the return of CalculateAreaDelegate back to double.

Define a local variable of type double named area and assign it to the call to calculateArea, passing in 42.

double area = calculateArea(42);

Make another call to calculateArea, passing in 17 and assigning it to the area variable.

C Check Your Work:
1 Set a breakpoint on the line that assigns calculateArea.
2 Start the application and click 'Delegate with method'.
3 Hover over the calculateArea delegate. Note that it is currently null.
4 Press F10. The calculateArea variable should now have the Value of a method and the Type of CalculateAreaDelegate.
Snip: Autos Delegate for 6.2 Scratchpad Learning Activity (NEW). Use the adjacent task instructions to identify the required controls, output, or debugger values.
Snip: Autos Delegate
5 Press F11. The debugger should step into the CalculateArea method assigned to the calculateArea variable.
6 Step through the method and back to the MainWindow. The area variable should be 5538.96
7 F10 over the second call. The area variable should now be 907.46
Intro to Funcs
Acceptance Criteria
Acceptance criteria
  • Start the application and click the 'Func with method' button. The calculateArea Func should be null.
  • Press F10. The calculateArea variable should now have the Value of Method and be of Type Func<int, double>
  • Press F11. The debugger should step into the CalculateArea method.
  • Step through the remaining method. The area variable should be 5538.96 and then 907.46.
Instructions
3.Intro to Funcs

Funcs are referred to as "syntactic sugar" at times because they do the work of a defined delegate such as the previous example, but on the fly.

A In the funcButton_Click:
1 Paste the code below:
Func<int, double> calculateArea = this.CalculateArea;

A Func type declares an input and an output. In this case the input is an int and the output it a double. Multiple inputs can be declared such as <int, , string, double>double> in which int and string would be parameters and the double would be the return. The last type declared will always be return. The CalculateArea method can then be assigned to the Func because it takes an int and returns a double.

2 Call the calculateArea delegate, passing in 42 and assigning the result to a local area variable.
3 Call the calculateArea delegate again, passing in 17 and assigning the result to the local area variable.
B Change the parameter type of the CalculateArea method to double instead of int.
Snip: Func Error for 6.2 Scratchpad Learning Activity (NEW). Use the adjacent task instructions to identify the required controls, output, or debugger values.
Snip: Func Error

Because the parameter does not match the <int, , double>> type as defined by the Func it is not compatible.

C Change the parameter type of the CalculateArea method back to int.
D Check Your Work:
1 Set a breakpoint on the line of code that assigns the calculateArea variable.
2 Start the application and click the 'Func with method' button. The calculateArea Func should be null.
3 Press F10. The calculateArea variable should now have the Value of Method and be of Type Func<int, double>
4 Press F11. The debugger should step into the CalculateArea method.
5 Step through the remaining method. The area variable should be 5538.96 and then 907.46.
Intro to Actions
Acceptance Criteria
Acceptance criteria
  • Start the application and click 'Action with method'. The myAction variable should be null.
  • Press F10. The myAction variable should have a Value of Method and a Type of Action<string>
  • Press F11. The debugger should step into the WriteToConsole method.
  • F11 through the remaining method. Use the Output window to ensure the proper strings are output.
Instructions
4.Intro to Actions

Actions are the same as Funcs, but they do not have a return type.

A Call a method directly.
1 In the directMethodWithoutReturnButton_Click:

Call WriteToConsole and pass in "Hello, world!" as the argument.

Call WriteToConsole and pass in "Goodbye." as the argument.

B Call a method using an Action type delegate.
1 In the actionWithMethodButton_Click:

Paste the code below.

Action<string> myAction = this.WriteToConsole;

The only thing declared in the < > for an Action is the parameter type(s).

Call myAction and pass in "Hello, world!"

Call myAction and pass in "Goodbye."

C Check Your Work:
1 Set a breakpoint on the line of code that assigns the myAction variable.
2 Start the application and click 'Action with method'. The myAction variable should be null.
3 Press F10. The myAction variable should have a Value of Method and a Type of Action<string>
4 Press F11. The debugger should step into the WriteToConsole method.
5 F11 through the remaining method. Use the Output window to ensure the proper strings are output.
Intro to Predicates
Acceptance Criteria
Acceptance criteria
  • Start the application and click 'Predicate with method'. The isLongString variable should be null.
  • Press F10. The isLongString variable should have a Value of Method and be of Type Predicate<string>.
  • Press F11. The debugger should step into the IsLongThan5 method.
  • Step through the remaining method. The variable isMatch should be false and then true.
Instructions
5.Intro to Predicates

Predicates are Funcs that return a boolean value.

A Call method directly.
1 In the directMethodWithBoolReturnButton_Click event handler:

Define a local variable named isMatch of type bool and assign it to the call to IsLongerThan5 and pass in "Hello" as the argument.

Assign isMatch to the call to IsLongerThan5 and pass in "Goodbye." as the argument.

2 Start the application and step through the code to ensure it works properly.
B Call method using a Predicate.
1 In the predicateWithMethodButton_Click:

Define a Predicate with a string parameter named isMatch and assign it to the IsLongerThan5 method.

Predicate<string> isLongString = this.IsLongerThan5;

Since Predicates always return a bool type there is no reason to declare it in the < >

Call isLongString, passing in "Hello" and assigning the result to a local variable named isMatch of type bool.

Call isLongString again, passing in "Goodbye." and assigning it to the isMatch variable.

C Check Your Work:
1 Set a breakpoint on the line of code that assings the isLongString variable.
2 Start the application and click 'Predicate with method'. The isLongString variable should be null.
3 Press F10. The isLongString variable should have a Value of Method and be of Type Predicate<string>.
4 Press F11. The debugger should step into the IsLongThan5 method.
5 Step through the remaining method. The variable isMatch should be false and then true.
Paperboy Example
Acceptance Criteria
Acceptance criteria
  • F10 over the calls to RegisterObserver. Bob and Frank should be added to the observers list.
  • F11 through the loop. Both Bob and Frank should read the new headline.
  • The completed implementation satisfies this requirement: Call the washingtonPost object's UpdateNews method and pass in the argument "Political Scandal...".
Instructions
6.Paperboy Example

In the case of a paperboy, they would need to deliver a paper to every house regardless of if they wanted it or not. This is a "push" system. Things changed, however, when people would subscribe to the newspaper and then only subscribers would get papers. This is a "pull" system. This pull system (called the Observer Pattern) relieves the strain on the paperboy and gives control to the person.

A Call methods directly.
1 In the paperDirectMethodButton_Click event handler:

Call the washingtonPost object's UpdateNews method and pass in the argument "Political Scandal...".

Call the bob object's ReadNews method and pass in this.washingtonPost.News

Do the same for the frank object.

Call UpdateNews and pass in a new headline.

Call ReadNews again for Bob and Frank.

There is a major issue here. Bob and Frank have no idea when the news updates so they would have to constantly be reading the news, waiting for it to update. This translates to a ton of wasted method calls on the Bob and Frank objects.

B Use the Observer Pattern.
1 Review the interfaces.

The ISubject interface represents the newspaper in this case and needs to know how to Register, Unregister, and Notify.

The IObserver represents the customer and they need to know when the paper (the ISubject) updates.

2 Implement interfaces.

Have the Person class implement the IObserver interface,

Have the Publisher class implement the ISubject interface.

3 In the Update method in the Person class:

Assign a local variable of type Publisher named publisher to the subject as a Publisher.

Call ReadNews and pass in the publisher's News property.

4 In the Publisher class, define and instantiate a private field of type List<IObserver> named observers.
5 In the RegisterObserver method, add the passed in observer to the observers list.
6 In the UnregisterObserver method, remove the passed in observer from the observers list.
7 In the NotifyObservers method, loop through the observers list and call Update on each IObserver, passing in the ISubject (this).
8 In the UpdateNews method, call NotifyObservers after assigning the News property.
9 In the paperObserverPatternButton_Click event handler:

Call the washingtonPost object's RegisterObserver method and pass in this.bob.

Call RegisterObserver again and pass in this.frank.

Call the washingtonPost object's UpdateNews method and pass in a headline.

10 Check Your Work:

Set a breakpoint on the line of code that calls RegisterObserver.

Start the application and click the 'Paper observer pattern' button.

F10 over the calls to RegisterObserver. Bob and Frank should be added to the observers list.

F11 into the UpdateNews method.

F11 into the NotifyObservers method.

F11 through the loop. Both Bob and Frank should read the new headline.

Snip: Observer Output for 6.2 Scratchpad Learning Activity (NEW). Use the adjacent task instructions to identify the required controls, output, or debugger values.
Snip: Observer Output

Now instead of Bob and Frank continually refreshing their browser to check if the news has changed, whenever the news changes they will be altered and will read it then.

Multicasting
Acceptance Criteria
Acceptance criteria
  • Press F11. The debugger should step into the WriteToConsole method.
  • F11 through that method. The debugger should then step into the WriteToConsole2 method.
  • Step through the rest of the event handler. The output should be the same as below.
  • F11 through the event handler. The debugger should step into the extra2Button_Click event handler.
  • F11 through the event handler. This time the debugger should go through the extra2Button event handler twice because it was plugged in a second time.
Instructions
7.Multicasting
A Multicast a delegate.
1 In the actionWithMethodButton_Click event handler, under the lines of code that assigns myAction paste the code below.
myAction += WriteToConsole2;

What this does is plug in an additional method to the delegate so that both methods execute when the delegate is invoked/called.

2 Check Your Work:

Set a breakpoint on the line of code that calls myAction.

Start the application and click 'Action with method'.

Press F11. The debugger should step into the WriteToConsole method.

F11 through that method. The debugger should then step into the WriteToConsole2 method.

Step through the rest of the event handler. The output should be the same as below.

Snip: Multicast Delegate for 6.2 Scratchpad Learning Activity (NEW). Use the adjacent task instructions to identify the required controls, output, or debugger values.
Snip: Multicast Delegate
B Multicast an event.

Event handlers are methods that are plugged into button delegates. A Click event, for instance, is a property on a button that takes an object type and a RoutedEventArgs type. What that means is that we can plug additional methods into that delegate type.

1 Inside the extra1Button_Click, paste the code below:
this.extra3Button.Click += this.extra2Button_Click;

This line of code plugs the extra2Button_Click event handler into Button 3's Click event delegate.

2 Check Your Work:

Set breakpoints at the beginning of all ExtraButton event handlers.

Start the application and click 'Extra button 1'

F11 through the event handler.

Click 'Extra button 3'.

F11 through the event handler. The debugger should step into the extra2Button_Click event handler.

Click the 'Extra button 1' again and the 'Extra button 3' again.

F11 through the event handler. This time the debugger should go through the extra2Button event handler twice because it was plugged in a second time.

Snip: Multicast Event for 6.2 Scratchpad Learning Activity (NEW). Use the adjacent task instructions to identify the required controls, output, or debugger values.
Snip: Multicast Event
Use an Action to broadcast news.
Acceptance Criteria
Acceptance criteria
  • Start the application and click 'Paper action'. The BroadcastNewsAction should have the Method ReadNews and have the Target of Person.
  • Press F11 on the BroadcastNewsAction delegate. The debugger should step into Bob's ReadNews method.
  • F11 through ReadNews and ReadNews should be called again, but this time on Frank.
Instructions
8.Use an Action to broadcast news.
A Define an Action property in the Publisher class.
public Action<string> BroadcastNewsAction { get; set; }
B In the paperActionButton_Click event handler, plug the call to bob's ReadNews method into the BroadcastNewsAction delegate.
this.washingtonPost.BroadcastNewsAction += this.bob.ReadNews;
C Repeat the previous step for frank.
D In the Publisher class, define a new method named BroadcastNews that takes a string type parameter named news.
E In the BroadcastNews method:
1 Assign the News property to the passed in news string.
2 Write an if check that checks if the BroadcastNewsAction property is not null.

If nothing has "subscribed to" or been "plugged into" the delegate a NullReferenceException would be thrown when trying to use it.

3 In the if check body, call the BroadcastNewsAction and pass in the News property.
F In the paperActionButton_Click, after plugging the methods into the delegate, call BroadcastNews and pass in a new headline.
G In the ReadNews method, replace the argument in Console.WriteLine with:
string.Format("{0} read: {1}", this.FirstName, news)
H Check Your Work:
1 Set a breakpoint on the line of code that calls BroadcastNews.
2 Start the application and click 'Paper action'. The BroadcastNewsAction should have the Method ReadNews and have the Target of Person.
Snip: Delegate Properties for 6.2 Scratchpad Learning Activity (NEW). Use the adjacent task instructions to identify the required controls, output, or debugger values.
Snip: Delegate Properties
3 Press F11 and step through the BroadcastNews method.
4 Press F11 on the BroadcastNewsAction delegate. The debugger should step into Bob's ReadNews method.
Snip: ReadNews for 6.2 Scratchpad Learning Activity (NEW). Use the adjacent task instructions to identify the required controls, output, or debugger values.
Snip: ReadNews
5 F11 through ReadNews and ReadNews should be called again, but this time on Frank.
Snip: Output for 6.2 Scratchpad Learning Activity (NEW). Use the adjacent task instructions to identify the required controls, output, or debugger values.
Snip: Output
Submit a zipped Visual Studio solution after completing the following:
9.Submit a zipped Visual Studio solution after completing the following:
A Ensure that the application has no compiler errors or warnings.
B Make the code StyleCop compliant.
C Remove all bin and obj folders from the entire solution.
Completion review
10.Review the feature acceptance criteria
A Confirm the required results

Return to each story and verify its acceptance criteria. Preserve the submission format and destination stated in the activity; a reading, setup guide, lab, video demonstration, and oral final may require different evidence.

Intro to Delegates Intro to Funcs Intro to Actions Intro to Predicates Paperboy Example Multicasting Use an Action to broadcast news.