I always get very interesting questions from the readership, and while I love answering emails, I don’t always have time to give people specific examples but like to set them on the right track…
Question of the Day:
from an iPhone/Objective-C developer
“I'm very new to Windows Phone 7. But does c# support Bindings like KVO and KVC
This is something I like about objective-c..”
Well most of you here in the .NET community who don’t look into native coding may not quite know what KVO and KVC are..
Key-Value Observing (KVO) and Key-Value Coding (KVC) are two very important concepts in Objective-C and are vital if you want to use technologies such as bindings or Core Data in your projects.
Keys and Values
Objects in Objective-C can have instance variables, or attributes, that help define the state of the object.
Key-Value Observing
This ability to refer to variables by their key is very powerful.
Here’s a look at doing this using iPhone/Cocoa coding and how binds work.
How do we do this with Windows Phone 7 is there a similar concept ?
Enter Reactive Extensions (Rx for short)
What is RX Framework? What is Reactive Programming?” What is Linq to events ?
The Reactive Extensions for .NET Framework is a library for composing asynchronous and event-based programs using observable collections.
Most smartphone programming requires asynchronous coding.. You call something, wait until it completes then get back the results (yeah there’s more to it than this but that’s what I will tell you for now).
PUSH vs. PULL
IEnumerable’s are sequences of data that we pull from a data source.
IObservable’s are sequences of data that are pushed onto us.
The IEnumerable Interface
. Almost every collection implements the IEnumerable interface and we use it every time we write a foreach. You can also use Linq (language integrated query) to query IEnumerables.
int[] numbers = new int[]{31,5,16};
IEnumerable<int>
smallerthansixteen = numbers.Where(number => number < 16);
The results would come out:
5
In addition to finite sequences it can sometimes be useful to create sequences that never end. Take this method that returns an infinite sequence of integers:
IEnumerable<int> NaturalNums()
{
int number = 0;
while(true)
{
yield return number;
number++;
}
}
Results:
0,1,2,3,4,5,6…
We don’t always pull data though. Often it is pushed onto us and we must react appropriately. This is called “Reactive Programming.”
Often it is pushed onto us and we must react appropriately. This is called “Reactive Programming.”
Events and Callbacks (as data)
The data passed to event handlers and callbacks can be thought of as sequences of data that are “pushed” at you rather than “pulled.” Every time an event is fired we get “pushed” a new piece of data: the EventArgs. Similarly when a callback is invoked it is typically “pushed” the result of the asynchronous method. You can think of an event as a sequence of EventArgs that never ends just like the NaturalNums sequence.
http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx
Applying this to Windows Phone 7
Quoting MSDN:
“The Reactive Programming Model
If your application interacts with multiple sources of data, such as user input events, web services requests, and system notifications, the conventional way to manage all of these interactions is to implement separate handlers for each of these data streams. Inside these handlers, you must provide the code to coordinate between all of the different data streams and process this data into a useable form. Reactive Extensions allows you to write a query that combines all of these data streams into a single stream that triggers a single handler. The work of filtering, synchronizing, and transforming the data is performed by the Reactive Extensions query so that your handler can just react to the data it receives and do something with it.
Mobile Scenarios for Reactive Extensions
Reactive Extensions is a programming model that has applications for a broad range of applications, but it can be particularly useful for applications that run on mobile devices, because they tend to function as a hub for receiving and processing a user’s data from multiple sources. This section will highlight some Reactive Extensions scenarios that are of particular interest to Windows Phone developers.
Filtering Events
The Microsoft Location Service exposes an event that will notify your application when location data is obtained. The built-in API lets you filter the data and allows you to request to be notified only if the location data changes by at least a specified amount. Reactive Extensions lets you further filter the events so that, for example, you could have your application be notified only when the location falls within a specified bounding rectangle. Reactive Extensions lets you define a query that filters a data stream so that only the data that meets the specified criteria ends up in the final stream. For an example of using Reactive Extensions with the Location Service, see How to: Use Reactive Extensions to Emulate and Filter Location Data for Windows Phone.
Composing Multiple Asynchronous Web Service Requests
Applications for mobile devices are often created by blending together the content and functionality from multiple Web services. The amount of time it will take for a web service to return a request is unpredictable by nature as it depends on the connection speed of the device, internet traffic, and the implementation of the service itself. Reactive Extensions enables you to make some number of web service requests and only receive responses that fall within a specified time window. You could also use it to compose search queries so that a search that is posted to multiple web services will return to your app once a specified minimum number of the search queries have returned.
Emulating Data Streams
Application development for mobile devices can be challenging because of the many conditions applications face in the working environment that are not present in the development environment. Accelerometer and location data, for example, can be difficult to simulate when developing applications on a device emulator. Because the Reactive Extensions model wraps consumers and producers of data into observer and observable objects with a defined interface, it is possible to write a consumer, such as a handler for accelerometer data, and swap out the producer, from a file stream containing simulated data to the live sensor, with very little overhead.”
Microsoft’s Accelerometer Sample for filtering data with Reactive Extensions
This full example can be found in whole at Microsoft’s MSDN page for the sample:
http://msdn.microsoft.com/en-us/library/ff637521(VS.92).aspx
The sample I am pointing to converts live accelerometer data and emulated data to Observable sequences, which the application can subscribe to and handle with event handlers. One of the advantages of using Reactive Extensions is that there are many built in operations for filtering and manipulating Observable sequences.
In the click handler for the start button, the following three lines of code are used to obtain the sequence and subscribe to it.
IObservable<IEvent<AccelerometerReadingAsyncEventArgs>> accelerometerReadingAsObservable =
Observable.FromEvent<AccelerometerReadingAsyncEventArgs>(
ev => accelerometer.ReadingChanged += ev,
ev => accelerometer.ReadingChanged -= ev);
var vector3FromAccelerometerEventArgs = from args in accelerometerReadingAsObservable
select new Vector3((float)args.EventArgs.Value.Value.X, (float)args.EventArgs.Value.Value.Y, (float)args.EventArgs.Value.Value.Z);
vector3FromAccelerometerEventArgs.Subscribe(args => InvokeAccelerometerReadingChanged(args));
With more code, you can scan the data stream to compare each data value to the previous one, converting the stream from a list of vectors describing the orientation of the phone to a list of vectors describing the difference, or delta, between the phone’s current orientation and its previously measured orientation. Adding another line will let you select only the values for which the delta is greater than a specified value. This allows you to only receive events when a sudden, forceful movement of the phone is made.
// Use the Scan method to take compare each element to the previous one
var deltas = vector3FromAccelerometerEventArgs.Scan(new { last = new Vector3(), delta = new Vector3() },(state, current) =>
{
var last = current;
var delta = new Vector3(current.X - state.last.X, current.Y - state.last.Y, current.Z - state.last.Z);
return new { last, delta };
}
);
// Use from, where, and select, to choose only deltas greater than a specified value
var largeDeltas = from d in deltas
where d.delta.Length() > 1.0
select d.delta;
// Subscribe to the new Observable sequence
largeDeltas.Subscribe(args => InvokeAccelerometerReadingChanged(args));
Pretty cool huh? Not a lot of code and very manageable..
References for Reactive Extensions:
http://www.silverlightshow.net/items/Using-Reactive-Extensions-in-Silverlight.aspx
Using Reactive Extensions with Web Services:
http://www.silverlightshow.net/items/Using-Reactive-Extensions-in-Silverlight-part-2-Web-Services.aspx
http://themechanicalbride.blogspot.com/2009/07/introducing-rx-linq-to-events.html
http://themechanicalbride.blogspot.com/2009/10/silverlight-drag-drop-support-part-2.html
http://themechanicalbride.blogspot.com/2009/08/joy-of-rx-building-asynchronous-service.html
http://www.silverlightshow.net/items/Using-Reactive-Extensions-in-Silverlight.aspx
http://msdn.microsoft.com/en-us/library/bb308959.aspx
http://msdn.microsoft.com/en-us/library/ff431792(VS.92).aspx
http://msdn.microsoft.com/en-us/library/ff637517(v=VS.92).aspx
http://msdn.microsoft.com/en-us/library/ff431782(v=VS.92).aspx
http://www.theleagueofpaul.com/blog/2010/09/02/mahapps-twitter-library-for-windows-phone-7-wip/
Got what you need here?
Still need to roll your own KVO/ KVC implementation?
Check out this great article from Daniel Kennett:
http://danielkennett.org/blog/2009/08/knkvc-implementing-key-value-coding-and-key-value-observing-in-c-net/
and the code at:
http://www.kennettnet.co.uk/code/KNKVC/

Thanks to Daniel Kennett for this more info can be found at his blog:
http://danielkennett.org/blog/2009/08/knkvc-implementing-key-value-coding-and-key-value-observing-in-c-net/
OATH AND TWITTER AND KEY PAIRS
If you are using this capability to watch over values to get updated check out this Windows Phone 7 implementation of oath at Mark Arteaga’s blog…
http://blog.markarteaga.com/OAuthWithSilverlightForWindowsPhone7.aspx
Confused yet? There is a lot of information to cover… Look for more follow up..