Certification Requirements update: Location Services Access #wpdev

Every since I can remember (at least 2 years now), the windows phone store’s certification requirements required:

  1. A store link to privacy policy
  2. Option to disable app’s use of location services.

If you didn’t do either of those two, the certification would fail (after about 7 days) and you would start again. However a fortnight back my Cineworld app failed a tiny update why ??? cause the update to certification requirements dictate that you also provide in app privacy policy (or a link) – not just on store.

Here are the new set of requirements:

App Policies: 2.7.2 Location Services Access

The privacy policy of your app must inform users about how location data from the Location Service API is used and disclose and the controls that users have over the use and sharing of location data. This can be hosted within or directly linked from the app. The privacy policy must be accessible from your app at any time.

Notification/Action Requested:

The app uses location services, however one or more of the following is missing:

  • A persistent privacy policy in-app
  • A privacy policy URL that is accessible through the Windows Phone Store
  • A privacy policy that is unique to the app

If you encounter certification failure, add a hyperlink button and point it to online privacy policy at the very least. Oh and in case you are wondering,  this used to be a Window 8 Store requirement – one store coming to devices near you ???

Advertisement

Photo / Camera API – 1 #wpdev

My memory of Windows Phone NoDo API set is pretty bleak. I distinctly remember presence of CameraCaptureTask and PhotoChooserTask. I think I used PhotoChooserTask with my first app Scribble. So what’s this post about ? well Photo / Camera options available on Windows Phone 8.

Since I started with the two tasks, they still exist in Windows Phone 8.

CameraCaptureTask: this fires the stock camera app – ability to navigate to camera roll and use other lens is blocked but otherwise it is the stock windows phone app. Tap to focus / capture or use dedicated shutter button. On capture you are presented with a preview and you have the option to accept or retake the capture.

wp_ss_20140130_0005 wp_ss_20140130_0006 wp_ss_20140130_0007

PhotoChooserTask: this is a different beast. This opens photos hub and presents user with list of albums allowing user to select a photo. The Task has a parameter that toggles visibility of camera icon – ability to not just select a picture but also initiate CameraCaptureTask from within.

While both of these are very basic, let me point out that Instagram BETA still uses a layout very similar to Photochooser task and obviously uses Camera Capture Task.

Its very likely that Instagram could get away with murder. Most of us – 3rd party developers however do not have such luxury. We would be termed as lazy if not worse. And you might not want the stock camera UI. So what can you do ? I am still in old API mode so let me mention an API that was part of Mango – I don’t know if NoDo had it or not – I only used it after Mango public release in my Cool Camera app.

PhotoCamera Class: this class provides raw access to camera and exposes a few options like resolution, flash and focus. Apps render live view by means of using a video brush whose source is set to an instance of photo camera class. How to create a base camera app for Windows Phone provides a great sample to kick start camera app development using this class

PhotoCamera

For a camera app, call CaptureImage. Others might not need a full blown capture – something like QR scanning app would just use focus and can do with GetPreviewBufferArgb32.

Whilst this is a good start, the API is not extensive enough for anything beyond basic. In the next post, I will discuss PhotoCaptureDevice class. This class though simple, exposes enough API to create a full blown camera app allowing you to control every single aspect of camera. If you hardware supports it, you should be able to utilise it

ColorWheel I often use in #wpdev

Ever since I started WPDev in April 2011, I have found myself in need of a color wheel. While working on my first ever app Scribble, I needed one and after plenty of looking I settled on HSV Photoshop style Color Wheel. It looks something like this

At time I even unsuccessfully tried to port it to Win8Dev without access to source that can be a bit tricky 🙂 Having posted the blog and the old dll, I did a quick search and found out that it is now hosted on codeplex
http://colorpickr.codeplex.com/

In the mean time, I have finally created a custom colour picker control for Win8Dev. I will share it in coming days.

It looks like this when added to Top AppBar

Happy coding

Super Duper All in one VisibilityConverter for #wpdev

On the 4th of July I blogged about simple visibility converters to toggle visibility. Of course I used two converters then.. one Visibility and another inverse aka Invisibility.

I also said that some clever people might tell me that its possible to do both in a single converter. Whilst that is true, no one did so apparently no one really reads or cares 😐 Coding4Fun toolkit has a converter than exposes Inverted property but my idea was to be able to use the same converter by pass a parameter.

So here’s what I did

 

public class VisibilityConverter : IValueConverter
{
    public enum Mode
    {
        Default,
        Inverted,
    }

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        Visibility returnVisibility = Visibility.Visible;
        Mode mode = Mode.Default;
        try
        {
            if(parameter != null)
                mode = (Mode)Enum.Parse(typeof(Mode), (string)parameter, true);
        }
        catch 
        {
            mode = Mode.Default;
        }

        if (value == null)
        {
            returnVisibility = Visibility.Collapsed;
        }
        else if(value is bool)
        {
            bool bVal = (bool)value;
            if (!bVal)
                returnVisibility = Visibility.Collapsed;
        }
        else if (value is string)
        {
            string itemVal = value as String;

            if (String.IsNullOrWhiteSpace(itemVal))
                returnVisibility = Visibility.Collapsed;
        }
        else if (value is IList)
        {
            IList objectList = value as IList;
            if (objectList == null || objectList.Count == 0)
                returnVisibility = Visibility.Collapsed;    
        }

        if (mode == Mode.Inverted)
            return returnVisibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
        else
            return returnVisibility;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

and how do I use it ? well this is how

<TextBlock Text="{Binding Review}" Visibility="{Binding Review, Converter={StaticResource VisibilityConverter}}" TextWrapping="Wrap" Style="{StaticResource PhoneTextNormalStyle}" Grid.Column="0" Grid.Row="1" Grid.ColumnSpan="2"/>
<TextBlock Text="(rating only)" Visibility="{Binding Review, Converter={StaticResource VisibilityConverter}, ConverterParameter=Inverted}" Foreground="{StaticResource PhoneSubtleBrush}" TextWrapping="Wrap" Style="{StaticResource PhoneTextNormalStyle}" Grid.Column="0" Grid.Row="1" Grid.ColumnSpan="2"/>

I could pass Default parameter or just leave it out and it defaults to normal behaviour. If I however pass Inverted parameter to the converter, it inverts the behaviour. Bingo.

Now waiting for the next clever people to tell me that I am using parameter designed for something else 🙂

Changes to Windows Azure Mobile Service and what they mean

Just over a month and half back, Windows Azure team released the Mobile Services. In addition to announcing paid services, they severely restricted the Free tier to the extent that it was not usable. The initial statement I got from them was that Free tier was meant for Testing. So what happened next ? I got it all up in my head and started a user voice. I talked to as many Windows Phone and Windows 8 developers as I could to tell them about it and to ask for their votes.

While I was vote gathering, I was also talking to Azure team and we discussed some stats on what is acceptable for free tier. We discussed the fact that 100 devices a month wasn’t really well thought-out idea and that it needed change. They agreed to increase the number and took on my suggestion of a daily device count as opposed to monthly device count.

The reasoning behind this is simple. If a user downloads your app, plays with it for 5 minutes but never ever uses your app, the user would have impacted the limited device count for whole month. With a daily limit, the new installs only impact for 24 hours not 30 days.

Last night Dinesh Kulkarni a Program Manager at WAMS acknowledged the user voice, closed it and updated the WAMS pricing document to reflect the changes that were in plan for good part of last month.

So what do we get now ?
Instead of 100 unique devices a month, we get 500 unique devices per day.

It is also worth noting Free tier isn’t covered by SLA and that its not monitored. Azure team will fix any issues on the Free tier (when identified) however Free tier services aren’t actively monitored – unlike the Standard and Premium tier that feature active monitoring to meet the SLA.

Additionally the 500 devices a day for Free tier are applicable across all your mobile services – not one. If you have 1 WAMS, you get 500 devices a day, if you have 10, you still only get 500 a day between all 10 services.

And finally what happens when your service registers 500 devices and additional devices keep coming ?
Well the service will stop servicing requests (not sure whether its for additional devices or across all) and will become available after 24hour device count reset.
The service would otherwise be untouched.

I think this is a satisfactory conditions imposed on Free tier. WAMS team would like to be cost neutral and for popular high device count / high volume app, they would like you to use paid SLA driven tiers.

I’d like to thank the Windows Azure Mobile Services team Josh Twist, Kirill Gavrylyuk and Dinesh Kulkarni for being open to the suggestion and of course all the Windows Phone and Windows 8 developers who took time to vote on the user voice. Without the developers, my whinging would have gone unheard. Thank you

LongListSelector and scroll to top #wpdev

I pulled out my Marauder’s Map, tapped my wand and said “I solemnly swear I’m up to no good”. Bang Visual Studio opens up and I am back to playing with Cineworld app. I know a few users hate my ever so frequent updates but I use the app and I need change 🙂

so I recently got to putting a DatePicker and LongListSelector for being able to “Show by date” film listings. It all worked – well mostly worked until I realised that LongListSelector was scrolled all the way to the bottom. I wonder why..

Of course there is no SelectedIndex I could magically set so did a quick search on the net.. StackOverflow usually has all the answers to “the life, the universe and everything else” but it didn’t really have one for this question.

There was a note saying use UpdateLayout and then ScrollTo and setting it to ItemSource’s first child did the trick for WP8 but not for WP7.

var dataLetter = cd.GetGroupForDate(userSelection); // get the grouped list of films

FilmsForSelectedDate.Clear(); // clear the bound observable collection

foreach (var entry in dataLetter)
    FilmsForSelectedDate.Add(entry);

lstShowByDate.UpdateLayout(); // call updatelayout

if (FilmsForSelectedDate.Count != 0)
    lstShowByDate.ScrollTo(FilmsForSelectedDate[0]); // set scroll to first group in the list

The problem I realised was that the first group in the LLS had zero items i.e. it was not being shown. This affected WP7 toolkit LongListSelector but not the native WP8 LongListSelector

var dataLetter = cd.GetGroupForDate(userSelection);

FilmsForSelectedDate.Clear();

foreach (var entry in dataLetter)
    FilmsForSelectedDate.Add(entry);

lstShowByDate.UpdateLayout();

if (FilmsForSelectedDate.Count != 0)
    lstShowByDate.ScrollTo(FilmsForSelectedDate.First(g => g.HasItems));

So the solution as shown above is, find the group that has items and set scroll to that element.

Mischief managed!

Converter to toggle visibility when content is empty #wpdev #wp8dev #wp7dev #win8dev

Recently Gustavo Guerra posted a question on StackOverflow.com stating that behaviour of TextBlock was different on Windows Phone 7 and Windows Phone 8. If the Text is empty, WP7 renders TextBlock with Height set to 0. On WP8, it occupies full height.

I replied back stating that he should consider using a Converter for the same. Of course I had a similar issue with Cineworld app. The screenshot shows ratings & review screen I implemented – its almost a copy of Windows Phone Store ratings & review.
wp_ss_20130704_0002[1]

what I noticed was that if user chose to not review it, the textbox would be fully render. So I did what I suggested Gustavo do. Created two converters – StringLengthInvisibilityConverter and StringLengthVisibilityConverter. Almost identical but doing the opposite thing.

 

public class StringLengthInvisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string itemVal = value as String;
        if (String.IsNullOrWhiteSpace(itemVal))
            return Visibility.Collapsed;
        else
            return Visibility.Visible;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

public class StringLengthVisibilityConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string itemVal = value as String;
        if (String.IsNullOrWhiteSpace(itemVal))
            return Visibility.Visible;
        else
            return Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
<TextBlock Text="{Binding Review}" Visibility="{Binding Review, Converter={StaticResource InvisibilityConverter}}" TextWrapping="Wrap" Style="{StaticResource PhoneTextNormalStyle}" Grid.Column="0" Grid.Row="1" Grid.ColumnSpan="2"/>
<TextBlock Text="(rating only)" Visibility="{Binding Review, Converter={StaticResource VisibilityConverter}}" Foreground="{StaticResource PhoneSubtleBrush}" TextWrapping="Wrap" Style="{StaticResource PhoneTextNormalStyle}" Grid.Column="0" Grid.Row="1" Grid.ColumnSpan="2"/>

 

Now I know one of you clever person is going to tell me I could have just used one 😛 Let me tell you this:

  1. I thought of it
  2. I could have searched around
  3. Realised no one really cares
  4. Created two converters and got the job done 🙂
  5. Submitted update and nap time

.

FlipTile, CycleTile and various iterations of #wpdev sdks

As you might have realised, the last few weeks, cineworld app has been my obsession. I started work on WP8 port and then back-ported some changes to WP7 version of the app (its the only one that’s live at the moment so makes sense). So what did I do so far on it (WP7 version) ?

1) Moved to using 50% space when displaying film posters, moved film little on top of the posters, removed the button style that caused me many xaml exceptions on WP8
2) Moved to using good quality images only for ImageTile control.
3) Added background task to download data files and to set Tile images

This is live as we speak and a few people emailed me saying it looks great. Now I am not going to create yet another background task for WP8 version (since I wanted to use Cycle Tile Template for WP8 version of the app.
Microsoft’s own tile related pages show how to support newer tiles for WP7.8 and WP8 even though the app itself is built on WP 7.1 (Mango) sdk

So far I stayed away from temptation of managing image repository on the device. you can see that it gets messy eventually and you have to clean up and what not.. however after implementing basic solution, it started throwing exceptions.. files used for tiles cannot be remote. Bugger.. more work

Step 1): Download image files locally. I have been using AsyncWebClient (Custom wrapper with TaskCompletionSource) exposing awaitable DownloadFile method. Plug that in and download all the files. Its background tasks, I am not really fussed about parallel execution.. just manageable execution (read sync like)

Step 2): For Uri array using relative path and ??? still nothing. More work, a quick search about the net found me a couple of posts for “live tile isolated storage image WP7” File Path in Isolated File Storage is the one that I first opened and a quick scan reminded me of “isostore” based Uri

Step 3): Save all the images to Shell\SharedContent and switch all Uri to use isotore:/Shell/SharedContent/Filename.jpg

The code below will help you create live tiles with new tile templates from WP7.1 (Mango) sdk based project. I will be using the same code for WP8 in coming days since its the same background task

A word to the wise:
* You cannot determine if the template used by Tile is Standard or a new one.
* What I now do is Create a CycleTileData template when user wants to pin (if WP7.8 or WP8) else StandardTileData
* When iterating tiles, I try CycleTileData template and failing that try StandardTileData for update

Code snippets that might help:

Add AppExtra above App element in WMAppManifest.xml file (works for both WP7.8 and WP8)

<AppExtra xmlns="" AppPlatformVersion="8.0">
  <Extra Name="Tiles"/>
</AppExtra>
public async Task DownloadFileAsync(string url, string filename, string folder = null)
{
    // create a web client for downloading the string
    var wc = new WebClient();

    try
    {
        IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();

        string file = (folder == null ? filename : String.Format("{0}/{1}", folder, filename));
                
        using (Stream s = await wc.OpenReadTaskAsync(url))
        {
            using (Stream slocal = isf.OpenFile(file, FileMode.Create))
            {
                s.CopyTo(slocal);
            }
        }
    }
    catch (Exception ex)
    {
        if (1 == 1) // just to check exceptions during debugging. do whatever pleases you
        {
        }
    }
}

//works for both WP7.8 and WP8
private static Version TargetedVersion = new Version(7, 10, 8858);
public static bool IsTargetedVersion { get { return Environment.OSVersion.Version >= TargetedVersion; } }

private static void SetTileBackground(string[] filesToShow, string folder, Random random, ShellTile currentTile)
{
    bool tryFlip = false;

    if (Config.IsTargetedVersion)
    {
        try
        {
            Uri smallimage = new Uri("Images/CycleSmall.png", UriKind.Relative);
            Uri mediumimage = new Uri("Images/CycleMedium.png", UriKind.Relative);

            UpdateCycleTile(smallimage, mediumimage, folder, filesToShow, random, currentTile);
        }
        catch
        {
            tryFlip = true;
        }
    }
    else
        tryFlip = true;
            
    if(tryFlip)
    {
        int rand = random.Next(0, filesToShow.Length);

        StandardTileData NewTileData = new StandardTileData
        {
            BackBackgroundImage = new Uri(String.Format("isostore:{0}/{1}", folder, filesToShow[rand]), UriKind.Absolute)
        };

        currentTile.Update(NewTileData);
    }
}

public static void UpdateCycleTile(
    Uri smallBackgroundImage, Uri backgroundImage,
    string folder, string[] filesToShow, Random random, ShellTile currentTile)
{
    // Get the new cycleTileData type.
    Type cycleTileDataType = Type.GetType("Microsoft.Phone.Shell.CycleTileData, Microsoft.Phone");

    // Get the ShellTile type so we can call the new version of "Update" that takes the new Tile templates.
    Type shellTileType = Type.GetType("Microsoft.Phone.Shell.ShellTile, Microsoft.Phone");

    // Get the constructor for the new FlipTileData class and assign it to our variable to hold the Tile properties.
    var UpdateTileData = cycleTileDataType.GetConstructor(new Type[] { }).Invoke(null);

    // Set the properties. 
    SetProperty(UpdateTileData, "SmallBackgroundImage", smallBackgroundImage);

    Uri[] mediumImages = new Uri[9];

    mediumImages[0] = backgroundImage;
    for (int i = 1; i < 9; i++)
    {
        int rand = random.Next(filesToShow.Length);

        mediumImages[i] = new Uri(String.Format("isostore:{0}/{1}", folder, filesToShow[rand]), UriKind.Absolute);
    }

    SetProperty(UpdateTileData, "CycleImages", mediumImages);

    SetProperty(UpdateTileData, "Title", "my cineworld");
            
    // Invoke the new version of ShellTile.Update.
    shellTileType.GetMethod("Update").Invoke(currentTile, new Object[] { UpdateTileData });
}

private static void SetProperty(object instance, string name, object value)
{
    var setMethod = instance.GetType().GetProperty(name).GetSetMethod();
    setMethod.Invoke(instance, new object[] { value });
}

This by no means is fine / perfect code. Please treat it as a PoC and do whatever you do normally

Geolocator and MovementThreshold #wpdev #win8dev

Last few months, I have had too much on my plate. Been doing lot to Windows 8 and Phone development. Surprisingly Microsoft UK is keeping tabs on phone developers who aren’t adapting to #WP8 and seemingly, I was invited to a dev event targeting the likes of me 😛

Sure I am going and in anticipation of the event, I decided to port Cineworld app to WP8. Its been a challenging task. Reworking a few bits of LongListSelector, Visual Studio / Blend disliking all the xaml and of course a button style causing xaml exception. If that wasn’t enough:

Having used Geolocator in Windows 8 app, I decided to use the same for WP8 as its usually a lot faster than GeoCoordinateWatcher. I moved the code to be more like Win8 and noticed that the location detection was flaky at best. Now I did the stupid thing and like in WP7 version, I decided to set both DesiredAccuracy to High and MovementThreshold to 0 thinking absolutely nothing.

Of course that didn’t help it, it made matters worse, instead of flaky behaviour, it decided to call it quits.

var pos = await locator.GetGeopositionAsync(TimeSpan.FromMinutes(5), TimeSpan.FromSeconds(2));

instead of timing out, it started to hang. In desperation, I started looking at other events exposed by this class and tried hooking into StatusChanged event. Now things were bad, I noticed that it was getting operation aborted exception and decided that something was seriously wrong and that I should take a nap instead 🙂

Of course the problem was still there when I woke up the next day 😛 its only later that I decided to search on Geolocation and operation aborted and realised that I wasn’t the only one and it was all my fault – causality of me setting the MovementThreshold to 0. I set it to 10 instead and bingo.. it all works.

While I didn’t find it, I hope this post helps people like an earlier post helped me.

MVVM and me – Part 2

I could have done this post yesterday but that would have been a long essay. Today we are going to look at displaying static data on XAML pages.

In C# when you have data that does not change, one tends to use const or static readonly. const causes compiler to replace all occurrences of variable usage with the actual data at compile time. That means you assemblies has no lookups at run-time. Static read-only is a static variable that can also be set in constructor – is read-only otherwise.

Now based on my previous experience doing WinForms and Webforms, normally I tend to set those directly in XAML. Say you want to content of a button or a textblock text (label). So the ideal way would be.

  1. Take View Model
  2. Define consts
  3. Set bindings to consts
  4. Compile and reload

Eureka.. there’s nothing..

Well XAML bindings make a big fuss of INotifyPropertyChanged interface. From sample I know that it works with properties so could it be that ?

Lets start:

  1. Take View Model
  2. Define consts
  3. Define properties
  4. Set property in the constructor to consts
  5. Set bindings to properties
  6. Compile and reload

There.. much better..

Lesson, const and compiler time optimisations are no good.. you need to define properties and additionally call PropertyChanged events and what not including set the properties at VM Creation in order to display data the proper MVVM way. A Single task of setting a text to a textblock or a button is translated into a handful tasks..

Update 1:
My friend @Scottisafool … suggested an alternative approach that he tends to use

  1. Define resources in App.xaml
  2. Set bindings to resources
  3. Compile and reload

This also works.. sure it means that all your strings are in one place but that’s still not MVVM
So it turns out there is not right way but there is a wrong way!! Everything else but code-behind as the last resource is the pukka MVVM way. Wrap up for today I think.

Update 2:
More messages suggesting that the mechanism to declare labels is to either hard code those or use Resources. That’s all fine.. I could use ResourceDictionary just in case the future me might want to localise the app.

That however still leaves the need to support of real consts impossible. There isn’t any support for those in bindings wrt View Model