All new Windows Phone 7.5 Mango APIs

JustinAngel

Hi folks,

In this article I’d like to present all the new Windows Phone 7.5 Mango APIs. The goal is to inform developers who aren’t familiar with Mango of what new APIs are available. Since there are “1,500” new APIs we won’t be able to deep-dive into APIs with code samples. We’ll examine the new APIs and their related class diagrams. Most APIs should be fairly straightforward to professional .net developers who should be familiar with Microsoft’s API style. Each section of this article will also contain external links for those wishing to learn more about the APIs, featuresets and their usages.

This article is geared towards professional .net developers who want to learn about the WP7.5 Mango release. If you can look at a Microsoft API and figure out what it does, then this article is for you. If can’t look at an API and figure it out, then this article isn’t for you. We won’t have any samples of code usage inline in the article. Though there are external links for most topics.

Using the Framework Design Studio I compared all the WP7.0 (NoDo) assemblies with the WP7.5 (Mango) assemblies. We’ll review those changes in this article.

A new overall class hierarchy has been added to support Sensor readings from various sensors. In WP7.1 we only had Acceleromators. In WP7.5 the API has also been expanded to support the Compasses, Gyroscope and combined “Motion” APIs.

As you can see the new SensorBase<TSensorReading> class is the base class for all the new sensor classes. This architecture is a very elegant solution to making Sensor APIs consistent across multiple devices.

Two new Sensors now supported in WP7.5 are the Gyroscope and Compass APIs. They follow the pattern we just saw above of inheriting from SensorBase<ISensorReading> and implementing their own sensor reading event arguments.

An additional new type of Sensor readings is the new “Motion” API which takes input from all other available sensors and provides sensor-independent motion information. It’s recommended developers use this API whenever applicable to allow apps to work on as many devices as possible regardless of low-level supported sensors.

The original API for WP7 Accelerometer was written back when there was only one Sensor API to support. As you’ve seen there is a new Sensor architectureand some elements of the Accelerometer API are now obsolete in favour of the new Sensor API conventions.

Video cameras as enabled as an extension method on VideoBrush through CameraVideoBrushExtensions.

publicstaticclassCameraVideoBrushExtensions

{

publicstaticvoid SetSource(this VideoBrush brush, Camera camera);

}

CameraButtons expose static events related to the shutter button.

publicstaticclassCameraButtons

{

publicstaticeventEventHandler ShutterKeyPressed;

publicstaticeventEventHandler ShutterKeyHalfPressed;

publicstaticeventEventHandler ShutterKeyReleased;

}

A preview of the current image in the camera is available via the PhotoCamera.GetPreviewBufferYCbCr() method. The information describing the contents of that preview is available through the YCbCrPixelFormat class.

publicsealedclassYCbCrPixelLayout

{

publicint RequiredBufferSize { get; internalset; }

publicint YPitch { get; internalset; }

publicint YXPitch { get; internalset; }

publicint YOffset { get; internalset; }

publicint CbPitch { get; internalset; }

publicint CbXPitch { get; internalset; }

publicint CbOffset { get; internalset; }

publicint CrPitch { get; internalset; }

publicint CrXPitch { get; internalset; }

publicint CrOffset { get; internalset; }

}

The last API for the Camera Mango featureset is the addition of the MediaLibrary.SavePictureToCameraRoll() method. With it developers can create custom camera apps that save to the same location as the WP7 built-in camera app.

There are new background processing related featuresets in mango: Audio, scheduled tasks, background transfers and toasts. As you can see from the diagram above there’s a common base class BackgroundAgent used by the 2 music streaming background agents and the 1 scheduled task background agent. Note that background transfers doesn’t have it’s own publicly exposed background agent.

publicabstractclassBackgroundAgent

{

protectedinternal BackgroundAgent();

protectedvoid NotifyComplete();

protectedvoid Abort();

protectedinternalvirtualvoid OnCancel();

}

As with the rest of the featuresets we’ll be discussing in this article, we won’t review how to create a background agent. Read more on background agents on MSDN’s Background Agents for Windows Phone.

As part of the new Mango featureset to support audio playback while apps are in the background there are 2 new background agents we can inherit from and implement. First is the AudioPlayerAgent that can be used for any media type Windows Phone can directly play from a Uri. The second background agent is AudioStreamingAgent for otherwise unsupported streaming media formats that need some pre-processing (such as shoutcast, icecast and RTSP) using a custom Silverlight MediaStreamSource.

The AudioPlayerAgent receives notifications whenever a user action happens (in the top media bar) and the playback status has changed.

publicenumPlayState

{

Unknown,

Stopped,

Paused,

Playing,

BufferingStarted,

BufferingStopped,

TrackReady,

TrackEnded,

Rewinding,

FastForwarding,

Shutdown,

Error,

}

publicenumUserAction

{

Stop = 1,

Pause = 2,

Play = 3,

SkipNext = 4,

SkipPrevious = 5,

FastForward = 6,

Rewind = 7,

Seek = 8,

}

Whenever the playstate changes or a user action has occurred, the background agent can respond interacting directly with audio playback through the BackgroundAudioPlayer.

publicsealedclassBackgroundAudioPlayer

{

publicvoid Play();

publicvoid Pause();

publicvoid Stop();

publicvoid FastForward();

publicvoid Rewind();

publicvoid SkipNext();

publicvoid SkipPrevious();

publicvoid Close();

publicstatic BackgroundAudioPlayer Instance { get; }

public PlayState PlayerState { get; }

public AudioTrack Track { get; set; }

publicTimeSpan Position { get; set; }

publicdouble BufferingProgress { get; }

publicbool CanPause { get; }

publicbool CanSeek { get; }

publicdouble Volume { get; set; }

publicException Error { get; }

publiceventEventHandler PlayStateChanged;

}

We previously mentioned there are two background audio agents. The first used for straight up Uri playback, and the other for custom MediaStreamSource playback. For the latter you’ll have to use an AudioStreamer in order to provide the MediaStreamSource.

As part of the mango featureset that allows apps to download and upload files while the app is in the background, developers can add new BackgroundTrasnferRequests to the BackgroundTransferService. The BackgroundTransferService will then schedule the download/upload transfers based on the overall transfer queue and network requirements.

It’s also possible to create scheduled tasks where we can execute arbitrary code in a ScheduleTaskAgent.

publicabstractclassScheduledTaskAgent : BackgroundAgent

{

protectedinternalabstractvoid OnInvoke(ScheduledTask task);

[EditorBrowsable(EditorBrowsableState.Never)]

protectedinternaloverridesealedvoid OnCancel();

}

To schedule running a ScheduleTaskAgent use either a PeriodicTask or for more resource intensive tasks (execution time, WiFi-only, device lock, etc) use the ResourceIntensiveTask. Both inherit from ScheduledTask. For more on this topic and the distinction between resource intensive and non-resource intensive tasks see MSDN’s Background Agents Overview for Windows Phone.

Using the new ShellToast class it is possible for background agents to show a toast notification that’ll act as a deep link back to the application. It’s important to mention that this API will not work for in-app notifications, and will only show toast notifications when invoked from a background agent. For more on that see Den Delimarsky’s ShellToast on Windows Phone.

Using the new PhoneDataSharingContext classes it’s possible to search for Appointments and Contacts on the phone, register for a search completed events and check the EventsArgs for the results. We can see the parallels between Appointments and Contacts from the class diagram above. Even though they are both independent they both share the same search-driven architecture. The resulting Contact and Appointment classes are very informative so we’ll address each in its own section in this article.

publicclassPhoneDataSharingContext

{

protected PhoneDataSharingContext(string baseUri);

protectedIEnumerable<T> ExecuteRequest<T>(string query);

protectedstring BaseUri { get; }

}

Both Appointments and Contacts’ search allow to filter based on user accounts with the relevant classes shown here:

The GameInviteTask is an API that can only be used by previously approved Xbox Live titles (currently there are less than 100 of those) to start multiplayer gaming sessions. For more on this task see MSDN’s How to: Use the Game Invite Task for Windows Phone.

publicsealedclassGameInviteTask : ChooserBase<TaskEventArgs>

{

publicoverridevoid Show();

publicstring SessionId { get; set; }

}

The SaveRingtoneTask launches a save dialog for a new phone ringtone based on a Uri. Note that even though the Uri can point to any file Uri there are very specific requirements for the audio file that you’ll want to make sure your ringtone meets. For more information on this task and the aforementioned requirements see MSDN’s How to: Use the Save Ringtone Task for Windows Phone.

Changes and additions to existing Launchers and Choosers

With Mango a few of the existing Launchers and Choosers have received new features. We’ll review these changes in this section.

The MediaPlayerLauncher task can now specify the Orientation of the video player. When trying to playback videos recorded on mobile devices the new portrait setting would be extremely useful.

publicclassMediaPlayerLauncher

{

publicvoid Show();

public Uri Media { get; set; }

public MediaPlaybackControls Controls { get; set; }

public MediaLocationType Location { get; set; }

public MediaPlayerOrientation Orientation { get; set; }

}

publicenumMediaPlayerOrientation

{

Landscape,

Portrait,

}

The EmailComposeTask now allows develoepers to specify suggested BCC emails and the CodePage to be used in globalization scenarios.

publicsealedclassEmailComposeTask

{

publicvoid Show();

publicstring Body { get; set; }

publicstring Bcc { get; set; }

publicstring Cc { get; set; }

publicint? CodePage { get; set; }

publicstring Subject { get; set; }

publicstring To { get; set; }

}

The EmailResult class which is returned from the EmailAddressChooserTask now also contains a DisplayName and in addition to the email address chosen by the user.

publicclassEmailResult : TaskEventArgs

{

public EmailResult();

public EmailResult(TaskResult taskResult);

publicstring Email { get; internalset; }

publicstring DisplayName { get; internalset; }

}

The WebBrowserTask now uses a strongly-typed Uri type property instead of a loosely typed String Url property. For any apps upgraded to Mango that use WebBrowserTask there should be a build warning asking you to switch to the new task.

An interesting hidden feature of this API is that it allows to also modify the primary tile pinned to the phone home page. So if the application itself is pinned to the homepage it’ll be in the ShellTile.ActiveTiles. That’s extremely useful if you want to add a background image and text to the primary tile. More on that is available on Pavel Yosifovich’s blog post Dynamic Live Tiles in Windows Phone 7.

Another change introduced in Mango is adding an overload for ShellTileSchedule so it can work with secondary tiles. Using this new API it is possible to set an interval in which the secondary tile images are updated from a remote server.

With Mango we can now have apps that run both Silverlight content and XNA content. There are two core usecases for this API we need to think about: (1) Adding Silverlight Content (e.g. a menu system) to an XNA game (2) Adding XNA content (e.g. a 3d image) to a Silverlight app. Thinking about these 2 usecases makes it easier to understand the new API introduced for this featureset.

The first step in creating a mixed XNA and Silverlight app is to make sure that SharingMode=Truewhenever we have mixed content rendering on the screen.

As part of Mango Linq-to-SQL running on SQL CE is now supported. Linq2SQL is huge and contains a lot of classes that are new to WP7. We can’t possibly cover all the API for those classes in this article so we’ll just see a huge class diagram and move on. For more information on the core Linq-to-SQL API see MSDN’s Local Database for Windows Phone.

There are however a few Linq-to-SQL APIs that are WP7 specific and we’ll cover those in a bit more depth. All these Linq2SQL WP7 specific APIs are part of the new Microsoft.Phone.Data.Linq and Microsoft.Phone.Data.Linq.Mapping namespaces.

The DatabaseSchemaUpdater is used to make sure that different versions of the application could upgrade the previously installed databases from older versions. When a database is first created it gets the DatabaseSchemaVersion of 0 or any other value you’d like to give it. It is then possible to use that version number to programmatically add database objects (tables, columns, etc) and update the schema version.

publicsealedclassDatabaseSchemaUpdater

{

publicvoid AddTable<T>();

publicvoid AddColumn<T>(string columnPropertyName);

publicvoid AddIndex<T>(string indexName);

publicvoid AddAssociation<T>(string associationPropertyName);

publicvoid Execute();

public DataContext Context { get; }

publicint DatabaseSchemaVersion { get; set; }

}

publicstaticclassExtensions

{

publicstatic DatabaseSchemaUpdater CreateDatabaseSchemaUpdater(

this DataContext dataContext);

}

The next part of WP7 specific Linq-to-SQL API is adding support for database Indexes which doesn’t exist in the desktop version of Linq-to-SQL. This is an important feature since there is no other way to execute DDL (i.e. “create index” statements) on the WP7 SQL CE database. If you expect a high volume of data in a SQL CE Table it’s best to optimize for query scenarios and index the “where” SQL SELECT query columns.

Search Extensibility

If your app has dynamic server data it’s a great idea to expose a few bing consumable XML files on the server that would deep link into your app from the WP7 search. There’s very little new API for the Mango feature that lets WP7 search deep link into apps. The client side changes involve adding the appropriate <Extension> tags to the WmAppManifest and <ExtensionInfo> tags to the Extras file.

Most of the work for this feature would have to happen on the server-side to expose XML files with the appropriate search data and deep links.

Sockets: IP and DNS Addresses

Sockets are a pretty large API and most devs will only work with frameworks based on this API. For these reasons we’ll skip the C# definitions for classes in this namespace and instead focus on overall featuresets and class diagrams.

As Sockets are all about direct communication between WP7 and a remote machine DNS and IP addresses classes have been introduced to Mango.

There are parts of the application UI that are actually part of the OS shell. The top “SystemTray” and the bottom “ApplicationBar” are two such UI elements.

The ApplicationBar class has added support to show the ApplicationBar as collapsed (similar to how it’s shown in the Music & Video hub) and specify the height used for both the default and minimal mode.

The SystemTray previously only had an IsVisible property to hide the top bar. The main reason why app developers hid the top bar in apps was due to a theme colour clash. So with Mango you can use your brand colours on the SystemTray by setting the new attached dependency properties. As a reminder a pattern of a static GetFoo, SetFoo and FooProperty members is an attached dependency property pattern.

A SystemTray.ProgressBar can be set to show a unified WP7 UI for any in-app process progress taking place (e.g. web requests). An example of how to do so can be found on MSDN’s ProgressIndicator Class.

Bing Maps changes: Random XAML elements positioning

With Mango the Bing Maps SDK has had only 1 change in it. Attached Dependency properties have been added to the MapPlayer class that allow to position random XAML elements in a latitude and longitude coordinate or relative to the rest of the map.

Removing Pages from the backstack frame journal

A common requirement in NoDo was to block the automatic frame navigation from navigating back into certain pages (e.g. splash page, registration page, etc). There are a few tricks in NoDo that allowed for a decent UX in the absence of any API for directly controlling the backstack. With Mango it is now possible to remove the last page from the back stack.

Xbox Live: Render Xbox Live Avatars in XNA

With the introduction of Microsoft.Xna.Framework.Avatar assembly it is now possible for Xbox Live Titles to render Xbox Live Avatars using the new AvatarRenderer class. Note, only Xbox Live Titles can use this functionality. Because of that limited subset of apps that have access to this functionality and because of the sheer size of the new assembly we’ll only briefly glance at a class diagram and move on.

Xbox Live: Avatar Assets

Xbox Live-titles (and only xbox live titles) can now take advantage of the new SignedInGamerExtensions and award assets to Xbox Live Avatars. Again, this feature is only available for Xbox-Live titles.

Custom Linq Providers

A core piece of LINQ that has been missing from NoDo was the ability to create custom Linq Providers. With Mango the IQueryProvider and IQueryable interfaces have been added. With the new support for custom LINQ providers it is now possible to use one of the many open source LINQ providers. for more on implementing a custom LINQ provider and the importance of IQueryProvider see Matt Warren’s LINQ: Building an IQueryable Provider.

publicinterfaceIQueryProvider

{

IQueryable CreateQuery(Expression expression);

IQueryable<TElement> CreateQuery<TElement>(Expression expression);

object Execute(Expression expression);

TResult Execute<TResult>(Expression expression);

}

publicinterfaceIQueryable : IEnumerable

{

Expression Expression { get; }

Type ElementType { get; }

IQueryProvider Provider { get; }

}

The additional classes of EnurableQuery, EnurableQuery<T>, EnurableExecutor, EnumrableExecutor<T> and Queryable are all helper classes used when implementing a custom LINQ provider. We won’t expend on them further in this blog post.

Dynamically compiled Lambda Expressions and Reflection.Emit

A small chunk of Refleciton.Emit has been added to Mango in order to enable the Expression.Compile() method. Using Expression.Compile() it is possible to build at runtime an expression tree, compile it and then execute it. All at runtime. We’ll only examine the change to LambdaExpression in greater detail. For more information on this topic see MSDN’s Expression(TDelegate).Compile Method.

mscorib.Extensions: SIMD/ARM-NEON XNA support

Mango allows to accelerate calculation operations on SIMD/ARM-NEON capable devices. Which means that XNA calculations on Vector, Matrix and other types would be somewhat faster. To take advantage of this new feature apply the attribute wit he SIMD flag on the relevant assemblies. For more on this see Enable SIMD support in Mango.

mscorlib.Extensions: INotifyPropertyChanging

The INotifyProperyChanging interface has been added as part of Mango. This API is the counterpart for the existing INotifyPropertyChanged interface. Currently the only feature using this new interface is Linq-to-SQL, but we could definitely take advantage of it for other 3rd party usages. For more on that see Claus Konrad’s WP7/7.1: Where is INotifiyPropertyChanging defined?.

WP7 NoDo was based on Silverlight 3. With the release Mango all the changes done in Silverlight 4 were migrated back to WP7. Most of the changes are in the System.Windows assembly (Silverlight) and the majority of other changes are in the mscorlib BCL (base class library) assembly. All the changes made in Silverlight 4 to the BCL were additions of new members to existing classes. The one exception to that is the removal of the TaiwanCalender class from Mango. The class diagram and code snippets below contain only the new members added to the BCL in Mango.

Silverlight 4 is it’s own product release and quite an extensive one at that. We’ll briefly cover the new API added to the System.Windows assembly as part of the Mango upgrade to Silverlight 4. For those of you interested in more details on Silverlight 4 changes from Silverlight 3 see Tim Heuer’s Silverlight 4 Beta – A guide to the new features. Please note, the API we’ll see in this section is the API that was added in Mango and not all the API in these classes.

In the System.Collections.ObjectModel namespace we’ve got new constructors for the ObservableCollection class that allow to easy convert a standard List<T> to an ObservableCollection<T>.

publicclassObservableCollection<T>

{

publicObservableCollection<T>(List list);

publicObservableCollection<T>(IEnumerable collection);

}

In the System.ComponentModel namespace we’ve got a few new APIs for databinding and some additions to design-time.

publicsealedclassAlternateContentPropertyAttribute : Attribute

{

public AlternateContentPropertyAttribute();

}

publicsealedclassDataErrorsChangedEventArgs : EventArgs

{

public DataErrorsChangedEventArgs(String propertyName);

publicString PropertyName { get; }

}

publicstaticclassDesignerProperties

{

publicstaticBoolean RefreshOnlyXmlnsDefinitionsOnAssemblyReplace

{

get;

}

}

publicinterfaceICollectionViewFactory

{

ICollectionView CreateView();

}

publicinterfaceIDataErrorInfo

{

String Error { get; }

Stringthis[String columnName] { get; }

}

publicinterfaceIEditableCollectionView

{

Boolean CanAddNew { get; }

Boolean CanCancelEdit { get; }

Boolean CanRemove { get; }

Boolean IsAddingNew { get; }

Boolean IsEditingItem { get; }

NewItemPlaceholderPosition NewItemPlaceholderPosition { get; set; }

Object CurrentAddItem { get; }

Object CurrentEditItem { get; }

Object AddNew();

void CancelEdit();

void CancelNew();

void CommitEdit();

void CommitNew();

void EditItem(Object item);

void Remove(Object item);

void RemoveAt(Int32 index);

}

publicinterfaceINotifyDataErrorInfo

{

Boolean HasErrors { get; }

IEnumerable GetErrors(String propertyName);

eventEventHandler ErrorsChanged;

}

publicinterfaceISupportInitialize

{

void BeginInit();

void EndInit();

}

publicenumNewItemPlaceholderPosition

{

None,

AtEnd

}

There are quite a bit of peer automation related changes in the System.Windows.Automation.* namespaces, but since Automation Peers are not supported on WP7 there’s no point in going over those in any great detail.

In the System.Windows namespace we have a few changes: Support for the new Tap & Hold & DoubleTap events, programmatic control of the Clipboard, Right-To-Left support and a few others. There are also a few “junk” changes to support features that aren’t supported in Mango and we won’t review those here.

publicstaticclassClipboard {

publicstaticBoolean ContainsText();

publicstaticString GetText();

publicstaticvoid SetText(String text);

}

publicclassDependencyObjectCollection<T>

{

publicvirtualsealedInt32 IndexOf(T item);

publicvirtualsealedvoid Insert(Int32 index, T item);

publiceventNotifyCollectionChangedEventHandler CollectionChanged;

}

publicenumFlowDirection {

LeftToRight,

RightToLeft

}

publicabstractclassFrameworkElement : UIElement {

publicFlowDirection FlowDirection { get; set; }

publicstaticreadonlyDependencyProperty FlowDirectionProperty;

}

publicabstractclassUIElement : DependencyObject

{

publiceventEventHandler DoubleTap;

publiceventEventHandler Hold;

publiceventEventHandler Tap;

publiceventTextCompositionEventHandler TextInput;

publiceventTextCompositionEventHandler TextInputStart;

publiceventTextCompositionEventHandler TextInputUpdate;

publicstaticreadonlyDependencyProperty AllowDropProperty;

publicstaticreadonlyRoutedEvent DoubleTapEvent;

publicstaticreadonlyRoutedEvent HoldEvent;

publicstaticreadonlyRoutedEvent TapEvent;

publicstaticreadonlyRoutedEvent TextInputEvent;

publicstaticreadonlyRoutedEvent TextInputStartEvent;

publicstaticreadonlyRoutedEvent TextInputUpdateEvent;

}

publicsealedclassVisualStateGroup : DependencyObject

{

publicVisualState CurrentState { get; }

}

The System.Windows.Controls and System.Windows.Controls.Primitives namespace has a few changes in it: The new ViewBox control, addition of ellipsis (“…”) text trimming to TextBlock, MVVM Button Commanding support, Video playback MediaElement timed markers and a few other features. The really interesting changes here is the introduction of a WP7 API for ScrollViewer.ManipulationMode for fine-tuned scrolling support on the phone. The ScrollViewer additions are exclusive to WP7 Mango.

In System.Windows.Documents a new RichTextBox control and many supporting classes have been added. We won’t review this control and it’s associated classes in-depth. For more information on this control see MSDN’s RichTextBox Overview.

In System.Windows.Data namespace there’s really one thing we care about: The addition of 5 new properties to the {Binding} syntax. There’s also a few other “junk” changes that aren’t applicable for WP7. which we won’t review here.

publicclassBinding : BindingBase

{

publicBoolean ValidatesOnDataErrors { get; set; }

publicBoolean ValidatesOnNotifyDataErrors { get; set; }

}

publicabstractclassBindingBase

{

publicObject FallbackValue { get; set; }

publicObject TargetNullValue { get; set; }

publicString StringFormat { get; set; }

}

A big part of the changes done in System.Windows.Media namespace is around the introduction of VideoSink and AudioSink. In WP7 these provide access to the Microphone and Camera which are available through more phone specific APIs so it’s best to avoid these if possible.

There are few interesting changes in the System.Windows.Media namespace: support for Playready DRM DomainAcquirer, support for RichTextBox support for all fonts, The VideoBrush and a VisualTreeHelper.GetOpenPopups() method.

The System.Windows.Input namespace has a few interesting additions as-well: 2 new input scopes have been added, fine-grained control of IME (use of Latin keyboards for Asian languages input) and a few other changes.