Add App Bar in Windows 8.1 XAML Applications

IC671114

Windows 8.1 simplifies a lot the creation of AppBars. We no longer need to use buttons with a particular style, because now the built-in AppBarButton control is available. The following example shows the main characteristics of the new AppBar:

  <Page.BottomAppBar>
        <CommandBar>
            <CommandBar.PrimaryCommands>
                <!-- These commands appear on the right -->
                <AppBarButton Icon="Play" Label="Play"/>
                <AppBarSeparator />
                <AppBarButton Icon="Add" Label="Add item" />
            </CommandBar.PrimaryCommands>

            <CommandBar.SecondaryCommands>
                <!-- These commands appear on the left -->
                <AppBarButton Label="Edit">
                    <AppBarButton.Icon>
                        <SymbolIcon Symbol="Edit" />
                    </AppBarButton.Icon>
                </AppBarButton>
                <AppBarButton Label="Rss" Icon="Read">
                
                </AppBarButton>
                <AppBarButton Icon="Globe" Label="Website"></AppBarButton>
            </CommandBar.SecondaryCommands>
        </CommandBar>
    </Page.BottomAppBar>

As we can see, everything is simpler. Instead of Grid and StackPanel, we have a CommandBar object that exposes two properties, PrimaryCommands and SecondaryCommands, that respectively contain buttons that appear on the right and on the left of the bar: appbar The AppBar has one more important feature that helps us adhere to UI design guidelines. When screen size gets smaller, Windows 8.1 automatically drops margins and labels to make buttons fit the available space. If this isn’t sufficient, Secondary commands are dropped at all.

In the previous post, we talked about Menus and Flyouts. We can use them with AppBarButton too, because it inherits from Button:

   <AppBarButton Icon="Add" Label="Add item">
    <AppBarButton.Flyout>
        <Flyout>
            <StackPanel Width="406">
                <TextBlock Text="Insert the value and tap the Send button:" FontSize="16"
                   FontWeight="SemiLight" FontFamily="Segoe UI"
                   Margin="0,0,0,10"  />
                <TextBox x:Name="ValueTextBox" />
                <Button Content="Send" HorizontalAlignment="Right"
                    FontSize="16" Margin="0,10,0,0" />
            </StackPanel>
        </Flyout>
    </AppBarButton.Flyout>
</AppBarButton>

appbar2

With the appbar added we now dont need to add extra buttons on the UI thus giving more space to content. It helps users organise the tasks they are doing.

Similarly you can also add a top appbar.

  <Page.TopAppBar>
        <CommandBar>
            <CommandBar.PrimaryCommands>
                <!-- These commands appear on the right -->
                <AppBarButton Icon="Play" Label="Play"/>
                <AppBarSeparator />
                <AppBarButton Icon="Add" Label="Add item">
                    <AppBarButton.Flyout>
                        <Flyout>
                            <StackPanel Width="406">
                                <TextBlock Text="Insert the value and tap the Send button:" FontSize="16"
                   FontWeight="SemiLight" FontFamily="Segoe UI"
                   Margin="0,0,0,10"  />
                                <TextBox x:Name="ValueTextBox" />
                                <Button Content="Send" HorizontalAlignment="Right"
                    FontSize="16" Margin="0,10,0,0" />
                            </StackPanel>
                        </Flyout>
                    </AppBarButton.Flyout>
                </AppBarButton>
            </CommandBar.PrimaryCommands>

            <CommandBar.SecondaryCommands>
                <!-- These commands appear on the left -->
                <AppBarButton Label="Edit">
                    <AppBarButton.Icon>
                        <SymbolIcon Symbol="Edit" />
                    </AppBarButton.Icon>
                </AppBarButton>
                <AppBarButton Label="Rss" Icon="Read">

                </AppBarButton>
                <AppBarButton Icon="Globe" Label="Website"></AppBarButton>
            </CommandBar.SecondaryCommands>
        </CommandBar>
    </Page.TopAppBar>

You can find a list of all default icons here and you can add custom icons as well.

  <AppBarButton Label="Rss">
                        <AppBarButton.Icon>
                            <BitmapIcon UriSource="/Assets/appbar.rss.png" />
                        </AppBarButton.Icon>
                    </AppBarButton>

 

So have  fun and add app bar to your application

Portable Class Library for SQLite Windows 8.1

Microsoft Open Technologies has recently released a Portable Class Library for SQLite. Thanks to it, we can use SQLite in the same way in all the supported platforms.

As a prerequiste you need to have SQLite for Windows 8.1 and then add as a reference to your project. Because it is a native library, the “Any CPU” architecture is not supported, so we need to choose a specific target platform: Visual studio will reference the appropriate extension SDK version the the project compiles.

Adding Reference to the Project

Now we use NuGet to install the portable library to our project.

Portable Sqlite Library

Now everything is ready to start using the library. Suppose for example we want to create a database named data.db with a Users table:

using (var connection = new SQLiteConnection("data.db"))
{
    using (var statement = connection.Prepare(@"CREATE TABLE IF NOT EXISTS Users (
                                                ID INTEGER NOT NULL PRIMARY KEY,
                                                FirstName NVARCHAR(50),
                                                LastName NVARCHUAR(50));"))
    {
        statement.Step();
    }
}

At this moment, SQLite PCL supports only direct SQL commands (no LINQ provider). At line 3, we use the connection.Prepare method to define the DDL query we want to execute. Then, on line 8, with statement.Step, we send the query to the database engine, that immediately executes it.
Now lets insert some data into the table.

using (var statement = connection.Prepare(@"INSERT INTO Users (FirstName, LastName)
                                            VALUES(@firstName, @lastName);"))
{
    statement.Bind("@firstName", "Rahber");
    statement.Bind("@lastName", "Ashraf");

    // Inserts data.
    statement.Step();

    // Resets the statement, to that it can be used again (with different parameters).
    statement.Reset();
    statement.ClearBindings();

    statement.Bind("@firstName", "Some User first name");
    statement.Bind("@lastName", "Some user last name");

    // Inserts data.
    statement.Step();
}

Again, the Prepare method is used to define the SQL command. In this case, it is an INSERT in which we have defined two parameters, @firstName and @lastName. At line 4-5, we bind them to their actual values, using the Bind method. The Step command (line 8) finalizes the operation.

And to retrieve the data we use the following code.

using (var statement = connection.Prepare(@"SELECT * FROM Users ORDER BY FirstName;"))
{
    while (statement.Step() == SQLiteResult.ROW)
    {
        var id = (long)statement[0];
        var firstName = (string)statement[1];
        var lastName = (string)statement[2];
    }
}

To read the records returned by the query, we need to iterate through the rows, in a way that resembles the SqlDataReader.Read method.

In order to retrieve the actual values, we need to use the indexer operator on the statement object, specifying the column number. As this method gets a result of Object type, we need to cast it to the real type of the column. If we want to avoid this syntax, and instead prefer to use generics, we can define a simple extension method:

public static class SQLitePCLExtensions
{
    public static T GetValue(this ISQLiteStatement statement, int index)
    {
        return (T)statement[index];
    }
}
And Finally now you can use the library easy 

NFC to have a Skype call with Windows 8.1

Check this blog if you want to rich your application with the availability to have a skype call with your friends from your app just using your NFC

ProximityDevice has made life easier to publish content that can be received by other NFC readable devices.
We can publish a uri to tag, we can publish a http:// protocol and it will launch the web link in the browser. So we can publish the uri to skype call.

  1. privatevoidWriteSkypeTag(string skypeUsername)
  2. {
  3. var device =ProximityDevice.GetDefault();
  4. if(device !=null)
  5. {
  6. using(var writer =newDataWriter{UnicodeEncoding=UnicodeEncoding.Utf16LE})
  7. {
  8. // Prepare the message to be published.
  9. var uri =string.Format(“skype:{0}?call”, skypeUsername);
  10. writer.WriteString(uri);
  11. var buffer = writer.DetachBuffer();
  12.  
  13. // Publish the message. You must tap an NFC tag to your device to write
  14. // the content to it.
  15. device.PublishBinaryMessage(“WindowsUri:WriteTag”, buffer,
  16. async (sender, messageId)=&gt;
  17. {
  18. device.StopPublishingMessage(messageId);
  19.  
  20. await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async ()=&gt;
  21. {
  22. var message =newMessageDialog
  23. (“The Skype contact has been written to the tag.”);
  24. await message.ShowAsync();
  25. });
  26. });
  27. }
  28. }
  29. }

We used the skype uri to create the link, for example the uri is skype:amrsader? call so this will open the skype and call the contact which is amrsaderin this case then using the WindowsUri:WriteTag we specified that its a uri can only be transmitted to a tag. Now we only need to tap the tag to the device and it will work.

real time progress bar for downloading in Windows 8.1

In this blog post I am going to show how to use Background Transfer feature to download files over HTTP in a Windows Store C#/XAML app. Background Transfer has many advantages over using traditionl HttpClient and is much better for long running transfers. I am going to create a simple app, that initiates download over the Internet, tracks progress of the download and supports re-attaching transfers after the app is closed.

So first of all i am going to create a new Project.

I will go to MainPage.xaml and will create a progress bar and Download button.

 

 

So now i will write its csharp code

  1. usingSystem;
  2. usingSystem.Collections.Generic;
  3. usingSystem.IO;
  4. usingSystem.Linq;
  5. usingSystem.Runtime.InteropServices.WindowsRuntime;
  6. usingSystem.Threading.Tasks;
  7. usingWindows.Foundation;
  8. usingWindows.Foundation.Collections;
  9. usingWindows.Networking.BackgroundTransfer;
  10. usingWindows.Storage;
  11. usingWindows.UI.Popups;
  12. usingWindows.UI.Xaml;
  13. usingWindows.UI.Xaml.Controls;
  14. usingWindows.UI.Xaml.Controls.Primitives;
  15. usingWindows.UI.Xaml.Data;
  16. usingWindows.UI.Xaml.Input;
  17. usingWindows.UI.Xaml.Media;
  18. usingWindows.UI.Xaml.Navigation;
  19.  
  20. // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
  21.  
  22. namespaceApp1
  23. {
  24. ///
  25.  
  26. /// An empty page that can be used on its own or navigated to within a Frame.
  27. ///
  28. publicsealedpartialclassMainPage:Page{
  29.  
  30. privateDownloadOperation _activeDownload;
  31.  
  32. private async voidDownloadClick(object sender,RoutedEventArgs e)
  33. {
  34. conststring fileLocation
  35. =http://www.microsoft.com/global/surface/en/us/renderingassets/surfacespecsheet.pdf&#8221;;
  36. var uri =newUri(fileLocation);
  37. var downloader =newBackgroundDownloader();
  38. StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(“FileName.pdf”,
  39. CreationCollisionOption.ReplaceExisting);
  40. DownloadOperation download = downloader.CreateDownload(uri, file);
  41. await StartDownloadAsync(download);
  42. }
  43.  
  44. privatevoidProgressCallback(DownloadOperation obj)
  45. {
  46. double progress
  47. =((double)obj.Progress.BytesReceived/ obj.Progress.TotalBytesToReceive);
  48. DownloadProgress.Value= progress *100;
  49. if(progress >=1.0)
  50. {
  51. _activeDownload =null;
  52. DownloadButton.IsEnabled=true;
  53. }
  54. }
  55.  
  56. private async TaskStartDownloadAsync(DownloadOperation downloadOperation)
  57. {
  58. DownloadButton.IsEnabled=false;
  59. _activeDownload = downloadOperation;
  60. var progress =newProgress<DownloadOperation>(ProgressCallback);
  61. await downloadOperation.StartAsync().AsTask(progress);
  62. }
  63.  
  64.  
  65. }
  66.  

First of all we need to obtain StorageFile (or more precisely IStorageFile implementation) – in our scenario we use ApplicationData.Current.LocalFolder.CreateFileAsync() to create a file in local app data store. Please note that we use async/await pattern, hence the event handling method is marked as async. We also need to create BackgroundDownloader class instance that is used to actually create new download using CreateDownload() method.

Every download created using Background Tranfser feature is encapsulated in DownloadOperation object. These objects provide basic operations used to manipulate the download. In example above we start the download using StartAsync() that returns IAsyncOperationWithProgress. We make use of AsTask() extension method to cast the returned value to Task and provide progress callback used to update ProgressBar control.

 

Download Progress

  1. async voidMainPageLoaded(object sender,RoutedEventArgs e)
  2. {
  3. await LoadActiveDownloadsAsync();
  4. }
  5. private async TaskLoadActiveDownloadsAsync()
  6. {
  7. IReadOnlyList<DownloadOperation> downloads =null;
  8. downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();
  9. if(downloads.Count>0)
  10. {
  11. //for simplicity we support only one download
  12. await ResumeDownloadAsync(downloads.First());
  13. }
  14. }
  1. private async TaskResumeDownloadAsync(DownloadOperation downloadOperation)
  2. {
  3. DownloadButton.IsEnabled=false;
  4. _activeDownload = downloadOperation;
  5. var progress =newProgress<DownloadOperation>(ProgressCallback);
  6. await downloadOperation.AttachAsync().AsTask(progress);
  7. }

Once we have this code in place our download will reattach every time we load the page. For simplicity we support only one active download.

Using Windows 8.1 SettingsFlyout control

Despite its name, the new SettingsFlyout control that comes with Windows 8.1 can be used as a normal flyout, like the one that is used, for example, by the official Twitter app for Windows Store:

setting flyout

If you want to show it independently you can use the following code.

  1. privatevoidButton_Click(object sender,RoutedEventArgs e)
  2. {
  3. var flyout =newMyFlyout{Width=646};
  4. // Opens the Settings flyout, and returns the user to the app
  5. // after the flyout is dismissed.
  6. flyout.ShowIndependent();

Thanks