Saturday, January 19, 2019

UWP Tip #24 - Get Started Building Windows UI XAML with XAML Studio

XAML Studio was recently made available as a Microsoft Garage project without much fanfare. You may have heard of it if you're a regular viewer of the On .NET show on Channel 9. XAML Studio's creator, Michael Hawker, joined Jeremy Likness to discuss the project last week.

What Is XAML Studio

XAML Studio aims to provide Windows UI developers with a quick way to create and prototype XAML markup for Windows. If you miss old lightweight XAML editors like XamlPad, you should install XAML Studio today. These are a few of the features already available in this early version of the tool.
  • Live Preview
  • Live Binding
  • Binding Debugging
  • Data Context Editor
  • Auto-Save (with Restore)
  • IntelliSense
  • Documentation Toolbox with Links to MS Docs
  • Alignment Guides
  • Namespace Helpers

Getting Started

You can search for XAML Studio in the Microsoft Store and install it from there or use this handy link. When you open the app for the first time, you'll be greeted by a Welcome screen like this.



XAML Editor

If you have an existing WinUI XAML file you would like to try, you can use the Open File link. Let's get started today by clicking the New File link to create and start editing your first XAML file.




The new XAML file is a Windows Page containing a Grid with a 2-line TextBlock. Let's start slow and the Run text of each line a little bit to read "Get Started with XAML Studio on UWP Tips" and "Check out the live preview.". You'll notice that the live preview is exactly that... live. The text in the preview will refresh as you change it in the editor.

IntelliSense and Live Preview

Let's test out the IntelliSense by adding a couple more controls to the page. We'll switch out the Grid for a StackPanel with the default vertical orientation and add a Button and another TextBlock.



Settings

The IntelliSense is quite nice, but I think the default Live Preview refresh interval is a little fast. The bright pink error messages about invalid markup are distracting while working in the editor. You can either disable auto-compilation or edit the interval in the app's settings. The default interval is to compile after 0.8 seconds of inactivity in the editor. I updated mine to 2 seconds.




You should take some time to explore all of the XAML Studio settings as you're getting familiar with the app.

Documentation Toolbox

Something else you should explore is the Documentation Toolbox in the left panel.




Here you can view all of the WinUI XAML controls available to the editor, complete with little info icons that link to the Microsoft Docs online documentation. The control name and namespace appear in the list for each item. If you have controls that you frequently use, you can add them to your favorites so they always appear at the top of the list.

Data Binding

Want to add some dynamic content to your page without coding up your model, view model or connecting to a live data source? You can create a mocked up data source with some JSON data in the Data Source pane on the left.




For this prototype, I grabbed some sample JSON data from one of Adobe's sites. This data contains an array of donuts, each with its own array of batters and toppings and some other properties. It's a handy bit of small, yet semi-complex data.

From the Data Source pane, you can save your JSON, open other JSON data files, or connect to a Remote Data Context. Using a remote data context is as simple as entering a REST Url that returns valid JSON data. The returned data will populate your Data Source window and can be saved for later use.

Here is my XAML markup from the screenshot above with bindings added for the donut JSON data.

<StackPanel Padding="40" DataContext="{Binding}">
     <TextBlock Margin="8">
         <Run FontSize="24" Foreground="#FFFC5185">Get Started with XAML Studio on UWP Tips</Run><LineBreak/>
         <Run>Check out the live preview.</Run>
     </TextBlock>
    <Button Content="I Do Nothing" Margin="8"/>

    <ListView ItemsSource="{Binding}">
         <ListView.ItemTemplate>
             <DataTemplate>
                 <StackPanel Orientation="Horizontal">
                     <TextBlock Text="{Binding Path=id}" Margin="4"/>
                     <TextBlock Text="{Binding Path=type}" Margin="4"/>
                     <TextBlock Text="{Binding Path=name}" Margin="4"/>
                     <TextBlock Text="{Binding Path=rating}" Margin="4"/>
                 </StackPanel>
             </DataTemplate>
         </ListView.ItemTemplate>
     </ListView>
</StackPanel>

These binding expressions are all valid except for one. Want to quickly know which of your bindings is invalid? Switch to the Debug Bindings pane and turn on the Debug toggle.




After debug is enabled on bindings, a list of the binding expressions will display in the pane with a 'Successful' or 'NotBound' status next to the binding target. A timestamp of the last bound time will display with any bindings that have been successful. In addition, the binding expressions in the code editor will be highlighted to indicate their status, making it easier to navigate to the failed bindings.

In my case, I tried to bind to a "rating" property, which does not exist on the donut array items in the JSON data.

Next Steps

That's all we're going to explore in this intro to XAML Studio. Next time we'll dive a little deeper into remote bindings, bind some more complex controls, and see how easily we can take our prototype XAML over to a real UWP application in Visual Studio.

Go check out XAML Studio today and be sure to provide feedback to Michael on Twitter!

Happy XAMLing!

Friday, November 2, 2018

Windows Developer Resource Roundup - November 2018 Edition

I typically leave the link blogging over on the Morning Dew, but I thought my readers here might appreciate a post with a rundown of useful resources for Windows developers.

GitHub Repositories

We'll start off with some GitHub repos that I have starred. The organizations behind each repo are listed in parentheses.

Windows UI Library (Microsoft) - These are the Microsoft UWP XAML controls/styles/materials created for backward compatibility across Windows 10 versions back to the Anniversary Update. As new features are added, you can immediately make them available to your apps across all of these versions of Windows.

Windows Community Toolkit (Windows Community Toolkit) - If you follow my blog, you're very familiar with this toolkit. Formerly known as the UWP Community Toolkit, it now provides a phenomenal set of controls, helpers and services for all Windows developers.

Windows Template Studio (Microsoft) - I've also blogged about this extension on several occasions. WTS provides templates for Visual Studio and a wizard to bootstrap your UWP app with a great foundation built on popular tools and good patterns & practices.

Rapid XAML Toolkit (Microsoft) - This toolkit is a newer community effort spearheaded by Matt Lacey. It is still in preview and aims to accelerate app development for all XAML developers - UWP, WPF, and Xamarin.Forms. I blogged about the toolkit a couple of weeks ago if you would like to learn more.

Fluent XAML Theme Editor (Microsoft) - This is the source code for the Fluent XAML Theme Editor app, now available in the Windows Store. Build your own Fluent theme with light and dark support and use it in your own apps. The app requires Windows SDK version 17763 or higher.

Prism (Prism Library) - Prism is the ultimate framework for XAML developers, with support for WPF, UWP, and Xamarin.Forms. Make your apps more maintainable and testable with simple and robust MVVM, DI, commands and other patterns & tools.

MVVM Light Toolkit (Laurent Bugnion) - MVVM Light offers an alternative to the MVVM framework provided in Prism. It supports UWP, WPF and Xamarin Forms/iOS/Android. This was the first MVVM library I used and it's still a favorite when putting together sample apps.

Documentation

A good framework or toolkit needs great documentation, right? Get the docs here, or contribute to them with your own expertise!

Universal Windows Platform Docs - The Microsoft Docs landing page for all UWP documentation. There are resources to get started, design, develop and publish your apps, as well as a full API reference.

Windows Community Toolkit Docs - The Microsoft Docs home for Windows Community Toolkit docs. Get help with controls or helpers in the toolkit, use get a reference for APIs or contribute to the docs yourself.

Prism Documentation - The official docs for the Prism Library. There are some general guides and sections specific to WPF and Xamarin.Forms.

MVVM Light Documentation - The MVVM Light docs have some samples, walkthroughs, and a link to a fundamentals course on Pluralsight.

Blogs

Keep up with the latest news.

Windows Developer Blog - The official Microsoft blog for the Windows Dev team. Subscribe for updates on SDKs, toolkits, Windows 10 releases and more.

Windows 10 Blog - This blog is the place to get announcements of new Windows features, upcoming events, and releases of new Windows 10 builds (final and Insiders).

The Visual Studio Blog - If you're a Windows developer, there's a pretty good chance you use Visual Studio. Keep up with the latest VS news here.

XAML Brewer - Diederik Krols has some great UWP tutorials on his blog, most recently about improving accessibility in a control.

Official Microsoft Sites

Windows Dev Center - The Microsoft hub for Windows developers. This site has links to all the resources Windows developers need today. Get to docs, tools, SDKs, events, design resources, and register to sell your apps on the Store through the Partner Center dashboard.

Visual Studio App Center - Sign up for the App Center can get continuous integration against your app's repo, test it on actual devices with automation, and deploy to beta testers and production users. You can also get crash reports and analytics with a few API hooks in your app.

Microsoft Design - Get information about the Fluent Design System and start designing and developing your apps with Fluent Design.

Windows Community Toolkit Sample App - Get the sample app to demo the components inside the Windows Community Toolkit.

Visual Studio Marketplace - Windows Template Studio - Download and install WTS from the VS Marketplace. Love the tool? Leave a review!

Other Sites

Prism LIbrary - Prism's home page. It's got links to their docs, learning resources and their Slack channel.

MVVM Light Toolkit - The MVVM Light homepage.

Stack Overflow - Questions tagged "uwp" on Stack Overflow.

@windowsdev - Follow the Windows Developer team on Twitter.

#ifdef WINDOWS - Join Nikola Metulev, Sr. Program Manager for Windows Dev, for a regular video series on Channel 9 where he interviews engineers on the Windows platform.


That's all I have for this first edition. If you have suggestions for future posts, please leave a comment or ping me on Twitter. I plan on posting these semi-annually, but if I get enough suggestions, I may have to create a second edition sooner. Thanks!


Saturday, October 13, 2018

UWP Tips Early Look - Rapid XAML Toolkit (Beta)

Note: The Rapid XAML Toolkit isn't UWP-specific. You can leverage these tools for WPF and Xamarin.Forms development. XAML developers, check it out today!

In today's tip, we will have a peek at a cool project still in early beta stages, the Rapid XAML Toolkit. What is this toolkit? From their readme.md on GitHub:
These tools aim to reduce the time and effort required to get the basics working and allow you to customize the UI to meet your preferences or the specific needs of your app. We can't and don't try to create the whole app for you but we can make creating and working with XAML faster easier.
In short, the toolkit can take a set of properties from a ViewModel in your project and generate XAML controls in your corresponding View.
To give this a try, you will need to download the source and run it in an experimental instance of Visual Studio. Get the full instructions from the getting started guide here. No VSIX file is available yet to run the toolkit in VS itself. That will be coming later. Let's give it a try.
You should have completed these steps from the getting started guide:
  1. Clone or download the Rapid XAML Toolkit solution
  2. Open and build the solution
  3. Run/Debug the toolkit solution in an experimental VS instance
Now, in the newly started instance of Visual Studio, create a new UWP project.

rapid01

You could also open an existing UWP project, if you have one handy. If not, add a new ViewModel, some model classes, and set up your data context, using your favorite MVVM toolkit/method. One other thing you will need to set up is in the Rapid XAML Toolkit settings in your VS options:

rapid02

Select a Profile and click "Set as Active". This will control how your copied ViewModel data is prepared and converted to XAML for your view. Save your settings, return to one of your viewmodel classes and highlight some properties to be copied. Then right-click and select the Rapid XAML menu:

rapid03

You can either copy the converted XAML to your clipboard or send it to your VS Toolbox to be dragged to your view(s). Next, open a view and paste those properties into the XAML editor.

rapid04

For this given ViewModel data that was copied:

public string PatientName { get; private set; }

public int SSN { get; set; }

public DateTimeOffset VisitDate { get; set; }

public string VisitNotes { get; set; }

public decimal CurrentWeight { get; }

public ObservableCollection<Medication> Prescriptions { get; set; }

For reference, this is the Medication model class:

public class Medication
{
     public int Id { get; set; }
     public string Name { get; set; }
     public string UnitOfMeasure { get; set; }
     public double Strength { get; set; }
}

You will have this XAML markup pasted:
<TextBlock Text="{Binding PatientName}" />

<Slider Minimum="0" Maximum="100" x:Name="SSN" Value="{Binding SSN, Mode=TwoWay}" />

<DatePicker Date="{Binding VisitDate, Mode=TwoWay}" />

<TextBox Text="{Binding VisitNotes, Mode=TwoWay}" />

<TextBlock Text="{Binding CurrentWeight}" />

<ListView ItemsSource="{Binding Prescriptions}">
     <ListView.ItemTemplate>
         <DataTemplate x:DataType="model:Medication">
             <StackPanel>
                 <TextBlock Text="{x:Bind Id, Mode=OneWay}" />
                 <TextBlock Text="{x:Bind Name, Mode=OneWay}" />
                 <TextBlock Text="{x:Bind UnitOfMeasure, Mode=OneWay}" />
                 <TextBlock Text="{x:Bind Strength, Mode=OneWay}" />
             </StackPanel>
         </DataTemplate>
     </ListView.ItemTemplate>
</ListView>

I'll grant that it doesn't create the prettiest UI, but it is still an early beta and very little editing is required from this point to create something usable. Here is what the generated view looks like to a user:

rapid05

Keep an eye on this project. I have a feeling it is going to eventually be a big time-saver for Windows devs. If you are the adventurous type, go out and download the beta source today. Have an idea to improve the toolkit? Create an issue on GitHub and start a discussion.

Happy coding!

del.icio.us Tags: ,,

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!