Sunday, September 9, 2018

UWP Tip #23 - Windows Community Toolkit - Microsoft Translator and Bing Services

Welcome back to another UWP Tip focusing on the Windows Community Toolkit.

Services Intro

The Windows Community Toolkit contains a growing collection of services that provide easy access to services from Microsoft and other sources. These are the services available to developers in version 4.0 of the toolkit.

  • Facebook - Login, get data from a user's feed, photos, and more.
  • LinkedIn - Login, get user profile information, share a post to a user's feed.
  • Twitter - Receive tweets, search Twitter, post a new tweet, and more.
  • Bing - Search Bing
  • OneDrive - Login and get file and folder info, manipulate files and more.
  • Microsoft Translator - Translate text between languages supported by the service.
  • Microsoft Graph Service - Login, send messages, get user info from Azure AD, get user events and more.

This post will illustrate how to use the Bing and Microsoft Translator services with some simple examples. The examples wrap the two services in our own application service class which could be used by a UWP app or other Windows application.

Microsoft Translator Service

To use the Translator service, an application key for the service is necessary. Developers can register for a key here.

The TranslateTextAsync async method will take three parameters:

  • sourceLanguage
  • destinationLanguage
  • sourceText

The source and destination languages are passed to the translate method in the form of 'friendly names' of each language. To the the entire list of these names, use the service method TranslatorService.Instance.GetLanguageNamesAsync(). Another option is to attempt detection of the source language with the method TranslatorService.Instance.DetectLanguageAsync(string).

Here is the complete code for our method.

private const string MyTranslatorKey = "<your key here>";
public async Task<string> TranslateTextAsync(string sourceLanguage, string destinationLanguage, string sourceText) {
     await TranslatorService.Instance.InitializeAsync(MyTranslatorKey);
     // Translates the source text to from the specified source language to the destination language.
     return await TranslatorService.Instance.TranslateAsync(sourceText, sourceLanguage, destinationLanguage); }

Bing Service

NOTE: The Bing service has been marked as obsolete as of Windows Community Toolkit 4.0. The team recommends using the Cognitive Services SDK moving forward. That SDK can be found here on GitHub.

The Bing API requires an API key, which can be obtained here. There is a free trial account available. Sign up, select the free options, and get access to up to 5000 queries per month from your applications. Our SearchAsync(string, int) method will create a searchConfig object which will tell the service to search from the U.S. using English language and perform a standard search. A News search type is also available. The method will then perform the search and return the number of BingResult record types specified by the numberofResults parameter.

public async Task<List<BingResult>> SearchAsync(string searchText, int numberOfResults)
{
     if (string.IsNullOrWhiteSpace(searchText))
     {
         return null;
     }
     var searchConfig = new BingSearchConfig
     {
         Country = BingCountry.UnitedStates,
         Language = BingLanguage.English,
         Query = searchText,
         QueryType = BingQueryType.Search
    };
     return await BingService.Instance.RequestAsync(searchConfig, numberOfResults); }

Easy-peasy, right? After the next major release of the Windows Community Toolkit, we will examine how to perform the same types of queries with the Cognitive Services SDK.

Wrap-Up

These are a couple of easy-to-consume services that developers can use today in their applications by simply adding the required Windows Community Toolkit NuGet packages. To check out the complete docs for the available services, visit Microsoft Docs.


Happy coding!


Thursday, August 9, 2018

UWP Tip #22 - Windows Community Toolkit 4.0 Released - DataGrid Is Ready For Your Production Apps

New Release

It's another milestone for the Windows Community Toolkit. Yesterday on the Windows Developer blog, Nikola Metulev announced that the Windows Community Toolkit v4.0 had been released. These are the major changes, according to the release notes on GitHub:
  • DataGrid control is now released out of preview
  • 2 Microsoft Graph controls were added:
  • WebView control enhancements
  • Services (Twitter, LinkedIn, MS Translator) moved Microsoft.Toolkit.Services. Anyone targeting .NET Standard 1.4 can now use these.
  • Twitter service enhanced to include some missing properties from Twitter tweet API
  • Windows Community Toolkit Sample App updated to implement fluent design and a dark theme!
  • Assembly strong naming
  • Dozens of bug fixes in controls, helpers, services and documentation

DataGrid Control

The DataGrid XAML control feel be immediately familiar to any developers who have used the Silverlight DataGrid. This control shares the functionality of the old Silverlight control. In fact, the docs for the DataGrid actually link to the Silverlight DataGrid's API for reference.
As usual, Microsoft's docs are a great place to start. There are eight How-To's for the DataGrid available, so I won't provide my own simple walkthrough here. Instead, let's explore DataGrid in the newly updated Windows Community Toolkit Sample App.
Open the sample app, and select the DataGrid from the Controls menu.
DataGrid01
As you can see, I'm already taking advantage of the addition of the dark theme support in the latest release of sample app.
You'll be presented with a DataGrid control filled with data about mountains. Let's take a minute to thank the developers who worked on the sample app for not providing users with yet another invoicing or inventory set of data.
DataGrid02
Speaking of Themes, did you notice another new feature of the sample app? You can select System, Light or Dark to apply themes to the individual controls displayed within the sample app. How useful!
Just below this, in the header area just above the DataGrid itself, users are able to Filter or Group the grid data with a set of AppBarButton controls. This is the default code for the header:
<StackPanel Orientation="Horizontal" Margin="12">
   <TextBlock Text="DataGrid Sample : Mountains" VerticalAlignment="Center" Margin="5,0" Style="{ThemeResource SubtitleTextBlockStyle}"></TextBlock>
   <AppBarButton Icon="Filter" Label="Filter by">
     <AppBarButton.Flyout>
       <MenuFlyout>
         <MenuFlyoutItem x:Name="rankLow" Text="Rank &lt; 50" />
         <MenuFlyoutItem x:Name="rankHigh" Text="Rank &gt; 50" />
         <MenuFlyoutSeparator />
         <MenuFlyoutItem x:Name="heightLow" Text="Height &lt; 8000ft" />
         <MenuFlyoutItem x:Name="heightHigh" Text="Height &gt; 8000ft" />
       </MenuFlyout>
     </AppBarButton.Flyout>
   </AppBarButton>
   <AppBarButton x:Name="groupButton" Icon="List" Label="Group by" />

</StackPanel>

The code for the DataGrid primarily consists of a number or properties and then a DataGridTextColumn for each column added to the control. Here's that code:
<controls:DataGrid
   Grid.Row="1"
     x:Name="dataGrid"
     Margin="12"
     VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
     HorizontalScrollBarVisibility="Visible"
     VerticalScrollBarVisibility="Visible"
     AlternatingRowBackground="Transparent"
     AlternatingRowForeground="Gray"
     AreRowDetailsFrozen="False"
     AreRowGroupHeadersFrozen="True"
     AutoGenerateColumns="False"
     CanUserSortColumns="False"
     CanUserReorderColumns="True"
     CanUserResizeColumns="True"
     ColumnHeaderHeight="32"
     MaxColumnWidth="400"
     FrozenColumnCount="0"
     GridLinesVisibility="None"
     HeadersVisibility="Column"
     IsReadOnly="False"
     RowDetailsTemplate="{StaticResource RowDetailsTemplate}"
     RowDetailsVisibilityMode="Collapsed"
     SelectionMode="Extended"
     RowGroupHeaderPropertyNameAlternative="Range">
   <controls:DataGrid.Columns>
     <controls:DataGridTextColumn Header="Rank" Binding="{Binding Rank}" Tag="Rank" />
     <controls:DataGridTextColumn Header="Mountain" Binding="{Binding Mountain}" Tag="Mountain" />
     <controls:DataGridTextColumn Header="Height (m)" Binding="{Binding Height_m}" Tag="Height_m" />
     <controls:DataGridTextColumn Header="Range" Binding="{Binding Range}" Tag="Range" />
     <controls:DataGridTextColumn Header="Parent Mountain" Binding="{Binding Parent_mountain}" Tag="Parent_mountain" />
   </controls:DataGrid.Columns>

</controls:DataGrid>

For the purposes of a sample app, everything but the grid data is hard coded. Your app could certainly bind any of these properties that you would like to either load from saved configuration or user preferences.
Let's round out our look at the sample app's code by reviewing the DataTemplate for the row details.
<DataTemplate x:Key="RowDetailsTemplate">
   <StackPanel>
     <TextBlock Margin="20" Text="Here are the details for the selected mountain:" />
     <Grid Margin="20,10" Padding="5">
       <Grid.RowDefinitions>
         <RowDefinition Height="Auto" />
         <RowDefinition Height="Auto" />
         <RowDefinition Height="Auto" />
         <RowDefinition Height="*" />
       </Grid.RowDefinitions>
       <Grid.ColumnDefinitions>
         <ColumnDefinition Width="Auto" />
         <ColumnDefinition Width="Auto" />
       </Grid.ColumnDefinitions>
       <TextBlock Text="Coordinates: " FontWeight="SemiBold" FontSize="13" />
       <TextBlock Grid.Row="1" Text="Prominence (m): " FontWeight="SemiBold" FontSize="13" />
       <TextBlock Grid.Row="2" Text="First Ascent (year): " FontWeight="SemiBold" FontSize="13" />
       <TextBlock Grid.Row="3" Text="No. of ascents: " FontWeight="SemiBold" FontSize="13" />
       <TextBlock Grid.Column="1" FontSize="13" Text="{Binding Coordinates}" HorizontalAlignment="Right" />
       <TextBlock Grid.Row="1" Grid.Column="1" FontSize="13" Text="{Binding Prominence}" HorizontalAlignment="Right" />
       <TextBlock Grid.Row="2" Grid.Column="1" FontSize="13" Text="{Binding First_ascent}" HorizontalAlignment="Right" />
       <TextBlock Grid.Row="3" Grid.Column="1" FontSize="13" Text="{Binding Ascents}" HorizontalAlignment="Right" />
     </Grid>
   </StackPanel>

</DataTemplate>
If a user were to view details on a row, this is how the information would be displayed. The sample app does not appear to currently implement a way to display the RowDetailsTemplate in the UI.

Wrap-Up

Go explore the source code, read the docs and play with the sample app. Then add the DataGrid to your own Windows app! It's a powerful grid control that will save you loads of time.

Happy coding!


Friday, July 27, 2018

UWP App Tips Announcement - Windows UI LIbrary (WinUI)

Big news for Windows developers this week!

On Monday, the Windows Developer team announced the preview release of the Windows UI Library. Windows UI Library, or WinUI, is a set of NuGet packages which contain UWP XAML controls and other features which can be used across different versions of Windows 10. Many of these will be compatible with release from 1607 to the latest Insiders Fast Ring builds.

Windows developers will no longer need to wait for their users to adopt the latest Windows 10 release in order to provide some of the rich features provided by these packages, like Fluent controls.

WinUI preview currently consists of two NuGet packages:

  • Microsoft.UI.Xaml - Contains new and updated XAML controls for UWP applications.
  • Microsoft.UI.Xaml.Core.Direct - Provides access to XamlDirect APIs on versions of Windows 10 that do not yet support these APIs.

Want to get started with WinUI? Here's a quick step-by-step guide to creating a project, adding the NuGet packages, and adding a couple of the new XAML controls to your main Window. Want to add WinUI to an existing UWP project? As long as your project's Minimum version is at least 14393 and Target version is 17134 or later, you can follow the same steps to add the NuGet packages.

First, create your project in Visual Studio 2017 (VS 2015 is not supported).

WinUI01

Next, open the NuGet package management window for your project. Select Browse, and search for Microsoft.UI.Xaml. Be sure to select the "Include prerelease" checkbox next to the search field or you will see no results.

WinUI02

Add the packages you want to use. After adding Microsoft.UI.Xaml, a readme file will open advising you to add the following snippet to your project's App.xaml. Be sure you do this immediately after installing the package.

<Application.Resources>
     <XamlControlsResources xmlns="using:Microsoft.UI.Xaml.Controls"/>
</Application.Resources>

Now you can close your NuGet Package Manager and the readme.txt and App.xaml files. Let's add a couple of new and updated controls to MainPage.xaml. Start by adding a reference to your Page:

xmlns:winUiControls="using:Microsoft.UI.Xaml.Controls"

I've added a few controls to my Page, a TwoPaneView containing a SplitButton in Pane1 and a PersonPicture in Pane2.

<winUiControls:TwoPaneView>
     <winUiControls:TwoPaneView.Pane1>
         <Grid>
             <winUiControls:SplitButton Content="Click or Select" Margin="12"/>
         </Grid>
     </winUiControls:TwoPaneView.Pane1>
     <winUiControls:TwoPaneView.Pane2>
         <Grid>
             <winUiControls:PersonPicture/>
         </Grid>
     </winUiControls:TwoPaneView.Pane2>
</winUiControls:TwoPaneView>

The result is exactly what you would expect for this snippet.

WinUI03

So, what controls are included in the Microsoft.UI.Xaml package? If you open Object Browser, you will currently find a huge list classes under the Microsoft.UI.Xaml.Controls namespace. A few of the new and updated controls include:

  • ColorPicker
  • DropDownButton
  • SplitButton
  • LayoutPanel
  • MenuBar
  • NavigationView
  • ParallaxView
  • RatingControl
  • PersonPicture
  • Repeater
  • Scroller
  • SwipeItem
  • TreeView
  • TwoPaneView

Lots to love for sure. Documentation of the classes in this namespace can be found here, although much of it is currently limited and only labeled as prerelease.

Ready to play? Go check out the Getting Started article on MS Docs and the XAML Controls Gallery code on GitHub! Remember this is currently prerelease code and may undergo some change before it goes RTM.


Happy coding!


Wednesday, June 27, 2018

UWP Tip #21 - File-->New Project with Windows Template Studio 2.2

Windows Template Studio 2.2 was released about two weeks ago. You can view the full list of new features, enhancements and bug fixes on the GitHub repo here. These are a few of the highlights.

You can install the latest version of Windows Template Studio from the Visual Studio Marketplace or in Visual Studio's extension manager.

wts22-00-extension

Let's walk through the new project creation process with Windows Template Studio in Visual Studio 2017. Start with File-->New Project.

wts22-01-newprojwindow

Select the Windows Template Studio (Universal Windows) project type, give your project a name and click OK. Next you'll start with the project wizard.

wts22-02-projtype

Start the wizard by choosing your project type.

  • Navigation Pane
  • Blank
  • Pivot and Tabs

I'm going to select the Navigation Pane type, which gives you a familiar left navigation area with a hamburger menu. Select Next to move on to Design Pattern.

wts22-03-designpattern

Choose your project's design pattern/package.

  • Code Behind
  • MVVM Light
  • MVVM Basic
  • Caliburn.Micro
  • Prism

I usually choose MVVM Light for my sample applications and other simple projects. Today I am going to select Prism to see what is generated by Windows Template Studio for this pattern.

Click Next to move on to selecting what types of pages to include in your application.

wts22-04-pages1

wts22-05-pages2

There are eleven types of pages from which to choose. Select the ones to be included in your project.

  • Blank
  • Settings
  • Web View
  • Media Player
  • Master/Detail
  • Telerik Data Grid
  • Chart
  • Tabbed
  • Map
  • Camera
  • Image Gallery

In addition to the default Main page selected, I've chosen to add a Web View named DewWebViewPage, a Settings page, and a Telerik Grid Page named SharedItemsGridPage.

Click Next again and we'll finish up by selecting some optional features to add to the app.

wts22-06-features1

wts22-07-features2

wts22-08-features3

wts22-09-features4

wts22-10-features5

Version 2.2 now has 17 features to select for your app. Pick the ones that best suit your application's needs and feature set and click Finish to generate your project.

Now that the project has been created, you should see the default UWP welcome screen with some helpful links and your Solution Explorer. I'm going to start by taking a look at what NuGet packages were added for my project.

wts22-11-packages

Based on my wizard selections, I have a handful of packages referenced by my project, including those for Prism.Unity and Telerik.UI.UWP. Your result will vary based on the pattern, pages and features selected for your project.

Next, let's expand a few of the project folders to examine the files created for the project.

wts22-12-solution

You should see a View and corresponding ViewModel for each of the Pages you selected for your app, assuming you did not select the Code Behind pattern. In that case, there will be no ViewModel classes.

The Services and Helpers will also vary from those above based on your feature selections.

In my case, there is a SampleOrder in the Models folder for use with the Data Grid. This will be changed to mirror the actual model to be used in the application's grid. The SampleDataService and its corresponding interface will be used to populate the grid. The WebView also has a service and a service interface for testability.

Run the app and try it out. All of the base navigation functionality is there and works great.

The Main Page

wts22-13-run

The WebView

wts22-14-runwebview

The Data Grid

wts22-15-rungrid

The Settings… let's change to the Dark Theme while we're in here.

wts22-16-runsettings

That's it for the basics. Stay tuned for the next part where we will examine some of the code files and make some tweaks to make it fit your application's requirements.


Happy coding!

Monday, June 4, 2018

UWP Tip #20 - Windows Community Toolkit - Part 16, InfiniteCanvas

Welcome back to my Windows Community Toolkit series, formerly known as the UWP Community Toolkit series (see this post). The previous five tips in the series can be found here:

Intro

The Windows Community Toolkit v3 was a major update for the toolkit. In addition to adding and enhancing many of the extensions, animations, helpers and services, it has added several new controls.

I will examine these new controls over the next several tips in the series. We will circle back to some of the other types of features in the toolkit later. Today, let's start with the InfiniteCanvas.

Using InfiniteCanvas

The new InfiniteCanvas control for UWP applications is a rich, polished and powerful control. Out of the box it supports inking, text entry & formatting, zooming, undo/redo and of course infinite scrolling (hence the name). You can also import and export the InfiniteCanvas contents as json.

Take a look at the InfiniteCanvas running in the latest version of the Windows Community Toolkit Sample App.

UWPTIps-InfiniteCanvas1

Notice that, like other text input controls in UWP apps, the text input in InfiniteCanvas supports spell checking. The toolbar on the control can be toggled on and off with the IsToolbarVisible property. You might want to bind that property so that it is only True when a particular part of your app has focus. Dropping the control into a Grid with the default functionality and a visible toolbar is as simple as:

<Grid>
   <wctk:InfiniteCanvas IsToolbarVisible="True"/> </Grid>

The import/export functionality is performed by calling a pair of methods. ImportFromJson(string json) takes a string containing the data to display on the canvas. ExportAsJson() takes no parameters and returns a string with the json data representing the objects currently on the canvas. Exporting an empty canvas results in a json string with only an empty pair of square brackets.

Zooming bounds can be controlled with the MinZoomFactor and MaxZoomFactor properties. The Min can be set to a System.Double between 0.1 and 1 with a default of 0.25. The Max can be set to a double between 1 and 10 with the default being 4.

The other properties currently available on the control are CanvasHeight and CanvasWidth. These provide access to the size of the drawing surface, rather than the Height and Width of the InfiniteCanvas control itself. Go check out the documentation for a complete listing of the API surface of the control.

Wrap Up

Go check out the source code for InfiniteCanvas, download the latest toolkit NuGet packages, and give it a try in your UWP application today.


Happy coding!


del.icio.us Tags: ,