Development of Windows 8.1 applications on XAML / C #. Part 2. Work with tiles

  • Tutorial
image

We continue to upgrade the application that we created in the last article .

Today we will discuss how to create tiles (Tile) for Windows 8.1 applications and how you can implement the dynamic change of content on them.

Tiles are what you see on the main screen of windows 8 or windows 8.1. These are not just icons. They are interactive. They may contain textual and graphic information about changes in the content of the application, attract the attention of the user and encourage the use of your application more often.

image

Why are tiles so important? Tile is the door to your application, it should be liked by the user and not annoy him. Otherwise, he will unpin it from the start screen and will soon forget about the application.

You can use the following types of tiles for your applications:
  • Large tile (310 x 310 pixels);
  • Medium tile (310 x 150 pixels);
  • Medium tile (150 x 150 pixels);
  • Small tile (30 x 30 pixels).

All of them are presented in the picture below.

image

You can find ready-made tile options and placing information on them in the tile template catalog .

Customize tiles for the application


Use the default settings to create simple tiles.

1. Open the application from the previous article or create a new Windows 8.1 application in Visual Studio 2013.
2. Double-click on package.appxmanifest . The manifest editor window opens.
3. Specify tile information:
  • Select the Visual Assets tab in the manifest editor.
  • Replace the default images in the path to your images.
  • Specify whether to display the short name of the application on the tile.
  • Depending on the background color, choose a light or dark font for the title text.
  • Accept the default background color or specify your own color string.

image

4. Launch the application and experiment with tiles.

image

As you can see, the tiles work and display the prepared images.

Now it's time to add interactivity and learn how to dynamically update the contents of a tile.

Update tile information


There are several ways to implement updating information on a tile:
  • Local update - updating the tile directly during the application itself.
  • At the set time - update the tile at the time you specify.
  • Periodically - update the tiles on a schedule by polling external services to obtain new content.
  • Using Push notifications - updating a tile by sending a notification from external services or systems to our application.

Depending on the tasks and requirements for your application, you can choose one of these options or combine their use.

Now consider each of the options in more detail.

Local tile update

To implement tile updates, directly from the application, we will add an event handler by clicking the Buy button in the product catalog. When you click on the button, the application tile will be updated with information about the selected product.

1. Open the application from the previous article.
2. In Solution Explorer, open the HubPage.xaml file and add a Click event handler for the Buy button and a parameter with the identifier of the ordered product.

image

3. An empty event handler was automatically generated in the HubPage.xaml.cs file . Let's write the following code there:

private void Button_Click(object sender, RoutedEventArgs e)
        {
            string TileXmlString =   ""
                                   + ""
                                   + ""
                                   + "{0}"
                                   + ""
                                   + ""
                                   + "{0}"
                                   + ""
                                   + ""
                                   + "{0}"
                                   + ""
                                   + ""
                                   + "";
            var group = (SampleDataGroup)this.DefaultViewModel["Group1Items"];
            if (group != null && group.Items.Count > 0)
            {
                IEnumerable dataItems = group.Items.Where(item => item.UniqueId == ((Button)sender).CommandParameter);
                if (dataItems != null && dataItems.Count() > 0)
                {
                    XmlDocument tileDOM = new XmlDocument();
                    tileDOM.LoadXml(string.Format(TileXmlString, "Ваш заказ: " + dataItems.FirstOrDefault().Title));
                    TileNotification tile = new TileNotification(tileDOM);
                    TileUpdateManager.CreateTileUpdaterForApplication().Update(tile);
                }
            }
}


To indicate what kind our new tile will be and what will be written on it - we used xml, taken from one of the standard tile templates in the catalog. TileNotification

class - Creates a message object for updating a tile. The update itself is performed by calling the TileUpdateManager.CreateTileUpdaterForApplication (). Update (tile); 4. Now you can launch the application, click on the "buy" button and find the information about the selected product on the tile.





image

Tile update at a given time

It is possible to change the tile not immediately, but after some time.
For example, you can make it change 3 hours after the event. To do this, you can change the Button_Click event handler by adding the following code instead of the last lines:

Int16 dueTimeInHours = 3;
DateTime dueTime = DateTime.Now.AddHours(dueTimeInHours);
ScheduledTileNotification scheduledTile = new ScheduledTileNotification(tileXml, dueTime);
scheduledTile.Id = "Future_Tile";
TileUpdateManager.createTileUpdaterForApplication().AddToSchedule(scheduledTile);


Periodic tile updates

Periodic updates are a great way to deliver tile updates to a large audience of users. This method is a little more difficult to implement and requires a web service on the Internet that implements the logic of creating and transferring tiles to a client Windows application. The web service should return XML content in a specialized format.

Now we will create a REST WCF service that will provide information for updating the tile.

Creating a web service:

1. Open Solution Explorer and select Add New Project in the context menu of the solution .
2. Select WCF Service Application as the project template and give it a name.

image

3. As a result, a web service project was created containing the interface and the web service class itself.
4. Open the Service1.cs file and replace the interface code:
    [ServiceContract]
    public interface IService1
    {
        [WebGet(UriTemplate = "/Tile")]
        [OperationContract]
        XElement GetTile();
    }

5. Rename the Service1.svc file to TileService.svc and replace its code:
    public class TileService : IService1
    {
        private const string TileXmlString = ""
                                  + ""
                                  + ""
                                  + "{0}"
                                  + ""
                                  + ""
                                  + "{0}"
                                  + ""
                                  + ""
                                  + "{0}"
                                  + ""
                                  + ""
                                  + "";
        public XElement GetTile()
        {
            string xml = string.Format(TileXmlString, "Ваш заказ находится в обработке" );
            return XElement.Parse(xml);
        }
    }

With this code, we generate xml in a format that is understandable for tiles.

4. Run the web service project and call the method. The web service should process and return xml.

Setting up a web service call in a Windows application:

1. In Solution Explorer, open Package.appxmanifest and specify the tile update settings:
  • Web service address;
  • The interval to access the service.

image

2. Now you can start the application, wait 30 minutes and see the changes on the tile.

image

You can also call a web service and update tiles programmatically.
This code creates or updates the task of periodically updating a tile from a web service once every half an hour:
var tileupdater = TileUpdateManager.CreateTileUpdaterForApplication();
tileupdater.StartPeriodicUpdate(new Uri("http://localhost:32298/TileService.svc/Tile"), PeriodicUpdateRecurrence.HalfHour);

Attention: the task will be performed even if you remove the tile from the main screen. Most likely, you will need to remove the task of updating the tile for some events, for this you need to run the following code:
var tileupdater = TileUpdateManager.CreateTileUpdaterForApplication();
 tileupdater.StopPeriodicUpdate();

Update tiles using push notifications

Push notifications - perfect for real-time tile updates. For example, an order in a store has changed status or a new message has appeared on the social network.
A push notification requires an external service that will manage the flow of notifications and deliver them to users' client applications using Windows Push Notification Services (WNS) .

We will use the Windows Azure mobile services to create and manage push notifications. You can take advantage of the free trial month of using Windows Azure.

You can configure the Windows Azure mobile service for Windows applications without leaving Visual Studio:

1. Open Solution Explorer. In the context menu of the project, select Add / Push Notification .

image

2. Fill the opened wizard. In the process, you will need to use an existing or create a new Windows Store developer account.

image

3. At the end of the wizard, a mobile service will be created in Windows Azure. We will return to her a little later.

image

4. Pay attention to what happened to the project.
The push.register.cs class was added to the project, which provides interaction with the mobile service.

image

5. In the App.xaml.cs file , in the application launch event, a change was also made.
There, the push notification channel is initialized.
public static Microsoft.WindowsAzure.MobileServices.MobileServiceClient nokiaproductsClient = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient(
        "https://nokiaproducts.azure-mobile.net/",
        "LKcaeBgDWQTEJFiifTiRzhZBdfIkLM35");
//…
protected override async void OnLaunched(LaunchActivatedEventArgs e)
{
//…
  eShop.nokiaproductsPush.UploadChannel();
//…
}

6. Now we need to teach the mobile service to send notifications to the application.
7. To do this, go to the Windows Azure Control Panel (https://manage.windowsazure.com/), then Mobile Services , select the mobile service, go to the Data tab and select the available data transfer channel.

image

8. On the page that opens, click on the Script tab .
9. A JavaScript file will open in which you can write code and generate notifications.

image

10. Edit the file, replacing the code with the following:
function insert(item, user, request) {
    request.execute({
        success: function() {
            request.respond();
            sendNotifications();
        }
    });
function sendNotifications() {
    var channelsTable = tables.getTable('channels');
    channelsTable.read({
        success: function(devices) {
            devices.forEach(function(device) {                              
                push.wns.sendTileWideText04(device.channelUri, {
                    text1: 'Ваш заказ принят'
                }, {
                    success: function(pushResponse) {
                        console.log("Sent tile:", pushResponse);
                    }
                });
            });
        }
    });
}
}

11. Save the script.

image

12. Return to Visual Studio and run the application.

image

The tile will instantly change to what was specified in the script.

So, we learned how to implement dynamically updated tiles for Windows applications in various ways. In future articles, we will continue to comprehend the development of Windows 8.1 applications with simple examples.

You can download the resulting application on SkyDrive at the link: http://sdrv.ms/1gKm4IJ

Useful materials


Creating Tiles
Catalog of ready-made tile templates
Selecting a delivery method for notifications
General information about periodic notifications
General information about push notifications

Also popular now: