DCSIMG
June 2011 - Posts - Alex Golesh's Blog About Silverlight Development

June 2011 - Posts

Windows Phone Mango – New Tasks (Beta & Beta2)

Windows Phone Mango adds few more task over initial Windows Phone (RTM) release. This post will cover new task (launchers and choosers) added to Windows Phone Mango Beta and Beta 2.

To introduce those features I’ve created sample application which looks very simple, yet have all those new tasks:

image

Before we are starting, one very important note about tasks in general. Some of them works on emulator as on real device (Bing maps, Bing directions, etc.), some of them works but doesn’t produce any “visible” output and cannot been verified (Save Ringtone) and some of them are not working at all. In order to take full advantage of task please consider using windows phone mango developer enabled device.

Let’s see the new tasks one by one. GameInviteTask used to display game invite screen to invite users into a multiplayer game session. This task works also for non-game scenarios, and in this case serves as application promotion:

private void btnGameInvite_Click(object sender, RoutedEventArgs e)

{

    GameInviteTask gameInviteTask = new GameInviteTask();

    gameInviteTask.SessionId = "SomeSessionID";

    gameInviteTask.Completed += new EventHandler<TaskEventArgs>(gameInviteTask_Completed);

    gameInviteTask.Show();

}

 

void gameInviteTask_Completed(object sender, TaskEventArgs e)

{

    if (null == e.Error)

    {

        MessageBox.Show(string.Format("Invite {0}sent!", (e.TaskResult == TaskResult.Cancel ? "not " : "")));

    }

    else

        MessageBox.Show("Error sending invite!");

}

This code snippet presents the following UI:

image

Next the Bing-related tasks. Many time you application want to present some geographic location without including Bing maps control into the application. In such case in Mango we can leverage BingMapsTask. This task uses search term to locate the point of interest and optionally zoom level and geographical position for centering the map and shows it on separate screen:

private void btnBingMaps_Click(object sender, RoutedEventArgs e)
{
    BingMapsTask bingMapsTask = new BingMapsTask();
            
    bingMapsTask.SearchTerm = "Eiffel Tower, Paris, France";
    bingMapsTask.ZoomLevel = 21;
    bingMapsTask.Show();
}

Executing the task leads to the following result:

image

If you application needs to provide driving/walking directions it can be achieved using BingMapsDirectionsTask:

private void btnBingDirections_Click(object sender, RoutedEventArgs e)
{
    BingMapsDirectionsTask bingMapsDirectionsTask = new BingMapsDirectionsTask();
    LabeledMapLocation start = new LabeledMapLocation();
    GeoCoordinate startLocation = new GeoCoordinate(48.51489, 2.1767119);
    start.Label = "Eiffel Tower, Paris, France";
    start.Location = startLocation;
 
    LabeledMapLocation end = new LabeledMapLocation("Louvre, Paris, France",
        new GeoCoordinate(48.516396, 2.2026199));
 
    bingMapsDirectionsTask.Start = start;
    bingMapsDirectionsTask.End = end;
    bingMapsDirectionsTask.Show();
}

Note: Your application can use GeoCoordinateWatcher class to resolve current device position and set it as start location for directions task.

The result presented as navigation sequence supported by voice directions:

image

Last Beta task is SaveRingtoneTask. This task enables your application to add custom ringtones to your device. The sound files should be placed in application data or isolated storage. In this sample I’ve added sample MP3 file as a content resource to my application and copy it into my application IsolatedStorage before executing the task:

private void btnSaveRingtone_Click(object sender, RoutedEventArgs e)
{
    using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
    {
        Stream str = Application.GetResourceStream(new Uri("Sound/Sound.mp3", UriKind.Relative)).Stream;
 
        IsolatedStorageFileStream outFile = iso.CreateFile("Ring.mp3");
 
        outFile.Write(ReadToEnd(str), 0, (int)str.Length);
        str.Close();
        outFile.Close();
    }
 
    SaveRingtoneTask ringtoneTask = new SaveRingtoneTask();
 
    ringtoneTask.Source = new Uri("isostore:/Ring.mp3", UriKind.Absolute);
 
    ringtoneTask.Show();
}
 
private static byte[] ReadToEnd(System.IO.Stream stream)
{
    long originalPosition = stream.Position;
    stream.Position = 0;
    try
    {
        byte[] readBuffer = new byte[4096];
        int totalBytesRead = 0;
        int bytesRead;
 
        while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
        {
            totalBytesRead += bytesRead;
            if (totalBytesRead == readBuffer.Length)
            {
                int nextByte = stream.ReadByte();
                if (nextByte != -1)
                {
                    byte[] temp = new byte[readBuffer.Length * 2];
                    Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
                    Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
                    readBuffer = temp; totalBytesRead++;
                }
            }
        }
 
        byte[] buffer = readBuffer;
 
        if (readBuffer.Length != totalBytesRead)
        {
            buffer = new byte[totalBytesRead];
            Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
        }
 
        return buffer;
 
    }
    finally
    {
        stream.Position = originalPosition;
    }
}

image

Note: this is one of those tasks, which actually works on emulator, but cannot be verified – the emulator simply have no interface to check the ringtones.

Now let’s see Beta 2 additions. In Beta 1 we got an ability to search for contacts (I’ve blogged about it here). Now we can populate a new contact data and enable user simply saving it:

private void btnSaveContact_Click(object sender, RoutedEventArgs e)
{
    SaveContactTask saveContactTask = new SaveContactTask();
    saveContactTask.Company = "Sela Group";
    saveContactTask.FirstName = "Alex";
    saveContactTask.LastName = "Golesh";
    saveContactTask.JobTitle = "Senior Consultant, Mobile Division Manager";
    saveContactTask.WorkEmail = "alexg@sela.co.il";
    saveContactTask.Website = "http://blogs.microsoft.co.il/blogs/alex_golesh/";
    saveContactTask.Nickname = "@DevCorner";
    saveContactTask.Completed += new EventHandler<SaveContactResult>(saveContactTask_Completed);
    saveContactTask.Show();
}
 
void saveContactTask_Completed(object sender, SaveContactResult e)
{
    if (null == e.Error)
    {
        MessageBox.Show(string.Format("Contact {0}saved!", (e.TaskResult == TaskResult.Cancel ? "not " : "")));
    }
    else
        MessageBox.Show("Error saving contact!");
}

User presented with the following UI which enables him to change any suggested values and save the contact:

imageimage

Last two are about social features. They enabling to share user status and link (on Windows Live, Facebook, etc. for example):

private void btnShareStatus_Click(object sender, RoutedEventArgs e)
{
    ShareStatusTask shareStatusTask = new ShareStatusTask();
    shareStatusTask.Status = "My phone just turn fruit!";
    shareStatusTask.Show();
}

 

private void btnShareLink_Click(object sender, RoutedEventArgs e)
{
    ShareLinkTask shareLinkTask = new ShareLinkTask();
    shareLinkTask.Message = "Visit my blog for new Windows Phone ‘Mango’ content!";
    shareLinkTask.Title = "My Blog";
    shareLinkTask.LinkUri = new Uri("http://blogs.microsoft.co.il/blogs/alex_golesh/", UriKind.Absolute);
    shareLinkTask.Show();
}

ShareStatusTask enables to change current status line and ShareLinkTask enables sharing some link along with title and description:

image

Note: those two launchers doesn’t works on the emulator – they are not producing any changes since there is no way to connect the emulator to the Live/Facebook accounts. You will need real Mango device connected to Facebook in order to check it.

 

Sources for this sample hosted here.

 

Stay tuned for more to come.

Alex

Windows Pone Mango–Developer Tools Beta 2 released!

Microsoft just released Beta 2 refresh of Windows Phone Mango developer tools!

The refresh further improves the tools, resolves bugs from previous release and adds some new features.

Most important – registered Windows Phone developers with retail device will get access to Mango updates via invites to Microsoft Connect site which will give them access to Mango for their retail devices!

Also, the release brings some breaking changes which we as developers need to be aware of. Here are the list of some breaking changes:

Change Improvement Resolution
Image decoding moved to the background thread Enables more responsive UI If background loading of an image is not suitable, change the CreateOptions of the image from BackgroundCreation to DelayCreation in either the XAML or the code-behind.
Asynchronous web client request that was generated on a background thread returns to the background thread pool. Enables complete background processing of downloads and leads to more responsive UI In code that relies on the response returning on the UI thread, marshal the response using Dispatcher.BeginInvoke
The OnCancel override method was removed from the ScheduledTaskAgent class   Remove this method from your application code
The MotionReading property types have changed This change eliminates the dependency between MotionReading, AccelerometerReading, and GyroscopeReading Code that uses the MotionReading class must change to use the new types and name
The Background Transfer Service folder in isolated storage was renamed This change groups all services that access files in the isolated storage under “Shared” Change all references from DownloadLocation, UploadLocation, and the source URI of the BackgroundTransferRequest constructor to point to “Shared\Transfers” instead of “Transfers”.
Tile data in isolated storage must use the folder Shared\ShellContent This change groups all services that access files in the isolated storage under “Shared”

Change all references from BackBackgroundImage and BackgroundImage to point to Shared\ShellContent. For example:   
BackgroundImage  image = new Uri("isostore:/Shared/ShellContent/TileBackground.jpg", UriKind.Absolute)

The ShellTileEnumerator class was removed The standard IEnumerable<T> interface is all that is needed when using the ShellTile.ActiveTiles Enumerate ActiveTiles by using the recommended IEnumerable patterns such as for-each
Background agents are not launched in the debugger by using the Add and Find methods The new LaunchForTest method makes it easier to debug background agents Use the LaunchForTest() method to debug background agents. For example:
PeriodicTask periodicTask = new PeriodicTask("TheWorker");
periodicTask.Description = "The worker task";
periodicTask.ExpirationTime = DateTime.Now.AddDays(1);
 
ScheduledActionService.Add(periodicTask);
 
if (System.Diagnostics.Debugger.IsAttached)     
ScheduledActionService.LaunchForTest("TheWorker", TimeSpan.FromSeconds(10));
Hardware camera button events removed from PhotoCamera class New CameraButtons static class enables same creating shared event handlers for hardware button events functionality Application code which uses PhotoCamera’s “OnButtonHalfPress”, “OnButtonFullPress”, and “OnButtonRelease” should use corresponding new events from CameraButtons’ “ShutterKeyHalfPressed”, “ShutterKeyPressed” and “ShutterKeyReleased”. For example:

//Event is fired when the button is half pressed
CameraButtons.ShutterKeyHalfPressed += camera_ButtonHalfPress;

//Event is fired when the button is fully pressed
CameraButtons.ShutterKeyPressed += camera_ButtonFullPress;

In addition, the Beta 2 adds some new launchers and choosers which will be covered in additional post.

Download Windows Phone Developer Tools Beta 2 here.

Stay tuned to more to come!

Alex