One XAML for UWP, Windows 8.1 and Windows Phone 8.1

I was recently involved in a conversation on how to have the easiest way to maintain a XAML view across a UWP (Universal Windows Project) a Windows 8.1 and Windows Phone 8.1 projects. There are a few options and the most straight forward way to do it with a UserControl residing in a Portable Class Library. However…

What if you wanted to have tailored code for each without littering your code with #ifdef but still share a XAML view?  The XAML View might be what you’re looking for. This is a tutorial on how to do just that. An example project is available for download at the end of the article. Let’s get started:

Step 1:

Create a new 8.1 Universal app

tpx1

Step 2:

Move the Shared, Windows and Windows Phone projects out of the virtual folder and delete the folder (you can cut/paste or just click and drag them). The solution should look like this now

tpx2

(Note: If you’re doing this to a solution that has many other projects, you might want to skip this step and add the UWP project to the virtual folder instead)

Step 3:

Add a new UWP project to the solution and name it the same as the 8.1 app, but with the Universal suffix.

tpx3

(Your solution should look like this now)

tpx4

Step 4:

Add a “Views” folder to each of the projects

tpx5

Step 5:

Within the Universal project, right click and Add > New Item > XAML View

tpx6

Step 6:

Move the new XAML View to the Shared project’s Views folder and change the namespaces in the view to match

tpx7

Step 7:

Delete App.xaml from the Universal project and add a reference to the solution’s Shared project (Note: this is in the new Shared projects references section)

tpx8

Step 8:

Here’s where the magic happens. We’ll be adding a code behind for this view in each of the projects! I’ll break this down into sub-steps:

  1. Add a new class to the Windows 8.1 project’s Views folder (Add > New Item), name it as if it were the code-behind for the view. In this case it would be SharedPage.xaml.cs
  2. Change the namespace of the class to Views
  3. Add the public, sealed and partial modifiers to the class
  4. You’ll next need to inherit from the Page class
  5. Add a page constructor
  6. Now you can copy and paste this new class into each of the platform projects (remember, we do not need it in the Shared project)

This is what it should look like

tpx9

Step 9:

You’ll need to quickly pop into the Build Configuration Manager and check off Build and Deploy for the Universal app (you can find Configuration Manager in the target dropdown or in the Build menu)

tpx10

Step 10:

Lastly, for the purposes of this demo, go to App.xaml.cs and change the initial launch target (MainPage) to be the new shared page (SharedPage). I could have put a button on MainPage for each app, but let’s keep this tutorial as short as possible.

tpx11

Final result!

This is the same XAML View compiled with different code-behind files 🙂

tpx12

(NOTE: I put a TextBlock on the SharedPage and update the text in each constructor to show which platform launched it. Here are the WP8.1 emulator, Windows 10 PC and Windows 10 Mobile Emulator running their apps all showing the same XAML view).

Source Code

Download the Sample App Source Code From Here

Bonus:

The Telerik Universal Control can be used in the shared page as long as each of the projects have a reference to the Telerik UYI for Windows Universal DLLs. Send me a tweet and show me what you’ve done, I’ll RT your awesomeness!

Read-only Address Bar for Webview

If you are having a Windows Store application fail certification or being unpublished because you have violated Policy 2.1.2  – requires a visible address bar that displays a secure connection to users when they enter financial information or complete a transaction (see policy definitions).

The reason for this rule is because you are bringing the user to a site that is using HTTPS and the user may be entering in secure information. You need to give the user confidence that you are not spoofing the website and stealing the entered information.

This is easily remedied by adding a TextBlock (which is read-only) to the page and displaying the web address every time a page loads. Conveniently, the WebView has a perfect event handler for this: OnNavigationStarting.

You can get the web address through the Uri property of the WebViewNavigationStartingEventArgs and then set it to the Text property of your TextBlock. This is better explain with some example code.

Let’s say you have a page with a webview, you want to add a TextBlock to the top. You’ll want to create a Grid with two rows, set the first row’s height to Height=”Auto”. Put the TextBlock in Row 0 and the WebView in Row 1.

Now, let’s hook into NavigationStarting of the WebView, and in the event handler grab the Uri and set it to your TextBlock.Text property.

Here is what you should have (put some placeholder text so you can see what it looks like, also use gray for a foreground text color so the user knows it is read-only).

<Grid Background="White">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <TextBlock x:Name="MyAddressBarTextBlock" 
                           Text="http://www.somewebsite.com" 
                           Foreground="Gray" />
            <WebView x:Name="MyWebView" 
                     NavigationStarting="MyWebView_OnNavigationStarting"
                     Grid.Row="1"/>
</Grid>

…and here is what your event handler should look like:

private void MyWebView_OnNavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
{
     try
     {
        //the event args contain the web address, get it from args.Uri and hold it in a local variable
        string websiteAddress = args.Uri.ToString();

        //now set the address to the Textblock's text property
        MyAddressBarTextBlock.Text = websiteAddress;
      }
      catch (Exception ex)
      {
         //do something with the error
      }
}

That’s all there is to it! Every time the WebView is going to load a page, the NavigationStarted event will fire and your TextBlock will show the upcoming address.

Here are some screenshots from the my sample…

WinAddressBar2 WinAddressBar

PhoneWebAddressBar2 PhoneWebAddressBar

Happy Coding!
Lance

Extra Credit and Sample Universal App:
This example is barebones, I challenge you to make a user control that houses the WebView and TextBlock, then you can reuse it across your app instead of doing this on every page. I’ve written a demo Universal app for you that has the following:

  • UserControl in the Shared folder (ReadOnlyWebView.xaml)
  • ProgressRing for loading content
  • Extends Source DependencyProperty and exposes Refresh method
  • Instantiates the custom control in MainPage.xaml for both Phone and Windows projects

This should wet your appetite and show you how to extend it further.

DOWNLOAD THE SAMPLE UNIVERSAL APPLICATION

Invalid XAML error updating from WP7

We are now seeing the beginning of the fast decline of Windows Phone 7 as it exits the market over the next several months, many of you will need to act to update your app to at least Windows Phone 8.  I did this for all of my WP7 apps and there was one error that was In just about every upgrade:

An error on this XAML namespace declaration:

xmlns:controls="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls"

Previous to Windows Phone 8, the Pivot and Panorama controls were part of a toolkit. The Windows Phone team did a solid by included these in the OS, they also added new controls like the LongListSelector to replace the toolkit’s ListPicker . These controls are now found in the Phone namespace.

It’s a very frustrating problem if you’re seeing it for the first time. Don’t worry, there is a really easy fix… Delete the xmlns:controls line and use only the xmlns:phone one or edit it and remove the “.Contols” part of the assembly pointer. Here is what it will look like after doing the edit option:

xmlns:controls="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"

However, in many newer app templates, this is already used for the xmlns:phone declaration that looks like this:


xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"

If you do have the xmlns:phone declaraiton, simply delete the bad line xmlns:controls line and change any UI controls on the page to use the phone one instead. For example

Change:

<controls:Pivot x:Name="MyPivot"> foo </controls:Pivot>

to

<phone:Pivot x:Name="MyPivot"> foo </phone:Pivot>

I hope this blog post was found when you searched for the error and it fixed it for you 🙂 Let me know if this doesn’t fix it for you and I’ll take a look at your XAML.

Happy coding!

Attend Publish Boston & Win Big

Since the prizes are really awesome for this event (May 17th), I’m going to start off with them. We will be rewarding the best student, best individual, and best company in each of the categories below:

  • Top Windows 8.1 app
    • Trip to the 2014 Formula 1 United States Grand Prix in Austin, TX.
    • 9 runner-up Nokia Lumia 1520 prizes
  • Top Windows Phone app
    • $10,000 to build your own “Dev Cave”
    • 9 Runner-up Nokia Lumia 1520 prizes
  • Top Cross Platform app
    • MakerBot 3D printer
    • 9 Runner-up Nokia Lumia 1520 prizes
  • Breakthrough in App Innovation and Design
    • MakerBot 3D printer
    • 9 Runner-up Nokia Lumia 1520 prizes

But wait, there’s more! I will be giving away these prizes at the end of the day…

  • Dell Venue Pro 8
  • Nokia Lumia 1520
  • Surface Pro and Surface Bluetooth Wedge Mouse (only windows phone entries are eligible)
  • 2 Nokia Lumia “Hero” Devices, winner’s choice of a Lumia 1020, 928, 925 or 920 (only windows phone entries are eligible)

So you are probably now asking yourself, “How do you win these prizes?”, funny that you ask because I was just going to tell you how you can…

Participate

Microsoft is holding an awesome world-wide Hackathon-style event titled //publish/.  The main purpose of the event is for you to publish your app to the Windows Phone or Windows Store. The app can be:

  • An app that you start working on now
  • An old app that you haven’t been able to finish
  • Some thing you build from scratch at the event

At the event –  If you attend in person on May 17th and submit your app to DevCenter by 7 PM, you will be able to demo it to the audience. The winners of the local prizes (second group) will be randomly chosen from those who successfully submitted (you will need to show me that the app is in submission or has been published to qualify).

After the event – The grand prizes (first group) will be awarded after the apps are published in the store. The winners will be chosen from three groups; student, indie and small business. For more details about the grand prize contest, go here.

How do you sign up?

Go here to register for //publish/ Boston  ( tweet ‘@lancewmccarthy I just registered for #pubWin Boston! #wpdev’ for a RT )

If you are not close to Boston and want to see if there is a //Publish/ event near you, go here and filter the list from the drop down. Note that the local event’s prizes will be different, but the grand prizes are the same.

I hope to see you all there, this is going to be tons of fun. I will come back here and update this post with a final agenda and more details when they become available.

Happy coding!

Lance

Legal Stuff: As with all my giveaways and contests, by participating and receiving a prize, you agree to this disclaimer.

Build 2014 Videos

This year’s Microsoft Build conference was jam packed with Windows Phone goodness. In fact, there is too much to take in at once. So what I’ve done for you is break it down into sections so that you can bookmark this page and come back at your leisure.

These videos are in no particular order, so review them all before you choose, enjoy!

Windows Phone Development

Windows and Windows Phone Design related

Market, Store, Performance and Analytics related

HTML, WinJS/javascript and Web related

Enterprise related

 

Here is the main Ch9 Build 2014 page if you want to look up any sessions not related to Windows or Windows Phone development. Let me know if you have any trouble with this page or if there is something you think I should add.

Happy coding!

 

 

Monetizing App Studio with Ads

So, you’d like to put some ads in your awesome App Studio app? No problem! I thought I would write a post to show just how easy it can be. Follow these easy steps and you’ll start earning money from ads…

Ad provider

The ad provider is the service the AdControl in your app gets the ad to display and also where you earn the revenue. As of Windows Phone 8 there is a PubCenter AdControl built into the framework, all you need to do is get an ApplicationId and an AdUnitId. You get that information from Windows Phone DevCenter, find out how to get your ApplicationId and AdUnitId in this great blog post.

If you want to use a separate Ad provider, for example AdDuplex, you’ll need to add the provider’s DLLs to your project. I’m using AdDuplex in the example below, learn how to add AdDuplex to your project here.

Step One: Enable ads in App Studio

Before generating your App Studio app, you’ll want to enable ad support. On the Publish Info tab, turn on the Enable ad client in the source code switch (see #2 in this screenshot):

App Studio Screenshot

Next, generate the app and download the source code.

Step Two: Open App in Visual Studio

After downloading the source code, you might need to unblock the binaries before unzipping the folder. This is a built-in security feature that prevents internet-downloaded code from running on your machine. Since we know where these files came from, it’s ok to go and unblock them. Here is how to do that:

  1. Right click on the downloaded zip folder
  2. Select “Properties
  3. If you see an “Unblock” button, click it. If you do not, continue to step 4.
  4. Now you can safely unzip the folder

Next, drill down into the unzipped folder until you see the Visual Studio solution file. Double click to open it in Visual Studio (Note: You need Visual Studio installed. If you do not, you’ll need to download and install the Windows Phone SDK from here).

Step Three: AdControl on MainPage.xaml

Drill Down to MainPage.xaml, see this screenshot to help you find it:

Visual Studio Solution Explorer

Near the top of the page, you will see a commented out section of code (approximately line #50). This is the built-in AdControl. All you need to do is:

  1. Uncomment the AdControl (delete the <!– and –> characters before and after the AdControl)
  2. Replace the placeholder ApplicationId and AdUnitId with yours

In this screenshot, I demonstrate how to use an AdDuplex ad control instead of the built-in AdControl.

MainPage

That’s all there is to it! Now you can do a Build and publish the generated XAP file. (If you are not familiar with how to publish an app built with Visual Studio, see this documentation)

This image shows what the published app looks like running on a phone, see for yourself and download the app.

NetduinoNinjaScreenshot

Happy coding!

Lance

Here are some follow-up resources to help you monetize your apps:

Make An App Dev Happy Day

The Windows Phone developer community is amazing in and of itself, but what happens when you add something like #makeAnAppDevHappyDay? You get pure awesomeness. What is #makeAnAppDevHappyDay?  Nokia DVLUP added fuel to an idea started by Dan Colasanti for developers to help them get the word out about their apps and generate app reviews.

Share your app…

Post your app’s name and link to the store on twitter with the #makeAnAppDevHappyDay, other devs will download your app and leave a review. you do the same for them (It’s also a great way for you to find new apps). Here is an example:

Check out my latest app, [app name here] thanks! [app link here] #MakeAnAppDevHappyDay

Share another app…

It is also a way to let the developers know that you have rated this app, for example:

I just rated [app name here] five stars, great job guys! You gotta try it out [app link here] #MakeAnAppDevHappyDay

When is it?

This happens every month on the first Friday. Just search the hashtag, or use this direct link and enjoy! I’m turning on comments for this blog post, leave a comment below and let everyone know #MakeAnAppDevHappyDay has worked for you

Get It In The Store

UPDATE:
This event is sold-out! If you were not able to register in time and need help getting your app published, send me an email and I’ll help you directly.

WPDev Day

Me and several other experts will be spending 6 hours with you on Saturday February 1st, 2014 to help you over come any obstacles that is preventing you from publishing an app. If you do not have any apps in the works, then come and build an App Studio app with our help. Click the Eventbrite button above to get your ticket.

Important: This is a very limited seating event and is intended for the Northeast United States, please do not register if you are 6000 miles away or do not intend on showing up, you’ll only be taking a seat away from another dev who needs it.

Here is the preliminary schedule (subject to tweaking):

  • 12 PM DevCenter Submission Walkthrough (30 minutes): See just how easy it is to submit and publish an app worldwide
  • 12:30 PM Build an app in 30 minutes with App Studio (30 minutes): See how to build an app from an idea to publishable in 30 minutes, literally.
  • 1 PM – 1:30 PM Lunch: I’ll be providing food and snacks. This is when you think about what you need help with or when you should think of your app idea for App Studio.
  • 1:30-6 PM Hands-on time: The experts will be available to help during this time. They will be walking around helping and/or attending to requests for help.

By the end of the day I fully expect everyone’s apps will be ready and submitted to DevCenter and on it’s way to the global app marketplace.

What will you need to bring?

  • If you need help on an existing app, bring your laptop dev environment with your app on it.
  • If you want to build an app without any code, bring a laptop that has a modern browser (IE10-11, Chrome). You’ll only need your browser to build and submit the app to the store. If you do not have a Windows Phone, the experts will be able to help you test the app on their phone

Giveaways

Everyone who attends and publishes their app will be entered to win a “hero” Nokia Lumia (1020, 928, 925, 920, etc) of their choice. I’ll be saving some swag/prize surprises for the day of the event. Also, Microsoft will be bringing some prizes of their own! I will update this post with more details as we get closer to Feb 1st.

Note: If you accept a prize from me, you agree to these terms.

Everything Must Go!

UPDATE

The winners have been picked, congratulations to all (I emailed you directly if you were a winner)! If you did not win, keep your app up to date (update at least once every 60 days) and you’ll always be eligible for my giveaways.

___________________________________________

I’m raffling off all my remaining gadgets and swag in two weeks (deadline is Dec 31st)! The only 2 conditions to enter are that you are in my region (see below) and that you published or updated an app in the last 6 months (since June 31st).

If you need to update or publish an app, you have just enough time to get it in. If you don’t have an app yet, I recommend going to Microsoft’s App Studio and building one… you can build a store-ready app in an hour. If you don’t have a Windows Phone DevCenter account I will get you one, this will also give you a Windows 8 developer account.

The Prizes:

To Enter:

Simply email me (ext-lance.mccarthy@nokia.com) the following info by Dec 31st:

  • Name (first/last)
  • Location (city/state only)
  • Dvlup Username (if you don’t have one, go to www.dvlup.com and register. It’s free and takes 30 seconds)
  • The app’s link to the store (the one you’ve published or updated).

That’s it! I’ll draw the winner on Jan 2nd and notify the winners via email.

Conditions

You must live in my region and have published or updated an app since June 31st

My region consists of the following states:

  • Massachusetts
  • New Hampshire
  • Maine
  • Vermont
  • Connecticut
  • Rhode Island
  • Michigan
  • Ohio
  • Indiana
  • Illinois

By entering this contest, you agree to the terms of service.

WpDev Success Kit

Now that you’re published, get this kit from my friends at Microsoft…

Get your app noticed with your personalized Windows Developer Success Kit. With customized promo materials specifically for your app, plus a little fun thrown in, we want to help you reap the rewards of your hard work.

Your Windows Developer Success Kit contains:

  • 100 customized business cards with app tile & down…load directions for you to hand out
  • 100 customized stickers with app tile to give away Promotion on MSDN East’s Facebook page facebook.com/msdneast
  • A $5.00 USD Starbucks card to keep you awake while you work on your next great app
  • 1600 Xbox Live points for a gaming break between coding sessions

How to get your kit: Email: msdneast@Microsoft.com Include: Your name, your app name and deep link, your physical mailing address, and the workshop/city you attended if any.

Terms and Conditions: *Offer valid for Windows or Windows Phone apps published in the Store between July 1 and December 31, 2013 in these states: Maine, New Hampshire, Vermont, New York, Massachusetts, Connecticut, Rhode Island, New Jersey, Virginia, Maryland, West Virginia, Pennsylvania, North Carolina, South Carolina, Georgia, Alabama, Florida. No purchase necessary. Limit 5 kits per Developer; one kit per published app. Please allow 2-4 weeks for delivery.