Windows Phone 7 – How to find the device unique id windows live anonymous Id and manufacturer

This post details how to use DeviceExtendedProperties and UserExtendedProperties classes from the Microsoft.Phone.Info namespace to find a WP7 device manufacturer, device unique Id and users Anonymous Windows Live ID as follows:

To be able to obtain the Device Unique ID and Windows Live Anonymous ID you must first add the capabilities to do this to your WMAppManifest.xml file within your WP7 project as follows:

    <Capabilities>
      ...
      <Capability Name="ID_CAP_IDENTITY_DEVICE"/>
      <Capability Name="ID_CAP_IDENTITY_USER"/>
      ...
    </Capabilities>

One important point to note is that you should only really use the device unique id and anonymous windows live Id in your application if really requires it. The reasoning on msdn is as follows:

DeviceExtendedProperties requires the device identity capability. If your application uses this class, the user will be alerted that the application requires access to the device identity when viewing your application on Windows Phone Marketplace. For this reason, it is recommended that you use this class only if your application requires it.

Note: In the example below the manufacturer is returned from GetManufacturer without needing to list the device identity capability within the WMAppManifest but if you tried to get the device Id onr anonymous Id without the capability it will throw an UnauthorizedAccessException.

The following code example demonstrates how to retrieve the Device Manufacturer, Device Unique ID and Windows Live Anonymous ID

using Microsoft.Phone.Info;
namespace NickHarris.Net
{
    public static class ExtendedPropertyHelper
    {
        private static readonly int ANIDLength = 32;
        private static readonly int ANIDOffset = 2;
        public static string GetManufacturer()
        {
            string result = string.Empty;
            object manufacturer;
            if (DeviceExtendedProperties.TryGetValue("DeviceManufacturer", out manufacturer))
                result = manufacturer.ToString();

            return result;
        }

        //Note: to get a result requires ID_CAP_IDENTITY_DEVICE
        // to be added to the capabilities of the WMAppManifest
        // this will then warn users in marketplace
        public static byte[] GetDeviceUniqueID()
        {
            byte[] result = null;
            object uniqueId;
            if (DeviceExtendedProperties.TryGetValue("DeviceUniqueId", out uniqueId))
                result = (byte[])uniqueId;

            return result;
        }

        // NOTE: to get a result requires ID_CAP_IDENTITY_USER
        //  to be added to the capabilities of the WMAppManifest
        // this will then warn users in marketplace
        public static string GetWindowsLiveAnonymousID()
        {
            string result = string.Empty;
            object anid;
            if (UserExtendedProperties.TryGetValue("ANID", out anid))
            {
                if (anid != null && anid.ToString().Length >= (ANIDLength + ANIDOffset))
                {
                    result = anid.ToString().Substring(ANIDOffset, ANIDLength);
                }
            }

            return result;
        }
    }
}

Other Extended Device information that can be retrieved using this class are:

    DeviceName
    DeviceUniqueId – if you are after an id to identify the user you should not use this, use Microsoft.Phone.Info.UserExtendedProperties with a parameter of “ANID”
    DeviceFirmwareVersion
    DeviceHardwareVersion
    DeviceTotalMemory
    ApplicationCurrentMemoryUsage
    ApplicationPeakMemoryUsage

More details on these extended properties can be found here

Nick

Happy 10000 hits time to introduce the team

Hi there, 

Today the team here at www.NickHarris.net made it to the 10,000 hit milestone 

Hit Graph

Hit Graph

We decided to down tools and celebrate with a team photo: 

Team photo

Team photo

Thats an ROI of 10000/10 = 1000 per team member 

And of course the blog would not be complete without mentioning that the photo was taken using a MS lifecam and a custom Silverlight App using the System.Windows.Media namespace specifically CaptureSource, VideoCaptureDevice and CaptureSource.CaptureImageAsync method 

If you’re sad because this blog post is coming to an end and your just not sure what to do with yourself then I can recommend that you go checkout this excellent .NET Blog www.thatdotnetguy.com

Now time to get back to that unpaid job of mine :)  

Nick

Search Marketplace on Windows Phone 7 with the MarketplaceSearchTask

This describes the straightforward task of how to search Microsoft Marketplace on Windows Phone 7 using the MarketpalceSearchTask. You should note that you can search by keyword and ContentType. Two usage examples would be as follows:

Example 1: Search Marketplace for “Rock” that is of content type Music – allows interesting application scenarios to be developed particularly for record labels like SONY
Example 2: Search Marketplace for “Your Company Name” that is of content type Application – useful if you want users of your application to be able to find other applications by you/your company.

Implementing Example 1:

  1. Add using statement to the Tasks namespace
  2. using Microsoft.Phone.Tasks;
  3. Create an instance of MarketplaceSearchTask set the ContentType and SearchTerms properties then call Show:
  4.     MarketplaceSearchTask mst = new MarketplaceSearchTask();
        mst.ContentType = MarketplaceContentType.Music;
        mst.SearchTerms = "Rock";
        mst.Show();
  5. Result: The first screen is the result, with the second screen being the resul of clicking on Rock Classic 100.
  6. MarketplaceSearchTask search for Rock Music

    MarketplaceSearchTask search for Rock Music

Implementing Example 2:
To search for applications all you need to do is change the mst.ContentType = MarketplaceContentType.Applications; and update the Search property

Note: if you have a specific target in marketplace in mind you can use MarketplaceDetailTask.

Enjoy,
Nick

Asynchronous Image download on Windows Phone 7

When running your solution on local and setting the Source property of the System.Windows.Controls.Image it is not visually apparent that the Image may take some period of time to download simplifying the code the following the original image swap out whereby i was using an arbitrary Uri to an image in Azure Blob Storage that would change at a predefined interval.

imgContent.Source = new BitmapImage(new Uri(arbitraryImageUriThatKeepsChanging));

As soon as the image is available from Azure Blob Storage – or any other hosting provider for that matter if you are not using a CDN and are a long way from your host then or the image is of a large size then it is likely that as soon as the image is set the image content becomes empty until the image is downloaded – i found this to be 10 to 30 seconds over the slow bandwidth of my phone.  To have an empty Image control on the screen was not acceptable so the simple solution is to pull down the image asynchronously using a WebClient then once downloaded update the Image.Source as follows:

Starting the Async download of the image:

WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
wc.OpenReadAsync(new Uri(arbitraryImageUriThatKeepsChanging), wc);

Handling the completed download and updating the image source – note: have intentionally removed the MVVM implementation here to minimise code in post if using MVVM setup the binding on the Image.Source property to the model Source.

void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
   if (e.Error == null && !e.Cancelled)
  {
      try
      {
         BitmapImage image = new BitmapImage();
         image.SetSource(e.Result);
         imgContent.Source = image;
      }
      catch (Exception ex)
      {
          //Exception handle appropriately for your app
      }
  }
  else
  {
      //Either cancelled or error handle appropriately for your app
  }

Async download of Images from Azure to windows phone.

Note: WebClient executes on the UI thread if you wish to do this on a background thread and then later update the UI you should use HttpWebRequest and then Dispatcher within your response to update the UI thread.

Note: It would be interesting to configure the Azure CDN to see the improved performance once the node is distributed from a CDN node that is geographically close.

Nick

How to Enable IntelliTrace on Windows Azure

If your Azure project targets the .NET framework 4.0 you can utilize IntelliTrace to help debug your application. This post briefly covers how to enable and retrieve your IntelliTrace log.  The issue I was debugging in this scenario was a service I was deploying and ASP .NET MVC website it was initializing /stopping / initializing / stopping repeatedly during the deploy to Azure.

  1. When publishing your service select the Enable IntelliTrace for .NET 4 roles checkbox
  2. Enable IntelliTrace

    Enable IntelliTrace

  3. Let the instance deploy and cycle through the initializing and stopping states
  4. Then to download your IntelliTrace log.  In Server Explorer expand your windows Azure hosted service node, right click on your hosting account and select View IntelliTrace log.  This will be downloaded Async.
  5. View Intellitrace

    View Intellitrace

  6. Once the log is retrieved you can review the exceptions
  7. IntelliTrace

    IntelliTrace

  8.  In this case I had not set the System.Web.MVC assembly to copy local and re-deployed.  Job done.

Nick

FREE Event – The Sydney Architecture User Group – Acrhitecting High Performance LOB Applications

: Acrhitecting High Performance LOB Applications
Paul Glavich
Thursday 23/09/2010 06:30 PM
Grace Hotel , Kiralee or Pinaroo Function Room 77 York st Sydney,NSW. 2000

Line of business applications might not be the new twitter or Facebook but often require high degrees of performance. This session will deal with the architectural considerations required to implement such an architecture and provide an open forum where performance issues in todays day to day business applications are discussed.
Paul Glavich is an ASP.NET MVP and a member of the ASPInsiders group with close links to the ASP.NET Team. Paul’s day job is working for Datacom as a solution architect, specialising in the web space but is currently involved in architecting a thick client WPF application. Paul has been working with .Net since its inception, has been in the industry for over 20 years and has written 3 books with the latest one on .NET Performance Testing and Optimization which is available as a free eBook or from Amazon in hardcopy

Monetize your Windows Phone 7 application with Microsft Advertising SDK

This post covers basic test Ads only.

1. Download the SDK – link can be found here http://advertising.microsoft.com/mobile-apps
2. Add a reference to the Microsoft.Advertising.Mobile.UI.dll
3. Add a reference in your XAML
 

xmlns:ad="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI"

4. Use one of the following three variants to display ads

<ad:AdControl AdModel="Contextual" ApplicationId="test_client" AdUnitId="Image300_50" />

<ad:AdControl AdModel="Contextual" ApplicationId="test_client" AdUnitId="Image480_80" />

<ad:AdControl AdModel="Contextual" ApplicationId="test_client" AdUnitId="TextAd" />

5. Job done:

Microsoft Advertising

Microsoft Advertising

Note: currently documentation seems to indicate only available to people with US tax identification number with aps targeted for the US market – more details here: http://advertising.microsoft.com/WWDocs/User/en-us/ForPublishers/Ads-in-Windows-Phone-7-Apps-FAQs.pdf

Those of you interested in a similar service for Australia please email me nicholas dot ian dot harris @ hotmail dot com or reply to this post with your contact details – i will keep the comments private.

Kind Regards,

Nick

How to place a Phone Call on Windows Phone 7 using PhoneCallTask

This describes the straightforward task of how to place a Phone Call on Windows Phone 7 using PhoneCallTask.

  1. Add using statement to the Tasks namespace
  2. using Microsoft.Phone.Tasks;
    
  3. Create an instance of PhoneCallTask set the DisplayName and PhoneNumber properties then call Show:
  4.             PhoneCallTask pct = new PhoneCallTask();
                pct.DisplayName = "Nick Harris";
                pct.PhoneNumber = "+61000000000";
                pct.Show();
    
  5. Result
  6. PhoneCallTask

    PhoneCallTask

  7. Press Call
  8. PhoneCallTask

    PhoneCallTask

  9. After a bit of fiddling it appears you can do conference calls which is pretty neat.
  10. Press the Down Arrow
    Press the dial button from the ApplicationBar
    Enter your number and press Call
    Then press merge call and you got yourself a conference call.

    Conference Call

    Conference Call

    It would be cool if the PhoneCallTask allowed for a collection of Display Name and Phone Numbers to be supplied for programmatic conference call initiation.

Nick

How to SMS using the SmsComposeTask for Windows Phone 7

Unlike Windows Mobile with Windows Phone 7 we are currently unable to directly send an SMS from within an application unless we show the composer screen using SMSComposerTask.  This does suck a little bit as we now Aps cant send SMS’s direct or intercept them at all for that matter.  So what does WP7 offer – well to send an SMS you can use SMSComposerTask and to intercept an SMS – nothing, you will need to re-think your application architecture

To send an SMS using the composer in Windows Phone 7 you need to do the following:   

  1. Add using statement to Tasks namespace
  2. using Microsoft.Phone.Tasks;
    
  3. Create an instance of SMSComposerTask set the To field and body then call Show:
  4. SmsComposeTask sms = new SmsComposeTask();
    sms.To = "0123456789";
    sms.Body = "Some prefilled text...";
    sms.Show();
    
  5. Result
  6. SmsComposerTask Windows Phone 7

    SmsComposerTask Windows Phone 7

If your application really can’t live without direct access to send and intercept an SMS without any user interaction in the composer:   

  1. Then you can wait and they may add it in future releases although I am unsure if this will ever occur and I would not rely on it
  2. Or you may be able to rework your architecture to replace SMS with Push Notifications, a WCF service and Database or XML as your storage. The obvious downside to this is that you loose the telcos serverside infrastructure and have to replace it yourself. This adds a lot more code and cost to the developer for implementation and continual subscription costs for hosting which then means your cool free App idea may become too costly.

If your application can live without SMS interception but needs direct access to send and SMS without any user interaction in the composer:

  1. Then you may be able to use those options listed above
  2. Or, look into SMS providers that provide a web service based API – needless to say if you can’t figure out how to oncharge this to the end user this will also cost you but it may be significantly less then hosting depending on your volume

 Nick   Â
   

Free Windows Phone 7 Deep Dive Workshop(Melbourne, Sydney, Adelaide and Brisbane)

Hi All,

Nick Randolph from Built to Roam is running a Free Windows Phone 7 deep dive over two days, the content looks great, and did i mention it was Free :)

For more details and to register jump on over to his blog Windows Phone 7 Deep Dive Workshop(Melbourne, Sydney, Adelaide and Brisbane)

Nick

ASP .NET Ajax ActionLink with UpdateTargetId callback

  1. The Ajax.ActionLink available withing ASP.NET AJAX can be used to invoke controller actions and update your form asynchronously based on the response. This brief post will describe at how to do this within the context of an Approvals table.
  2. In yoru ASP .NET MVC 2 Web Application add a references to the ASP.NET AJAX library scripts into your Views/Shared/Site.Master at the end of your head element. 
  3. <head>
    ...
    <script src="/Scripts/MicrosoftAjax.js" type="text/javascript"/>
    <script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"/>
    </head>
    
  4. Update your view
  5. Tip: To improve performance these files are available on the Microsoft CDN which means if you use this they should be downloaded faster from the appropriate node based on user location as compaired to from your own web server.

  6. Add your Ajax.ActionLinks.  In  this case we want one to Approve and one to Reject.  On success we want the cell to the left of the ActionLinks to be updated to contain the updated status. 
  7. <%@ Page Title="" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<Dummy.Web.Models.SomeModel>>" %>
    
    <asp:Content ContentPlaceHolderID="TitleContent" runat="server">
     Index
    </asp:Content>
    
    <asp:Content ContentPlaceHolderID="MainContent" runat="server">
     <table>
            <tr>
                <th>
                    Name
                </th>
                <th>
                    Caption
                </th>        Â
                <th>
                   Approved/Rejected
                </th>         Â
            </tr>
    
        <% foreach (var item in Model) { %>  Â
            <tr>
                <td>
                    <%: item.Name %>
                </td>
                <td>
                    <%: item.Caption %>
                </td>        Â
                <td id="status_<%: item.Id.ToString() %>>
                     <%: item.Status %>
                </td>
                <td>
                    <%: Ajax.ActionLink("Approve", "ApproveAction", new { id= item.Id }, new AjaxOptions() { UpdateTargetId = string.Format("status_{0}", item.Id) })%>
                    <%: Ajax.ActionLink("Reject", "RejectAction", new { id= item.Id }, new AjaxOptions() { UpdateTargetId = string.Format("status_{0}", item.Id) })%>
                </td>        Â
            </tr>
      Â
        <% } %>
    </asp:Content>
    

    Note: the Id of the cell that we want to update afterwards is set dynamically as follows <td id=”status_<%: item.Id.ToString() %>> then the ActionLink parameters state Text of Approve, call the Controllers ApproveAction with the parameter id set as a value of item.Id and the result of the ApproveAction is to update the target cell with id string.Format(“status_{0}”, item.Id)

  8. Update your corresponding controller to define the ApproveAction and RejectAction methods:
using System;
using System.Web.Mvc;
using Dummy.Web.Models;
using Dummy.Web.Models.Common;

namespace Dummy.Web.Controllers
{
    [Authorize]
    public class ApprovalsController : AntiForgeryController
    {
        ISomeRepository _someRepository;

        public ApprovalsController():this(new someRepository()){ }

        public ApprovalsController(ISomeRepository someRepository)
        {          Â
            _someRepository = someRepository);
        }
        //
        // GET: /Approvals/
        public ActionResult Index()
        {
            return View(_someRepository.GetItemsForApproval(20));
        }

        [HttpPost]      Â
        public string ApproveAction(Guid id)
        {
           return UpdateAction(id, ApprovalStatusType.Approved);
        }

        [HttpPost]      Â
        public string RejectAction(Guid id)
        {
           return UpdateAction(id, ApprovalStatusType.Rejected);
        }

        protected string UpdateAction(Guid id, ApprovalStatusType status)
        {

           string result = "Error: Unable to Update";
            if (_someRepository.UpdateStatus(id, ApprovalStatusType.Approved))
            {
                result = ApprovalStatusType.Approved.ToString();
            }

            return result;
        }
    }
}

Thats about all that is required to add an Ajax.ActionLink that can be used to invoke controller actions and update your form asynchronously based on the controllers response.

Nick