Sharing Code Part II: Partial Classes

In the first part of Sharing Code series we looked at sharing a common class source file across three different platforms. Continuing the series on Sharing Code across various platforms, we’ll look at leveraging partial classes to help share code across our many apps on Windows 8, Windows Phone 7 & Windows Phone 8 using the same source code from Part I.

What is a Partial Classes?

Essentially a partial class allows you to separate a class or structure into two or more separate files. Personally, I use this technique to hide any specific platform code from other platforms.

Implementation of Partial Class

We’ll use this in a the Math2 class to create a Divide() method that returns a float.

NOTE: you can create the float Divide() method within the same class but for demonstration purposes we’ll assume we want to have the float Divide() hidden from WP8_App and W8_App

In WP7_App, open up Math.cs and add the partial keyword to the class. You should end up with something like

public partial class Math2 {..}

Next, add a new class called Math_WP7.cs and change the implementation to the following

namespace Common
{
    public partial class Math2
    {
        public float Divide(float x, float y)
        {
            return x / y;
        }
    }
}

Updating the UI

To use the new overloaded Divide() method, we’ll have to add some code to our UI, Update the btnDivide.Click() handler to the following

lblResult.Text = Common.Math2.Default.Divide(float.Parse(x.Text), float.Parse(y.Text)).ToString();

Now, when you run the code, you will get a float value returned and shown in the display.

9

Another Example

Although the example above shows how to use partial classes, the example is pretty basic. A real world example could be getting the device Unique Id.

In the WP7_App project, add a class called DeviceInfo and change the implementation to the following

namespace Common
{
    public partial class DeviceInfo
    {
        private static DeviceInfo _default;
        public static DeviceInfo Default
        {
            get
            {
                if (_default == null)
                    _default = new DeviceInfo();
                return _default;
            }
        }

        private DeviceInfo()
        {
        }
    }
}

Add another class file called DeviceInfo_WP7.cs and change the implementation to the following

namespace Common
{
    public partial class DeviceInfo
    {
        private string m_DeviceUniqueId;
        public string DeviceId
        {
            get
            {
                if (m_DeviceUniqueId == null)
                {
                    object val;
                    if (Microsoft.Phone.Info.DeviceExtendedProperties.TryGetValue("DeviceUniqueId", out val))
                        m_DeviceUniqueId = Convert.ToBase64String((val as byte[]));
                }
                return m_DeviceUniqueId;
            }
        }
    }
}

Now open MainPage.xaml.cs and in the constructor add the following line

System.Diagnostics.Debug.WriteLine(Common.DeviceInfo.Default.DeviceId);

Run the app and in the console output window, you will see the device unique ID displayed.

Why do this?

If you have done Windows Phone 8 or Windows 8 development and want to get the device unique ID, you will know that the code to get that information is different. Partial classes will help us solve this while maintaining a common API across the different platforms which is Common.DeviceInfo.Default.DeviceId.

In WP8_App and W8_App add the following line to the MainPage.xaml.cs constructor

System.Diagnostics.Debug.WriteLine(Common.DeviceInfo.Default.DeviceId);

Add the DeviceInfo.cs file to the WP8_App and W8_App projects making sure to add it as a link to the file. In the W8_App project, create a new file called DeviceInfo_W8.cs with the following implementation

namespace Common
{
    public partial class DeviceInfo
    {
        private string m_DeviceUniqueId;
        public string DeviceId
        {
            get
            {
                if (m_DeviceUniqueId == null)
                {
                    var token = Windows.System.Profile.HardwareIdentification.GetPackageSpecificToken(null);
                    var hardwareId = token.Id;
                    var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(hardwareId);

                    byte[] bytes = new byte[hardwareId.Length];
                    dataReader.ReadBytes(bytes);

                    m_DeviceUniqueId = BitConverter.ToString(bytes).Replace("-","");
                }
                return m_DeviceUniqueId;
            }
        }
    }
}

Now in the WP8_App project, create a new file called DeviceInfo_WP8.cs with the following implementation

NOTE: you will have to add ID_CAP_IDENTITY_DEVICE to your WMAppManifest.xml for this to work

namespace Common
{
    public partial class DeviceInfo
    {
        private string m_DeviceUniqueId;
        public string DeviceId
        {
            get
            {
                if (m_DeviceUniqueId == null)
                {
                    m_DeviceUniqueId = Windows.Phone.System.Analytics.HostInformation.PublisherHostId;
                }
                return m_DeviceUniqueId;
            }
        }
    }
}

Now when you run the code on all platforms

  1. You have a different ID returned on all three platforms
  2. You use a common API DeviceInfo.DeviceId property to acess the device ID

You can download the source code off github.

Up Next

In the next part, we’ll look at using Conditional Compile statements to try and share some more code and we’ll look at some of the UI Code.

 

 

 


Warning: count(): Parameter must be an array or an object that implements Countable in /nfs/c07/h02/mnt/110221/domains/markarteaga.com/html/wp-includes/class-wp-comment-query.php on line 405