Thursday, December 9, 2010

Windows Phone Unplugged - How to Detect the Zune Software

I've been blogging about Windows Phone development since the first CTP version and also blogged about the photo and camera API.
This post will cover a little trick my Pictures Lab app uses to detect if the Zune software is running when the device is connected to the PC. This is important because the device's media Hubs can't be accessed when the device is connected and the Zune software is running. The same is true for the media APIs (PhotoChooser, MediaLibrary, ...).
The Pictures Hub and the Zune Hub show a little animation when you try to open these while Zune is running. Unfortunately there's no built-in method to detect this in code.

An app mostly performs the classic IPO Model operations: load, process, save. The load and save steps can fail when Zune is connected. The following two code snippets show how to detect if the Zune software is running and ask the user to close it. I use the PhotoChooser and MediaLibrary here to demonstrate this exemplarily for picture handling, but the same is also valid for other media like audio.

Save fail
If the device is connected to the PC and the Zune software is running, an InvaildOperationException is thrown.
By the way, this blog post covered how to save a WriteableBitmap as JPEG to the device's media library.

private static void Save(WriteableBitmap bitmap)
{
   try
   {
      SaveToMediaLibrary(bitmap, "mySuperCoolPic.jpg");
   }
   catch (InvalidOperationException)
   {
      MessageBox.Show("The Zune software is running and the picture can't be saved. Please close Zune or disconnect the phone.");
   }
}
This is quite straightforward.


Load fail
Unfortunately it's not that easy to detect if the Zune software is running when a picture is opened through the PhotoChooserTask API. (How to use this Task was also covered here.)

Some users contacted me when they tried to open a photo with Pictures Lab and nothing happened. The problem is that the picture viewer just won't open when the PhotoChooserTask.Show method is called and Zune is running on the PC. There's no built-in feedback here. I implemented the following code in the Completed event handler of the PhotoChooserTask to get a better user experience.

private void PhotoProviderTaskCompleted(object sender, PhotoResult e)
{
   try
   {
      if (e != null)
      {
         if (e.TaskResult == TaskResult.OK)
         {
            // Do something with the JPEG stream in e.ChosenPhoto
         }
         else if (e.Error is InvalidOperationException)
         {
            throw e.Error;
         }
         else if (e.TaskResult == TaskResult.Cancel)
         {
            // Try to get an image from the Pictures Hub. 
            // If this fails, the device is connected and Zune is running.
            var pictures = new MediaLibrary().Pictures;
            if(pictures.Count > 0)
            {
               pictures[0].GetThumbnail();
            }
         }
      }
   }
   catch (InvalidOperationException)
   {
      MessageBox.Show("The Zune software is running and the picture can't be saved. Please close Zune or disconnect the phone.");
   }
}
One might wonder why the MediaLibrary is queried when the PhotoResult EventArgs has the Error property. Unfortunately it's not used when Zune is running, only the TaskResult is set to Cancel in this case. This TaskResult value is also used when the user presses the back button while choosing a photo and it's not clear why the TaskResult was set to Cancel.

Fin
That's it.
I hope it helps.
Let me know if you found a better way.

The above photo was taken with a HTC Mozart and edited with Pictures Lab (cropped and Lomo effect).

Tuesday, November 2, 2010

Tracking Sales Statistics with the Silverlight Analytics Framework for Windows Phone

The official statistics are now available at the App Hub portal. However, this approach is capable of more than sales tracking.

Are you a Windows Phone developer? Are you also curious how well your app performs in the Windows Phone Marketplace? I am!
Some might say it doesn't matter yet, since there aren't many devices out there, but nevertheless I'd like to know my statistics. Also O2 Germany recently reported they have sold out the first batch of HTC HD7 devices with sales in the 5-figure range. Unfortunately we won't see official statistics from the Marketplace any time soon. An App Hub forum member contacted the Microsoft App Hub support and they told him that sales statistics won't be available before January 2011. Bummer!
Fortunately we are app developers and we can implement our own statistic tracking. On the other hand this means we have to setup and pay some service and implement tracking code. Here is where the Silverlight Analytics Framework and Google Analytics come to the rescue.
This blog post provides a step-by-step guide on how to track your app (sales) statistics with the Silverlight Analystics Framework and Google Analystics. Did I mention it's free and not only free for a limited period?
Let's go...

Setup Google Analytics
If you don't have a Google Analytics account, just sign up here. It's free.
  1. Create an empty HTML page with the minimum tags and upload it to some public webspace. If you don't have webspace available, just create a free Dropbox account and put the page in the public folder.

  2. Go to Google Analytics and use the "Add Website Profile" functionality. Choose "Add a Profile for a new domain". Enter the URL of the dummy website.

  3. The next page setup page will show the necessary Java Script tracking code. Copy the code, paste it into the dummy website and upload the website.

  4. Your website profile is now waiting for activation. Go back to the overview and click the Edit link of your website profile. See the little yellow exclamation mark with the text "Tracking Not Installed" at the upper right corner. Click on "Check Status". The status should change soon and the profile will become active. If not, give Google a couple of minutes and retry it then.


Setup the Silverlight Analytics Framework
Now it's time to submit the tracking events from your app to Google Analytics. This task is pretty easy with the help of the Silverlight Analytics Framework.
The Silverlight Analytics Framework is an extensible web analytics framework mainly developed by the Microsoft evangelist Michael S. Scherotter. It's really nice, designed in a flexible way with the use of modern technologies and open source. Google Analytics is just one of the many supported analytics services.
  1. Download the latest version from the Codeplex site and install it or download the latest source code from the repository and build it yourself. I've chosen the latter since Michael recently implemented a nice feature: The Silverlight Analytics Framework for Windows Phone tracks each page view by default. In the changeset 63020 Michael added an IsPageTracking property which allows to disable the page tracking. This feature is part of the latest release 1.4.8.

  2. Add the following assembly references to your project.
    From the Silverlight for Windows Phone Framework: System.Device, System.Windows.Interactivity
    From the Silverlight Analytics Framework: Microsoft.WebAnalytics, Microsoft.WebAnalytics.Behaviors, Google.WebAnalytics, System.ComponentModel.Composition, System.ComponentModel.Composition.Initialization

  3. Create a new class in your project:
    public class AnalyticsService : IApplicationService
    {
       public void StartService(ApplicationServiceContext context)
       {
          // Wire up MEF
          CompositionHost.Initialize(
             new AssemblyCatalog(
                Application.Current.GetType().Assembly),
                new AssemblyCatalog(typeof(Microsoft.WebAnalytics.AnalyticsEvent).Assembly),
                new AssemblyCatalog(typeof(Microsoft.WebAnalytics.Behaviors.TrackAction).Assembly));
       }
    
       public void StopService() { }
    }
    

  4. Go to the App.xaml file of your project and add the namespace definitions to the first tag:
    <Application
        x:Class="MyApp.App"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    
        xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    
        
        xmlns:local="clr-namespace:MyApp"
        xmlns:ga="clr-namespace:Google.WebAnalytics;assembly=Google.WebAnalytics"
        xmlns:mpc="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
        xmlns:mwa="clr-namespace:Microsoft.WebAnalytics;assembly=Microsoft.WebAnalytics"
        >
    
  5. Then add the service references inside the Application.ApplicationLifetimeObjects declaration in your App.xaml file:
    <Application.ApplicationLifetimeObjects>    
        <local:AnalyticsService />
        <mwa:WebAnalyticsService IsPageTrackingEnabled="False">
            <mwa:WebAnalyticsService.Services>
                <ga:GoogleAnalytics WebPropertyId="UA-XXXXXXX-X" />
            </mwa:WebAnalyticsService.Services>
        </mwa:WebAnalyticsService>
    </Application.ApplicationLifetimeObjects>
    
    Most important you need to replace the WebPropertyId in the GoogleAnalytics element with the Id of your newly created Google Analytics website profile.
    I'm not interested in the page tracking, therefore I've set the IsPageTrackingEnabled property to False. You should also keep in mind that page tracking has an impact on the performance of the app. I recommend to disable it.
     
  6. Since your app is now using a network connection, you need to add the ID_CAP_NETWORKING capability to your WMAppManifest.xml file. 
That was all to get the Silverlight Analytics Framework connected to your Google Analytics profile. It now tracks the Deactivated, Activated and Started events.
You can find the results here:

Please keep in mind that it usually takes 12 - 24 hours until the tracked data shows up in Google Analytics.


Add sales tracking
There's only one puzzle piece left now, the actual sales tracking. I use two Windows Phone APIs for this. First the LicenseInformation.IsTrial method which tells us if the app runs in trial mode or if it was paid. The second API is the DeviceExtendedProperties class with the DeviceUniqueId key which provides a unique 20 byte long hash for the phone. Such an id is needed to count unique installations.
  1. Add a new class to your project for the explicit tracking from code:
    public class AnalyticsHelper
    {
       // Injected by MEF   
       [Import("Log")]
       public Action<AnalyticsEvent> Log { get; set; }
    
       public AnalyticsHelper()
       {
          // Inject
          CompositionInitializer.SatisfyImports(this);
       }
    
       public void Track(string category, string name)
       {
          // Track analytics event
          Log(new AnalyticsEvent { Category = category, Name = name, });
       }
    }
    

  2. Call the Track method when your app launches and provide the necessary information.
    Add this code to the Application_Launching event handler in the App.xaml.cs file.
    private void Application_Launching(object sender, LaunchingEventArgs e)
    {
       var analyticsHelper = new AnalyticsHelper();
    
       // Get device id
       var value = (byte[])DeviceExtendedProperties.GetValue("DeviceUniqueId");
       var id = Convert.ToBase64String(value);
       
       // Track launch
       analyticsHelper.Track("Launch All", id);
    
       // Track if paid
       if (!new LicenseInformation().IsTrial())
       {
          analyticsHelper.Track("Launch Paid", id);
       }
    }
    
    Gergely Orosz (@Gergely Orosz) gave me the idea to track the statistics only if the phone is connected to Wi-Fi. This is pretty easy to implement, just add an if condition around the tracking: NetworkInterface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211

  3. The app is now using the unique id of the phone, so you have to add the ID_CAP_IDENTITY_DEVICE capability to your WMAppManifest.xml file. 

As you can see all app launches are tracked in the category "Launch All" and all paid launches in the "Launch Paid" category. This makes it easy to see all installations and all sales directly. Needless to mention that Launch Trial = Launch All - Launch Paid.
You can check if all works with the Fiddler or the TCPView tool while using the Windows Phone emulator. By the way, the tracking is pretty fast. I measured 20 to 40 ms for each Track call when the phone was connected to Wi-Fi.

The tracked events are best viewed when grouped by categories. The screenshot below shows a test with multiple launches of a phone and the emulator. The total number of events is listed at the bottom right of the table. Note that Unique Events aren't significant here since they only represent unique events for one session.

The id (event name) we supply through the AnalyticsEvent is mapped to the Google Analytics Event Action. You can find all event mappings and more info in the relevant Silverlight Analytics Framework documentation.

Conclusion
The update I submitted to the Marketplace works nicely and I hope to see some meaningful statistics in the next weeks. I think the described method is a good way to track your sales and other statistics until the App Hub team provides the official usage / sales statistics. Actually the provided tracking functionality is even useful when the App Hub team provides official statistics. And it's all free without a limited timeframe.

Monday, November 1, 2010

Silverlight is not dead and not undead either

No, it's alive and kicking.
You might have heard about the rumors that came up after the PDC conference and Bob Muglia's interview with Mary Jo Foley. Many people flooded Twitter and other sites with speculations that Silverlight is dead for the web. Microsoft's President of the Server and Tools Division Bob Muglia just clarified the situation.

"Make no mistake; we’ll continue to invest in Silverlight and enable developers to build great apps and experiences with it in the future."

You should also read the blog post from the Silverlight program manager Tim Heuer. Without a doubt he puts all his effort into the success of Silverlight. And not to forget the Microsoft Silverlight evangelist John Papa who also proves his commitment to Silverlight here.

Now let's get back to work...

The picture is an old poster from the movie Santo en el Museo de Cera with the famous Mexican lucha libre wrestler El Santo.

Monday, October 18, 2010

Pictures Lab for Windows Phone

"Windows Phones are going to be absolutely amazing devices for taking pictures and dealing with pictures." - Joe Belfiore at the official Windows Phone 7 launch event in NYC. I totally agree, they are. Just think about that each device needs to have at least a 5 megapixel camera and the little camera button with the "pocket to picture" functionality. I've been working heavily to enhance this photo experience with my kind of skills. This blog post contains information about the Windows Phone app I created and will also provide the references to how it works internally.


Download here

Pictures Lab is the ultimate picture effects app for all Windows Phone device types.
MSNBC.com: "a Swiss Army knife of photo tweaks".
Engadget.com: "a must-have for WP7 devices ... the program provides a set of amazing effects and tweaks for your photos"
Gizmodo.com : "Pictures Lab offers a ton of effects for your money."

If you like to make beautiful photos, then this app is a perfect addition to your phone’s toolset. Pictures Lab provides you with thousands of different modifications for your photos and has a camera functionality with superior features like face detection auto focus, steady mode and much more. It's also integrated as a Lens.
Pictures Lab is the original with high quality filters, features and great user experience. It's fast and responsive and you quickly get your job done with just a few moves. Often been copied, but never reached.
Microsoft uses Pictures Lab in its presentations as a "delightful app" which "Looks and feels like an integral part of Windows Phone". "Uncluttered, polished experience".

The app comes with controllable, easy-to-use, but advanced effects like different vintage and hipster-like filters, Tilt Shift (miniature faking), HDR, Lomo, Soften, Auto Adjust, Sharpen, Comic, Bulge, B&W, Sepia and many more. Dynamic previews of the effects are shown in a list, making it possible to easily pick the right one. The high quality borders are also presented in a nice preview list and can be combined with any filter and any aspect ratio. Multiple effects can also be combined.
It is also possible to crop, rotate and flip images. An enhanced picture and the EXIF data can be saved to the phone’s pictures hub or shared directly on Facebook, Twitter and other social networks. Later editing is also supported. The app performs the image processing on the original picture in its original resolution, thus making it also possible to print the image or use it as desktop wallpaper.
Full Pictures Hub Apps integration and support for landscape and portrait orientation. Trial version with complete functionality only save is disabled.

    If YouTube works better for you.

Reviews
  • The well-known site Engadget lists it under The best apps, accessories, and tips. They write: "... a must-have for WP7 devices ... the program provides a set of amazing effects and tweaks for your photos ..."
  • Gizmodo included Pictures Lab in Windows Phone 7 Essential Apps, Reviewed. They also recorded a video. They write: "Your phone isn't complete until you can take photos that look like they came out of a $5 camera from 1974. Pictures Lab fortunately offers a ton of other effects for your money. $2."
  • Gizmodo Australia also featured it in the article The Best Windows Phone 7 Apps.
  • msnbc.com wrote: "The app, a Swiss Army knife of photo tweaks, will be one of my first downloads."
  • techradar.com wrote that Pictures Lab is the #1 app worth paying for: "Tilt-shift effects, crop and rotate... Pictures Lab combines the fun effects of an iPhone photo app like Hipstamatic with the useful fixes you're mostly likely to need (sharpen and - in the imminent update - crop) in a beautifully designed app that crosses the power of Silverlight with the tools of the Windows Phone 7 interface. Pick a photo, see all the possible effects as thumbnails or swipe up and down to try them one at a time."
  • msnbc.com listed it in the article: "The first Windows Phone 7 apps you should grab"
  • MSN UK listed it under the "20 top mobile phone app". And they put my fat nose on the front page. Fortunately two of my girls brought the beauty back to the page.
  • America's popular WIRED magazine with a circulation of 800,000 featured Pictures Lab in there special edition WIRED App Guide.
  • UK's popular gadget magazine T3 with a circulation of more than 60,000 featured Pictures Lab in the 02/2011 issue on the page: "Killer Apps"
  • Pictures Lab was featured in Channel 9's Hot Apps series.
  • Nokia writes "it’s the closest thing to having Photoshop on your mobile phone."
  • Nokia included Pictures Lab in Top of the Apps: 10 Hotties.
  • Softpedia featured the Windows Phone 8 update.
  • All About Windows Phone reviewed the app: "Pictures Lab is one of many photo toolboxes for your smartphone, but it's the one that I enjoy using the most." and "Very, very much recommended."
  • All About Windows Phone also reviewed the Windows Phone 8 update: "It goes significantly beyond the one shot filters typically offered in apps of this type (Nokia Creative Suite, HTC Photo Enhancer) to the point at which it's about a lot more than just fun filters."
  • Another very popular UK magazine Stuff wrote a 5 stars review in the March edition. They write that Pictures Lab is better than a well-known iPhone app.  
  • Germany's popular media and design magazine PAGE with a circulation of 20,000 featured Pictures Lab in the 01/2011 issue
  • Microsoft features Pictures Lab in their presentation slides for Windows Phone under the category delight: "Looks and feels like an integral part of Windows Phone 7". "Uncluttered, polished experience".
  • Geek.com listed it as one of the Five must have apps for Windows Phone: "Pictures Lab is $2.99, but well worth it in my opinion for all of the new features added to the camera on your phone."
  • The famous blogger Scott Hanselman says in his Essential Apps blog post: "Pictures Lab is a nice effects and editing application (if not THE BEST editing app) for Windows Phone. All the functionality is there and cleanly integrated with the Photos Hub. Crop, Rotate, Effects, etc. It's a must-have if you are doing any photography on your phone."
  • Business Insider writes "Pictures Lab is like Instagram for Windows Phone 7. Take pictures with Pictures Lab, apply filters, and share them with friends."
  • The famous design site Smashing Magazine included Pictures Lab as an example in the article Introduction To Designing For Windows Phone 7 And Metro
  • Bright Hub lists Pictures Lab as the first app in Top 5 Samsung Focus Apps: "It is considered one of the most popular photo editing programs on the Windows Phone platform, and for good reason. It has an array of sophisticated and beautiful effects ..."
  • APC (Australian Personal Computer) writes: "WP7’s best picture editing and effects app.Pictures Lab has received a lot of attention as the “go-to” image editing suite for new WP7 users – and for good reason, too."
  • Mobility Digest wrote: "This app makes me happy. Tons of features, seems simple to use and it’s cheap – that’s a win! It even has a trial mode that includes all effects."
  • Mobility Digest also posted a walk through: "I didn’t realize it, but when you go to the list of available effects you get to see a preview of the effect which is really great and I have to say, I’m really impressed for how much this app can do."
  • Mobility Digest listed it in: "The First 25 Windows Phone Apps To Download"
  • Pocket-Lint wrote in the article Best Windows Phone 7 photography apps: "... the smart way to go is with Pictures Lab..."
  • maximumpc.com wrote: "Speaking of pictures, for two bucks you can have a great little mobile suite of photo effects, fixes, and basic editing tools. The Windows Phone 7 UI language really shines through in this one."
  • Mobile Choices listed it as one of the two Windows Phone apps in The 12 best Christmas apps: "...turning lifeless images into photographic masterpieces..."
  • The blog Noisecast recorded a nice video review: "The program @PicturesLab is the best photo editor for Windows Phone 7, hands down."
  • 1800pocketpc.com wrote: "If you love to add effects to your picture then this is one app video you wouldn’t want to miss."
  • 1800pocketpc.com also wrote a review including a video
  • wpcentral.com wrote: "... interesting photo effect application."
  • wpcentral.com also got the WP8 update and : "... Things fly along nicely and the effects don’t take too long to apply in full ..."
  • mobiledownloadblog.com wrote: "There is no doubt that any phone device is incomplete without good picture depiction. A fantastic photograph app known as Picture Lab is now available for Windows Phone 7."
  • Techland.com has it on the list: "50 Windows Phone 7 Apps to Get You Started"
  • mobiledownloadblog.com has it on the list: "Samsung Focus: 30 Best WP7 Applications"
  • The German site phoneseven.de wrote: "Die App sieht wirklich klasse aus und lässt sich allem Anschein nach wirklich gut bedienen. Wer also befürchtet hat, dass Windows® Phone 7 zu wenig Möglichkeiten für gute Apps bietet, der wird mit Pictures Lab sicherlich eines besseren belehrt. Die App wird sicherlich zu meinen ersten Käufen aus dem Marketplace gehören."
  • The Portuguese site pcdebolso.com also wrote an article: "Pictures Lab a caminho do Windows phone 7"
  • Dave Campbell wrote a nice review: "All-in-all, I give Pictures Lab 5 stars"
  • John Papa wrote: "Overall, very nice app, good UI, snappy (which was a surprise to me since it does a lot)."
Feature list
  • Full support for Windows Phone 7 and 8 including all screen resolutions.
  • 30 advanced effects: Ten different vintage and hipster-like effects, Tilt Shift (miniature faking), HDR, Lomo, Soften, Auto Adjust, Sharpen, Comic, Bulge, B& W, Sepia, Manual, Edge Detection, Night Vision, Rainbow, Mirror, X-Ray, Heat Image, Colorization, Negative and Bitmap.
  • Editable effect parameters with ready-to-use default values.
  • Combination of multiple effects.
  • 11 high quality borders and more seasonal borders.
  • Share on Facebook, Twitter, Email, NFC and much more.
  • Take photo functionality with face detection auto focus, steady mode, rule of thirds grid. Integrated into the phone as a Lens. The steady mode requires a device with a gyroscope. The face focus is enabled if the device supports focus at point. It also supports devices with a front facing camera.
  • Post edits from the Pictures Hub using the WP Rich Media extension.
  • Crop, rotate and flip also with predefined aspect ratios.
  • Multi-touch manipulation for Tilt Shift and other effects where multi-touch is meaningful.
  • The app can save edited pictures with advanced effects applied in full resolution even on a device with 256 MB RAM. Thus making it also possible to print the image or use it as desktop wallpaper.
  • Full Pictures Hub Extras integration.
  • The trial version includes the complete functionality and all the effects, only the save functionality is disabled.
  • Support for landscape and portrait orientation.
  • Effect list with dynamic previews and caching of the larger previews.
  • Flicking through the effects on the main page.
  • Setting for the maximum output size, JPEG quality and many more.
  • State preservation when the app is deactivated (tombstoning).
  • Localization for English, German, Japanese, Chinese, Russian, Dutch, French, Italian, Spanish, Portuguese and Portuguese (Brasil).








How it works
Some of the image processing algorithms that are used in the Pictures Lab app would normally be implemented as pixel shaders for Silverlight. The Windows Phone platform doesn't support custom pixel shaders at the moment, therefore all effects are implemented in C# and manipulate the WriteabeBitmap Pixels' in some way. How this works in detail was shown in my Coding4Fun articles I've written months ago. This is actually where Pictures Lab has its roots. The first article described all the necessary basics and two simple effects. The second part of this short Coding4Fun article series shows how to implement the basic tilt shift and vintage effects you can find in the Pictures Lab app. Yes, some parts are open source! Except the secret sauces I gotta keep for me that adds the final touch to the effects. I also wrote blog posts about some parts of the application that are surely interesting for other Windows Phone developers.
The Slider control that is used in the App was originally developed by Nokola and then adapted for Windows Phone and made bindable by Clint Rutkas and myself.

To be continued
The planned feature list for the next versions is already pretty long and I have some real diamonds on there. You can follow @PicturesLab on Twitter to get all the status updates. I'd also like to know what feature you want to see in a future version. Just write a comment.

Monday, September 20, 2010

Windows Phone Memory Constraints

The final Windows Phone Developer Tools have been released and the launch date is not far away. It's time to finalize the apps.
Windows Phone has some tough hardware requirements, but it's still a mobile platform with limited resources. In this blog post I'll describe how to determine the current memory usage, what the allowed maximum is to get your app approved for the Marketplace and other constraints a developer should be aware of.


Maximum memory usage
The Windows Phone hardware specifications requires that a device has 256 MB RAM or more. The allowed maximum memory an app can use is defined in the Windows Phone 7 Application Certification Requirements at point 5.2.5
The application must not exceed 90 MB of RAM usage. However, on devices that have more than 256 MB of memory, an application can exceed 90 MB of RAM usage.
One might now ask how to get this information at runtime. Fortunately there's the DeviceExtendedProperties class to obtain some device information at runtime. This class defines the GetValue and TryGetValue methods which expect a string key as parameter. The list of available property keys is defined here. Among other interesting properties like the DeviceUniqueId, it's possible to retrieve the DeviceTotalMemory, the ApplicationCurrentMemoryUsage and the ApplicationPeakMemoryUsage. The property keys are interpreted case-sensitive.
The application needs to define the device identity capability in the WMAppManifest.xml file in order to retrieve the DeviceUniqueId property, but it's not needed for the other keys like the ApplicationPeakMemoryUsage.

Here's the code to get the peak memory usage and the available total memory at runtime:

var timer = new DispatcherTimer {Interval = TimeSpan.FromSeconds(2)};
timer.Tick += (s, e) =>
{
   var memuse = (long)DeviceExtendedProperties.GetValue("ApplicationPeakMemoryUsage");
   var maxmem = (long)DeviceExtendedProperties.GetValue("DeviceTotalMemory");
   memuse /= 1024 * 1024;
   maxmem /= 1024 * 1024;
   MyTextBlock.Text = String.Format("Mem usage: {0} / {1} MB", memuse, maxmem);
};
timer.Start();

The timer checks the properties every two seconds and converts the bytes to MB. The values are then shown in a TextBlock. The peak memory is the most interesting since this value must not exceed 90 MB on a device with 256 MB. Also note that an empty application with two grids and a TextBlock already has a peak of 5 - 7 MB in the emulator or on a device.


PhoneApplicationPage.State limitation
The PhoneApplicationPage.State property is typically used to save transient state for tombstoning. The size of the State data is limited to 2 MB for a Page and 4 MB for the whole application. Be warned, if this limit is reached a not very descriptive exception is thrown. The message text is "The client who called IAccessControl::IsAccessPermitted was the trustee provided tot he method".
If more than 2 / 4 MB is needed to save transient data, the IsolatedStorage can be used. The applications IsolatedStorage is only limited by the device's flash storage size. The minimum requirement for Windows Phone is 8 GB. The available free isolated storage in bytes can be retrieved with the AvailableFreeSpace property of the IsolatedStorageFile class.