Mobile Corner

Integrate Windows Phone 8 Functionality Into Windows Phone 7 Apps

How to use the new Windows Phone 8 SDK to build applications across both Windows Phone 7 and Windows Phone 8.

Windows Phone 8 devices are starting to appear in the market. However, it will be a while before they outnumber the existing Windows Phone 7 devices. The Windows Phone 8 SDK already supports developing applications for both versions of Windows Phone, and applications targetting Windows Phone 7 will run without modification on Windows Phone 8. One question that remains unanswered is how best to develop applications that work on Windows Phone 7, yet take advantage of the new features of Windows Phone 8. In this article we'll touch on two techniques you can use to solve this issue.

Strategy No. 1: Seperate Projects
The first strategy is to create separate Windows Phone projects for each version of the platform. The source code files can be linked to both projects, allowing for full reuse of the code base. In order to support some of the additional features of Window Phone 8, you can then simply add code to the Windows Phone 8 project.

This can be done by including additional code files, or by placing conditional compilation guards around the code. The following code illustrates creating an appointment with a conditional guard, making it only available in the Windows Phone 8 project.

#if WP8
    var appt = new SaveAppointmentTask
                    {
                        AppointmentStatus = AppointmentStatus.Busy,
                        Details = "This is a super important appointment",
                        EndTime = DateTime.Now.AddHours(6),
                        StartTime = DateTime.Now.AddHours(4),
                        Reminder = Reminder.ThirtyMinutes,
                        Subject = "Important Appointment"
                    };
    appt.Show();
#endif

Of course, you'll need to define the WP8 symbol in the properties for the Windows Phone 8 project for the code to be included in the compilation. This is illustrated in Figure 1, in which the Conditional compilation symbols have been amended to include WP8.


[Click on image for larger view.]
Figure 1. Project properties, with compilation guards.

This strategy is particularly useful if there are a large number of new Windows Phone 8 features you want to take advantage of. The downside is that you have to then deploy and manage two different versions of the application.

Strategy No. 2: Reflection
Another strategy is to build a Windows Phone 7 version of the application and use reflection to target specific Windows Phone 8 features. An example of this is documented on MSDN. This strategy works for more than just using the new tile templates, too. In this example, we're going to use a similar approach to use the SaveAppointmentTask in a Windows Phone 7 application. The task will only be available, however, when run on a Windows Phone 8 device.

In order to use the SaveAppointmentTask from within a Windows Phone 7 app, we're going to use reflection to dynamically create a runtime instance of the task. Our application will be compiled against the Windows Phone 7 core libraries, which means we can't reference any types that were introduced in Windows Phone 8; specifically, in this case, the SaveAppointmentTask. But with reflection, at runtime we can attempt to locate this type; and if it exists, create and populate an instance of the task.

The first step is to see if the type exists. On Windows Phone 7, the type won't exist; on Windows Phone 8, it will. In the following code, if the type exists, reflection is used to locate the default constructor, which is then used to create an instance of the SaveAppointmentTask.

var type = Type.GetType("Microsoft.Phone.Tasks.SaveAppointmentTask, Microsoft.Phone");
if (type != null){
 var constructor = type.GetConstructor(new Type[] {});
 var appt = constructor.Invoke(null);

The next step is to set all the relevant properties before invoking the Show method on the task. In order to streamline the reflection code required for locating the property to be set, and then setting the property value, a helper method can be used:

private static void SetProperty(object instance, string name, object value)
{
    var setMethod = instance.GetType().GetProperty(name);
    setMethod.SetValue(instance, value,null);
}

Next, set the Subject, StartTime and EndTime, then invoke the Show method:

SetProperty(appt, "Subject", "Important Appointment");
SetProperty(appt, "StartTime", DateTime.Now.AddHours(4));
SetProperty(appt, "EndTime",DateTime.Now.AddHours(6));

type.GetMethod("Show").Invoke(appt, null);

Invoking this code will display the New Appointment dialog, shown in Figure 2.


[Click on image for larger view.]
Figure 2. The SaveAppointmentTask after invoking the Show method.

The code presented so far illustrates the basic mechanism for using reflection to dynamically create the SaveAppointmentTask. The problem is that doing it this way makes our application code quite messy and hard to follow.

Listing 1 includes a substitute SaveAppointmentTask you can use within your Windows Phone 7 application. The static constructor uses reflection to locate the type information necessary to create the actual SaveAppointmentTask. If this type isn't located, the IsSupported property returns false. This class can now be used by your code in the same way as the actual SaveAppointmentTask.

if (SaveAppointmentTask.IsSupported)
{
    var appt = new SaveAppointmentTask
                    {
                        AppointmentStatus = AppointmentStatus.Busy,
                        Details = "This is a super important appointment",
                        EndTime = DateTime.Now.AddHours(6),
                        StartTime = DateTime.Now.AddHours(4),
                        Reminder = Reminder.ThirtyMinutes,
                        Subject = "Important Appointment"
                    };
    appt.Show();
}
More Uses of Reflection
The use of reflection isn't limited to working with the new tile templates or the SaveAppointmentTask. You can use this technique with the other new tasks, as well as other new Windows Phone 8 features; for example, the ability to create a custom contacts store which will populate application contacts into the People hub, or read and write to NFC tags.

About the Author

Nick Randolph runs Built to Roam, a consulting company that specializes in training, mentoring and assisting other companies build mobile applications. With a heritage in rich client applications for both the desktop and a variety of mobile platforms, Nick currently presents, writes and educates on the Windows Phone platform.

comments powered by Disqus

Featured

  • Mastering Blazor Authentication and Authorization

    At the Visual Studio Live! @ Microsoft HQ developer conference set for August, Rockford Lhotka will explain the ins and outs of authentication across Blazor Server, WebAssembly, and .NET MAUI Hybrid apps, and show how to use identity and claims to customize application behavior through fine-grained authorization.

  • Linear Support Vector Regression from Scratch Using C# with Evolutionary Training

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the linear support vector regression (linear SVR) technique, where the goal is to predict a single numeric value. A linear SVR model uses an unusual error/loss function and cannot be trained using standard simple techniques, and so evolutionary optimization training is used.

  • Low-Code Report Says AI Will Enhance, Not Replace DIY Dev Tools

    Along with replacing software developers and possibly killing humanity, advanced AI is seen by many as a death knell for the do-it-yourself, low-code/no-code tooling industry, but a new report belies that notion.

  • Vibe Coding with Latest Visual Studio Preview

    Microsoft's latest Visual Studio preview facilitates "vibe coding," where developers mainly use GitHub Copilot AI to do all the programming in accordance with spoken or typed instructions.

  • Steve Sanderson Previews AI App Dev: Small Models, Agents and a Blazor Voice Assistant

    Blazor creator Steve Sanderson presented a keynote at the recent NDC London 2025 conference where he previewed the future of .NET application development with smaller AI models and autonomous agents, along with showcasing a new Blazor voice assistant project demonstrating cutting-edge functionality.

Subscribe on YouTube