Category Archives: Windows 8

Windows Tile Updater (Part 5 – sharing XAML)

In Part 4 we finished with an MVVM app, running on both Windows 8 and Windows Phone. In this post I’m going to explore the idea of using the same XAML.

Is this a good idea?

The very short answer is probably “NO!”. The problem is that in anything but the most trivial of applications, the XAML will need to differ. In this application, it probably doesn’t matter, but then, it wouldn’t kill anyone to maintain two sets of very trivial XAML either.

My approach to this, and to the above question is to create a custom user control, and then use that in both applications. The good thing about this is that it does make sense to share user controls (to me anyway).

New UserControl

We’ll create a View directory in the shared project, and add the UserControl there:

NewView

It should look like this:

<UserControl
    x:Class="TileUpdater.View.MainView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:TileUpdater.View"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300"
    d:DesignWidth="400"
    DataContext="{Binding MVM, Source={StaticResource MainViewModel}}">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <StackPanel Orientation="Horizontal" Margin="20" Grid.Row="0">
            <TextBlock FontSize="30" Margin="10">Image</TextBlock>
            <TextBox Text="{Binding ImagePath}" Margin="10"/>
        </StackPanel>

        <StackPanel Orientation="Horizontal" Margin="20" Grid.Row="1">
            <TextBlock FontSize="30" Margin="10">Text</TextBlock>
            <TextBox Text="My Phone Number: 123456 890 12" Margin="10"/>
        </StackPanel>

        <Button Grid.Row="2" Command="{Binding UpdateCommand}">Update</Button>
    </Grid>
</UserControl>

You’ll be familiar with this XAML by now. Nothing had changed, it’s the same. In the Phone app, we’ll replace the whole XAML with the following:

<Page
    x:Class="TileUpdater.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:TileUpdater"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:view="using:TileUpdater.View"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <view:MainView/>
</Page>

And the Windows 8 XAML with this:

<Page
    x:Class="TileUpdater.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:TileUpdater"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:view="using:TileUpdater.View"
    mc:Ignorable="d">    

    <view:MainView/>
</Page>

Other than the theme, they are the same. You could obviously just have MainPage in the shared project, but personally, I don’t believe that is extensible; if you do so, you run the risk of ending up with an overly complex XAML file trying to cater for each separate project type.

Conclusion

Just a short post this time. In the next post on this, I’m going to add the missing functionality. This should be far easier now that the whole application is basically inside the shared project.

Windows Tile Updater (Part 3 – Move the code to a shared project and create the Phone App)

In the third part of my series on creating a universal app, I’m going to transfer the code that we created in part 2 and move it into a shared project.

If you want to have a look at the source code, or just use it for something, it’s here:

https://windowstileupdater.codeplex.com/

So far, we have code to update the tile, but it’s in the Windows 8.1 app. Let’s just move that to the shared project:

movetoshared

TileUpdater.cs looks like this:

    public class UpdateTile
    {
        private static void UpdateTileImage(string image)
        {
            XmlDocument xmlDoc = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150Image);

            XmlElement imageNode = (XmlElement)xmlDoc.GetElementsByTagName("image")[0];
            imageNode.SetAttribute("src", string.Format("ms-appx://{0}", image));

            Windows.UI.Notifications.TileUpdater tileUpdater = TileUpdateManager.CreateTileUpdaterForApplication();
            TileNotification tileNotification = new TileNotification(xmlDoc);
            tileUpdater.Update(tileNotification);
        }

        public static void UpdateTileImage()
        {
            string image = "/Assets/test.png";
            UpdateTileImage(image);
        }
    }

You might notice this is precisely the same code. The button click event on the main page looks like this now:

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            TileUpdater.UpdateTile.UpdateTileImage();            
        }

Now, run again and the behaviour should remain the same. This isn’t much – I mean, if you’re reading this and have just found out how to separate code from the main program then you might be reading the wrong blog. So, let’s try wiring up the phone app. We’ll start with the XAML:

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <StackPanel Orientation="Horizontal" Margin="20" Grid.Row="0">
            <TextBlock FontSize="30" Margin="10">Image</TextBlock>
            <TextBox Text="c:locationimage.png" Margin="10"/>
        </StackPanel>

        <StackPanel Orientation="Horizontal" Margin="20" Grid.Row="1">
            <TextBlock FontSize="30" Margin="10">Text</TextBlock>
            <TextBox Text="My Phone Number: 123456 890 12" Margin="10"/>
        </StackPanel>

        <Button Grid.Row="2" Click="Button_Click">Update</Button>
    </Grid>

The XAML is familiar – I copied it verbatim from the Win 8 app (as I said in the last post, I will try to rationalise this a little, although other than in a very trivial app such as this, you would probably want the XAML to be different). And the code behind:

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            TileUpdater.UpdateTile.UpdateTileImage();
        }

And, it works:

phoneappstartscreen

Did it just work – just like that?

Well, no.

Okay – there was some fiddling – here’s the fiddling:
1. The app will (again) not be pinned to the start screen, you’ll need to use the emulator to do so.
2. The tile will, again, initially be a small square (half the size of a wide tile – 150 x 150); this will need to be a wide tile, and to do so, you need to press and hold and the first reduce the size, before increasing to a wide tile.

Conclusion

Okay – so, we now have a Windows Store and Phone App. There’s a common codebase (admittedly it’s a bit scrappy), and the phone app took around 20 seconds.

In the next post I’m going to tidy up the code and investigate options for using shared XAML.

Windows Tile Updater (Part 2 – creating the project and tile update logic)

In my first post of this series I looked at some considerations of designing a store / phone app. This post will cover the basics of creating a new Phone / Store app.

Universal App

The new type of application is called a Universal App – so let’s create one:

NewUniversal

I’m going to select a blank app, and create the project. What this gives me is a solution containing three separate projects.

UniversalSolutionExplorer

If I select to run the Windows app I get a blank Windows Store App, and if I select to run the phone app I get a blank phone app. The shared project can be used to create a common application lifecycle, share events and logic. However, the UI is separate (ish – we’ll come back to that in a later post). Let’s start with the Window 8 app

Create the tile image

You can’t update a tile that doesn’t exist; for this example, we’re going to update the wide tile, so you’ll need one. Just create any image 310 x 150 as a png file and point your Windows app at it:

universalmanifest

The app will use a wide tile if it is present on the first install only. If you miss this, then uninstall using the following option:

universaluninstall

Create the tile updater

Next, create another tile image – just copy the first and change the text or draw something on it. Add this to your Windows 8.1 project, and call it test.png (place it under the Assets folder).

The code to update a tile in Windows 8 is as follows:

        private static void UpdateTileImage(string image)
        {
            XmlDocument xmlDoc = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150Image);

            XmlElement imageNode = (XmlElement)xmlDoc.GetElementsByTagName("image")[0];
            imageNode.SetAttribute("src", string.Format("ms-appx://{0}", image));

            Windows.UI.Notifications.TileUpdater tileUpdater = TileUpdateManager.CreateTileUpdaterForApplication();
            TileNotification tileNotification = new TileNotification(xmlDoc);
            tileUpdater.Update(tileNotification);
        }

A little (actually not so little) gotcha is that Live Tiles don’t work in the simulator (http://social.msdn.microsoft.com/Forums/windowsapps/en-US/8357462e-f97b-48c2-8fea-57d47c7ead2a/do-live-tiles-updated-properly-in-the-simulator?forum=toolsforwinapps)

Testing is further complicated because tiles are not automatically pinned to the start menu; so you may deploy and not see your tile. Even worse, I noticed a few times that despite the tile not being on the start screen, on searching for it, Windows claimed it was (so I had to un-pin and re-pin).

Just write the code for Windows

Okay, so let’s just create the tile updater inside Windows 8.1 (this is the code for MainPage.xaml.cs):

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            UpdateTileImage();
        }

        private void UpdateTileImage(string image)
        {
            XmlDocument xmlDoc = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150Image);

            XmlElement imageNode = (XmlElement)xmlDoc.GetElementsByTagName("image")[0];
            imageNode.SetAttribute("src", string.Format("ms-appx://{0}", image));

            Windows.UI.Notifications.TileUpdater tileUpdater = TileUpdateManager.CreateTileUpdaterForApplication();
            TileNotification tileNotification = new TileNotification(xmlDoc);
            tileUpdater.Update(tileNotification);
        }

        public void UpdateTileImage()
        {
            string image = "/Assets/test.png";
            UpdateTileImage(image);
        }

If you need the XAML, it’s here:

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <StackPanel Orientation="Horizontal" Margin="20" Grid.Row="0">
            <TextBlock FontSize="30" Margin="10">Image</TextBlock>            
            <TextBox Text="c:locationimage.png" Margin="10"/>
        </StackPanel>
        
        <StackPanel Orientation="Horizontal" Margin="20" Grid.Row="1">
            <TextBlock FontSize="30" Margin="10">Text</TextBlock>
            <TextBox Text="My Phone Number: 123456 890 12" Margin="10"/>
        </StackPanel>

        <Button Grid.Row="2" Click="Button_Click">Update</Button>

Conclusion

You now have a little program for Windows 8.1 that updates tiles based on a button click. In the next post, we’ll move this into the shared project and call it from the phone app, too. In later posts, I’ll change and refactor the architecture, too.

Windows Tile Updater (Part 1 – design)

A walkthrough of creating a Windows Universal App from scratch

There is a new type of project that allows the creation of Windows 8 and Windows Phone apps. I thought I’d run through creating a simple app (I’m also going to try and publish it in the store).

Design

This seems a little extravagant – a design. Having said that (I believe) you should at least be able to state what your program is intended to do in one or two sentences:

My program will display a tile notification on the start screen that can be defined by the user.

You should also try to decide the answers to the following questions:
1. Will all or part of your app be required to run outside Windows?
2. Do you expect to make money, and if so, how?
3. Does your idea have any competition, and if so, why will anyone look at your idea?

My answers are:
1. No – this is a demo app, so it will be entirely Windows. If the answer is yes then research mono, portable class libraries and Xamarin.
2. No. I may however add some advertising in a later post just to show how it’s done (to make money from advertising, you need very high usage of your app – also, at the time of writing, Microsoft’s fill rate for adverts was a little over 30%).
3. Yes – there are other apps that do this. At the time of writing, I hadn’t spotted an app that shared the tiles between phone and desktop – although I’m confident there will be one. The only reason anyone might choose to use this over another one would be because the source code will be publicly available. You might want a more convincing argument than this for your own work.

So, you’ve decided what the app will do, whether and how it will earn you a fortune, and why people will choose your app over the competition. The next thing is deciding what it will look like. Windows doesn’t leave too much scope for imaginative designs here – it needs to look Metro; having said that, I don’t think I’ve ever had an app fail on appearance.

Here’s my design for Windows:

Win8DT

For Windows Phone:

WP8

And:

TileAppDesign

As you can see, this is a complex and detailed design. Although, from my experience, anything more detailed than this back-of-a-fag-packet screenshot and general concept is a waste at this stage. However, there is one more thing that you should probably do:

Minimum Viable Product (MVP)

You need to decide what you can release with. I think this applies regardless of whether you’re a big company or just some bloke on a train writing software for fun. This should be the absolute least that your application can accomplish and still be your application.

In my case, it’s pretty minimalist as it is, so there’s little point, but you should probably decide the features that are necessary:

– Ability to set text for a tile
– Ability to set image for a tile

Maybe my MVP doesn’t need to include an image – just text? If you release and people download, then add the other features. This is basically a fallback for people who can’t or don’t use a product backlog. It’s essentially the same idea, but it doesn’t come with the overhead of the word agile*.

Conclusion

Now we have a design, in the next post, I’ll post some code.

* My opinion of agile is not that it is an overhead – simply that the word carries a lot of misconceptions and assumptions that may detract from its purpose and primary benefits.

Handling both Touch and Mouse Input with Monogame

I’ve already posted a few times on handling input for Monogame. This one’s a little bit different though, and came from the fact that I had a game trying to get through certification that was repeatedly failing. What I was doing was detecting touch capabilities and, where I found them, using them; otherwise, using keyboard or mouse.

What I ended up doing was handling both. At the time this was just to get the game through certification in the Windows Store; but the more I think about it, the better I think the solution is.

Instead of maintaining a single input contoller, and assigning to it via a factory method, I maintain a list of controllers:

List<IInputController> _inputControllers;

Then, instead of an if / else statement to assign to the controllers, I simply add what’s available:

        // Determine how the user will interface with the game
        private void HandleInput()
        {
            // Instantiate the controllers collection
            if (_inputControllers == null) _inputControllers = new List<IInputController>();
            
            if (_inputControllers.Count == 0)
            {
                // Can we handle touch?  If so, add a new controller to handle touch
                Windows.Devices.Input.TouchCapabilities tc = new Windows.Devices.Input.TouchCapabilities();
                if (tc.TouchPresent == 1)
                {
                    _inputControllers.Add(new TouchController());
                }

                // Can we handle Mouse?  If so, add a new controller to handle mouse
                Windows.Devices.Input.MouseCapabilities mc = new Windows.Devices.Input.MouseCapabilities();
                if (mc.MousePresent == 1)
                {
                    _inputControllers.Add(new MouseController());
                }
            }

So, now we’ve got a list (and it doesn’t have to be restricted to 2 elements if, for example, you suddenly decide to support a thought-power interface http://en.wikipedia.org/wiki/Emotiv_Systems).

On the update method of your game, you now simply iterate through them:

foreach (IInputController inputController in _inputControllers)
{
    inputController.HandleInput();
}

Isn’t it a bit messy having the (potentially) giant conditional statement above

Yes. So, how about this.

            // Determine how the user will interface with the game
            if (_inputControllers == null) _inputControllers = new List<IInputController>();
            
            if (_inputControllers.Count == 0)
            {
                TouchController.AddController(_inputControllers);
                KeyboardController.AddController(_inputControllers);
            }

And then add the AddController function as a static method; like so:

        internal static void AddController(List<IInputController> controllers)
        {
            Windows.Devices.Input.MouseCapabilities mc = new Windows.Devices.Input.MouseCapabilities();
            if (mc.MousePresent == 1)
            {
                controllers.Add(new KeyboardController());
            }

        }

I’m unsure if this qualifies as a “Factory” method as such, although effectively that is what it is.

Conclusion

I’m now quite happy with this approach. I can foresee future uses for the logic, so at some point, if I get time, I might transfer it all to a PCL and publish on Codeplex… assuming I can work out how to get the Windows.Devices namespace to work in a PCL.

Implementing a Review Reminder in a Windows Store C# XAML App

If, like me, you aren’t getting very many reviews for your Windows Store Apps, you might want to give people a nudge. Be careful with this approach, as there’s nothing more irritating than a constantly nagging textbox whining about reviewing an app. Don’t be surprised (or blame me) if you get a review saying: Stop nagging about reviews. But done correctly (in-frequently) you might just persuade a few extra people to review your app.

The process is relatively straightforward; you first need to store two additional roaming setting; mine look like this:

var reviewed = roamingSettings.Values["ReviewedProduct" ];
var lastReminder = roamingSettings.Values["LastReminder" ];

I’m not sure these need any explanation (but I’ll provide one): one to determine whether the product has ever been reviewed and one to say when.

Next, and it’s entirely your choice when but, you need to prompt the user. Having said that, at the start or end of using the app seems a sensible choice; whereas suspending the app mid way and interrupting the user, does not. I do this on load at the same time as reading the other roaming settings:

         protected override void Initialize()
        {
            try
            {
                // Get settings first
                ReadSettings();
                CheckAppReview();

My CheckAppReview function looks like this:

            var reviewed = roamingSettings.Values[ "ReviewedProduct"];

            if (reviewed == null || !Boolean.Parse(reviewed.ToString()))
            {              
                var lastReminder = roamingSettings.Values[ "LastReminder"];

                if (lastReminder == null || DateTime.Now > DateTime.Parse(lastReminder.ToString()).AddDays(5))
                {
                    MessageBoxHelper.MsgBox.ChangeButtonText("Cancel" , "Never ask again");
                    var result = await MessageBoxHelper.MsgBox.ShowAsync("Please would you consider reviewing this application?", "Review Reminder",
                                            MessageBoxButton.YesNo | MessageBoxButton.Cancel);
                    if (result == MessageBoxResult.Yes)
                    {
                        await Helpers. Product.Review();
                        roamingSettings.Values[ "ReviewedProduct"] = true ;
                    }
                    else if (result == MessageBoxResult.No)
                    {
                        roamingSettings.Values[ "LastReminder"] = DateTime.Now.ToString();
                    }
                    else if (result == MessageBoxResult.Cancel)
                    {
                        roamingSettings.Values[ "ReviewedProduct"] = true ;
                    }
                }
            }

The MessageBoxHelper class is the subject of another post, which can be found here.

Obviously this does have its own problems; not the least of which is that it’s pretty difficult to unit test because it uses roamingSettings directly. At some point in the future, I may supplement this with a post on the abstraction of this, but if I don’t, then you definitely should (abstract it that is, not write a blog post – although if you do the latter then send me a link and I’ll amend this post to include it!).

Other problems with it are that the 5 day interval is hard coded and it doesn’t account for the user migrating across a time zone (or even changes their culture) with their profile. So, if any of this matters then be sure not to copy and paste the code verbatim!

Conclusion

You might find this approach to be counter productive. People tend not to want to give reviews, because it means spending time doing something that has nothing to do with the functionality of your app or game. If you’re feeling brave (and I have no idea if this is compliant with the Windows Store Police) you could have certain features that are enabled only after the user agrees to review your app. You could implement that by simply checking the roaming setting:

roamingSettings.Values[ "ReviewedProduct"]

With something like a game, you could give extra credits, or if your app uses any paid features then you could offer to provide them for a limited time period or something.

I imagine this will force people to either review your app or just uninstall it!

Also, keep in mind that once the user agrees to review your app, there’s no way to tell if they’ve actually done so using this approach; nor is there any way to detect they’ve done so via another method.

MessageBox Helper for Windows Store Apps

Believe it or not, the MessageBox.Show() function is unavailable for WinRT. Admittedly, you probably shouldn’t be using it too much. But when you do, it’s unavailable (so you can’t). The workaround is to build up a MessageDialog. Have a go – for a yes / no box, you’re looking at maybe 10 lines of code.

I found an article on the web about creating a helper class; modified it a little, and then felt obliged to re-post.

(Here’s the original article: http://www.reflectionit.nl/Blog/2012/messagebox-show-in-winrt)

What you’ll see if you read that is that he produces a very nice helper class; but what if you want cancel to be called something else (which I did)? Well, here’s my attempt:

         public async Task< MessageBoxResult> ShowAsync(string messageBoxText,
                                                             string caption,
                                                             MessageBoxButton button) {
 
            MessageDialog md = new MessageDialog (messageBoxText, caption);
            MessageBoxResult result = MessageBoxResult .None;
            if (button.HasFlag( MessageBoxButton.OK)) {
                md.Commands.Add( new UICommand(buttonTextMap[ "OK"],
                    new UICommandInvokedHandler((cmd) => result = MessageBoxResult.OK)));
            }
            if (button.HasFlag( MessageBoxButton.Yes)) {
                md.Commands.Add( new UICommand(buttonTextMap[ "Yes"],
                    new UICommandInvokedHandler((cmd) => result = MessageBoxResult.Yes)));
            }
            if (button.HasFlag( MessageBoxButton.No)) {
                md.Commands.Add( new UICommand(buttonTextMap[ "No"],
                    new UICommandInvokedHandler((cmd) =>; result = MessageBoxResult.No)));
            }
            if (button.HasFlag( MessageBoxButton.Cancel)) {
                md.Commands.Add( new UICommand(buttonTextMap[ "Cancel"],
                    new UICommandInvokedHandler((cmd) => result = MessageBoxResult.Cancel)));
                md.CancelCommandIndex = ( uint)md.Commands.Count - 1;
            }
            var op = await md.ShowAsync();
            return result;
        }

The eagle eyed and alert amongst you will notice that this is a carbon copy, with the exception that I’m using a variable called buttonTextMap, instead of using a hard coded string.

Here’s the definition:

         private Dictionary<;string , string > buttonTextMap = new Dictionary> string, string>()
        {
            { "OK", "OK" },
            { "Yes", "Yes" },
            { "No", "No" },
            { "Cancel", "Cancel" }
        };

So far, so… exactly the same. The next section is not really a leap forward in software engineering though:

         public void ChangeButtonText( string button, string newButton)
        {
            buttonTextMap[button] = newButton;
        }

And that’s it. Here’s how I used it:

    MessageBoxHelper.MsgBox.ChangeButtonText("Cancel" , "Never ask again");
    var result = await MessageBoxHelper.MsgBox.ShowAsync("Please would you consider reviewing this application?", "Review Reminder", MessageBoxButton.YesNo | MessageBoxButton.Cancel);

I’ll be posting some more on the context I used it in soon.

Conclusion

What this means it that you can replace the existing buttons with custom named ones, and the code is not as hard to read as building up each option individually.

Thanks to Fons Sonnemans who wrote the original post, on which this is based.

Adding a settings Page to the Windows 8 Settings Charm

I recently completed by second game in Windows 8 (the first using the MonoGame framework). Given the MonoGame architecture, displaying a settings screen seemed a little more complicated than it should have been; obviously displaying this using native Windows controls will mean that I have some re-work should I ever try to port to Android.

This first thing with WIndows is always to hook up the Windows settings charm (don’t confuse this with your own settings page):

        private void AddFlyouts()
        {
            var settingsPane = SettingsPane.GetForCurrentView();           
            settingsPane.CommandsRequested += settingsPane_CommandsRequested;           
        }

This function should be called from the OnLaunched event of you app (for C# apps this is in App.xaml.cs).

Next, create the CommandsRequested event handler, and show the settings screen:

        void settingsPane_CommandsRequested(Windows.UI.ApplicationSettings.SettingsPanesender, Windows.UI.ApplicationSettings.SettingsPaneCommandsRequestedEventArgs args)
        {
             var commandSettings = 
                              new SettingsCommand ("settings" , "Settings" , settingsCommandInvoked);
            args.Request.ApplicationCommands.Add(commandSettings);
        }

And here’s what settingsCommandInvoked looks like:

        private Popup _popUp;
        private const double WIDTH = 646;
        private void settingsCommandInvoked(Windows.UI.Popups.IUICommand command)
        {
            Rect window = Window.Current.Bounds;

            _popUp = new Popup
            {
                Width = WIDTH,
                Height = window.Height,
                IsLightDismissEnabled = true,
                IsOpen = true
            };
            _popUp.Child = new Pages.SettingsPage () 
                              { Width = WIDTH, Height = window.Height };
            _popUp.SetValue( Canvas.LeftProperty, SettingsPane.Edge == SettingsEdgeLocation .Right ? (window.Width - WIDTH) : 0);
            _popUp.SetValue( Canvas.TopProperty, 0);
        }

If you’re just copying this verbatum and now compile that, you’ll discover that you need Pages.SettingsPage. That’s basically a XAML page that actually displays the settings. Mine looks something like this:

< UserControl
    x: Class ="MyApp.Pages.SettingsPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns: x ="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns: d ="http://schemas.microsoft.com/expression/blend/2008"
    xmlns: mc ="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc: Ignorable ="d"
    d: DesignHeight ="300"
    d: DesignWidth ="646">;
    <Border BorderBrush ="#FF590151" BorderThickness ="1">
        < Grid Background ="AliceBlue" VerticalAlignment="Stretch">
            < Grid.RowDefinitions>
                < RowDefinition Height ="80"/>
                < RowDefinition Height ="*"/>
            </ Grid.RowDefinitions>
            < Grid Background ="Aqua" Grid.Row="0">
                < Grid Margin ="40,20,17,13">
                    < Grid.Transitions>
                       < TransitionCollection>
                            < EntranceThemeTransition FromHorizontalOffset ="50" />
                        </ TransitionCollection>;
                    </ Grid.Transitions>
                    < Grid.ColumnDefinitions>
                        < ColumnDefinition Width ="50" />
                        < ColumnDefinition Width ="*" />
                        <; ColumnDefinition />
                    </ Grid.ColumnDefinitions>
                    < Button Click ="Button_Click_1" Margin="0,3,0,0" Grid.Column="0"
                        HorizontalAlignment ="Left" Style ="{ StaticResourceBackButtonStyle}"/>
                    < TextBlock Margin ="10,5,0,0" Grid.Column="1" FontFamily ="Segoe UI"
                        FontWeight ="SemiLight" FontSize ="24.6667" Text="Settings"HorizontalAlignment="Left" />
                    < Image Source ="/Assets/icon.png" HorizontalAlignment="Right"Grid.Column="2" Margin="0,0,6,0" />
                </ Grid>
            </ Grid>
            < Grid Grid.Row ="1" Margin="40,24,23,0" VerticalAlignment ="Top">
               
                < Grid.Transitions>
                    < TransitionCollection>
                        < EntranceThemeTransition FromHorizontalOffset ="120" />
                    </ TransitionCollection>
                </ Grid.Transitions>
                               
                < Button x : Name="MySetting" Foreground ="Black" BorderThickness="1"
                        Click ="MySetting_Click">Do Something</ Button>
               
            </ Grid>
        </ Grid>
    </Border >
</ UserControl>

That should be it. Inside the settings page itself, my suggestion would be that you use a instance of a class defined in App.Xaml.cs, and then use that elsewhere in your app / game to reference the setting. This means that you’re not constantly passing indiviual settings around.

Conclusion

As I said at the start, although this does work, if you’re using a cross platform framework for your game or app then this might not be the best approach; however, you do need to have your settings here if you intend to get into the Windows Store.

Adding Privacy Statement to Windows 8 Store App Built With Monogame

This has been covered many times on the web, but when using Monogame it isn’t as straightforward (not that it’s rocket science).

The key thing is to make sure that when creating the Monogame project, it is created using Monogame and XAML (I’ve blogged about this previously here).

In App.xaml.cs, add the following function to call your privacy statement:

Private async privacyCommandInvoked(Windows.UI.Popups.IUICommand command)
{
    Uri uri = new Uri("http://mypage.com/privacystatement.htm"");
    await Launcher.LaunchUriAsync(uri);
}

As far as I’m aware, it is a requirement of the Win 8 approval process that this be a web site; that is, it can’t simply be a XAML page that displays the text.

Now create a function to add this to the menu, and an event to handle it when it’s selected:

private AddFlyouts()
{
    var settingsPane = SettingsPane.GetForCurrentView();
    settingsPane.CommandsRequested += settingsPane_CommandsRequested;
}

void settingsPane_CommandsRequested(Windows.UI.ApplicationSettings.SettingsPane sender, Windows.UI.ApplicationSettings.SettingsPaneCommandsRequestedEventArgs args)
{
    commandHelp = new SettingsCommand("privacy", "Privacy Policy", privacyCommandInvoked);
    args.Request.ApplicationCommands.Add(commandHelp);
}

You’ll need to change the OnLaunched event to call `AddFlyouts();` and you should be set.  

Remember that this will launch a web browser, so you may need to handle the suspend / resume events to deal with that.

Monogame with XAML – how to use both

Introduction

I haven’t written anything for a while, but I spent a good while on the issue below, so I thought I’d share.

The Problem

I recently starting playing with MonoGame. I’d previously dabbled with using Javascript and HTML5; you can see the results here.

Being predominantly a C# programmer, I decided to try a similar thing using the Monogame framework. When you install Monogame, you’re faced with a box, asking you to either start a Monogame project, or a Monogame with XAML project:

Monogame

So, what’s the difference?

I searched for this on-line, but found more or less nothing; consequently, I thought: what do I need XAML for if I’m writing a game?

And I was right – you don’t… that is, unless you’re using anything later than VS2010 (in which case it allows you to display text without the ridiculous palava that you HAVE to go through otherwise, just to get a FONT into your game.

Having made my decision, I went through this rigmarole, and moved onto the next part of the game: I needed to display a Microsoft Ad Control… which is a XAML control.

So, unless you KNOW that you don’t need XAML… and my guess is that you DON’T, then select XAML & Monogame. You can migrate your code across at a later time though; if you’ve structured your code properly then it may only be a 20 minute job.

Having transferred to use XAML, the question does arise as to how. It’s by no means clear, and I found no documentation at all.

Interacting With XAML / Benefits of having XAML

Annoyingly, I haven’t found any real way to interact with the game graphics from the XAML or vice-versa. It looks like you’d have to keep the instance of the main game page and talk to that from the game logic.

Without this though, you can simply overlay the game graphics on top of the XAML and that seems to work fine. In order to position my ad control I just created the following XAML:


    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="180"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>;        
        <UI:AdControl Grid.Column="0"                      
                      ApplicationId="1234" 
                      AdUnitId="1212" 
                      HorizontalAlignment="Left" 
                      VerticalAlignment="Bottom"
                      Width="160"
                      Height="600"
                      IsAutoRefreshEnabled="True"                      
                      Margin="5"/>
    </Grid>;

Another benefit that I didn’t consider until I moved across is all the resume suspend logic (that is so important in Windows 8 apps).

Conclusion

That’s pretty much all I’ve got to say about this. It’s not an ideal way of doing things, but Monogame is worth using, and it’s free (at least until you want to deploy to Android or something – at which point you pay).