Mobile Zone is brought to you in partnership with:

Mikael is the founder of Adafy Oy, a Finnish software startup providing development services for Windows Phone, Windows 8 and Windows Azure. Adafy is available for hire: www.adafy.com. Mikael is a DZone MVB and is not an employee of DZone and has posted 46 posts at DZone. You can read more from them at their website. View Full User Profile

Converting Windows Phone 7 ANID to Windows Phone 8 ANID2

08.22.2013
| 929 views |
  • submit to reddit

Windows Phone 7 has an anonymous user ID property called ANID. Windows Phone 8 replaced that with ANID2. The difference is that ANID2 is dependent on the app’s publisher ID. With ANID and ANID2 you can identify your user. This is helpful, for example, if you want to store some of your user's app data in the cloud.

The Problem

The problem is that, if a user upgrades his or her phone from WP7 to WP8, his or her ANID changes. Before, his or her ANID was the same in all of his or her apps. Now, as the publisher ID is part of the ANID2, his or her ANID2 will be the same in different apps only if the apps are from the same publisher.

The Solution

If you use ANID to identify your users, it may be useful to always convert the ANID to ANID2. This way, even if your user upgrades his or her phone, you can still identify him or her. It’s possible to convert from ANID to ANID2.  Microsoft has released a C++ sample on how to do the conversion and this post shows the same algorithm in C#, with big help from SO.

The Code

To do the conversion from ANID to ANID2, you have to have your publisher ID (GUID). Also, the WP7 ANID must be in “full” format. Some example code on the net shows how you take a substring from the ANID and use that as an ID. Don’t do that. You need the whole ANID (in theory, at least).

Here’s the code that does the conversion:

public static string GetAnid2FromAnid(string anid, Guid publisherId)
{
    var anidAsBytes = System.Text.Encoding.Unicode.GetBytes(anid);
    var publisherAsBytes = publisherId.ToByteArray();
 
    var macObject = new HMACSHA256(anidAsBytes.Take(anidAsBytes.Length / 2).ToArray());
    var hashedBytes = macObject.ComputeHash(publisherAsBytes);
 
    var result = Convert.ToBase64String(hashedBytes);
 
    return result;
}
Published at DZone with permission of Mikael Koskinen, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)