Windows Apportals – Developers Training

Course Edition 1.0 (Pilot)

Disclaimer: TEKsystems obtained written permission from Inviso to use the following copyrighted materials: ______Trademark

Inviso or TEKsystems. All rights reserved. No part of this book may be reproduced or transmitted in any form or by an means—electronic, mechanical,, photocopying, recording, or otherwise—without the prior written permission of Inviso or TEKsystems

Windows Apportal – Developer Training | 1

Table of Contents Table of Contents ...... 2 About the Course ...... 3 Audience ...... 3 Chapter One: Introduction to the Windows Apportal ...... 4 What is a Windows Apportal? ...... 4 Windows 8.1 Application ...... 4 Why Windows Apportals? ...... 5 Portal Content Structure ...... 5 Windows Apportals in the Enterprise ...... 5 Anatomy of an Apportal ...... 6 Hubs, Groups, and Tiles ...... 7 Navigation ...... 8 Report View Types ...... 9 Drill Up and Drill Down ...... 11 Other View Considerations ...... 13 Chapter Two: Building an Apportal ...... 15 In This Chapter ...... 15 Hub and Groups ...... 16 Tiles and Tile Sets ...... 23 Appendix A: Resource Files ...... 27 Appendix B: Global Filters ...... 28 Appendix C: Offline ...... 31 Offline Challenges ...... 31 Loading Data into Memory ...... 32 Downloading ...... 33 Filters Persistence...... 33 HTTPHandler ...... 35

Windows Apportal – Developer Training | 2

About the Course

Audience Commented [HC1]:

1) Introductions Whether you’re an established professional or new to the field, this training will give you 2) This is a Pilot. the guidance you need to develop a fully functional Windows Apportal. Built on top of Windows 8.1, Windows Apportals organize and reveal data and apps needed for a 3) You are qualified, and a big part of making this successful – orient specific role or task. them to the resource files and feedback document.

4) Standard schedule and logistics discussion To get the most out of this course, it is highly recommended that you have a practical understanding of the following technologies:

 Familiarity with developing Windows 8.1 applications  C#  XAML for Windows 8.1 (or previous experience in any of the XAML-based frameworks)  Using the MVVM Pattern in Windows 8.1  Familiarity with Visual Studio, WCF Data Services, and Active Directory is recommended

A Developer account is required for developing and publishing Windows 8.1 applications.

Windows Apportal – Developer Training | 3

Chapter One: Introduction to the Windows Apportal

What is a Windows Apportal?

A Windows Apportal is a Windows 8.1 application that mimics the Windows 8.1 Start screen presentation of tiles (which are rectangles of various sizes) that display information (such as icons, images, or data) and perform an action when clicked or tapped.

Built on Microsoft technologies, third-party tools, and code that aggregate data from diverse sources, an Apportal is a tailored application that runs in Windows 8.1 (that is the ”app” portion of the name). The concept of specific control of presented data is very similar to that of an Intranet Portal (that is the “portal” portion of the name).

Windows 8.1 Application

An Apportal interface looks and feels very much like the Windows 8.1 Start screen, which is exactly the point—the hub screen of an Apportal is a single application presenting its data in the familiar groups and tiles of Windows 8.1.

Similarities to Windows 8.1 Start screen and tile behaviors include the following:

1. Apportal tiles can display hierarchical data in a navigable dashboard. 2. Tiles can launch native Windows applications like Outlook, Notepad, and Control Panel. 3. Tiles can open URI targets using a browser (e.g., Dynamics CRM Online). 4. Rotating data points can be displayed on the tile, or the tile can display a picture or another media file.

The Apportal tiles also have behaviors that are different than those in the Windows 8.1 Start screen:

1. Tiles in the Apportal are not user-configurable in any way (such as size, position, style, or data displayed). The size and position of a tile within an Apportal is created by the code. Users cannot add or remove tiles.

2. The size of Apportal tiles are static, and will not change based on the screen resolution or window size. For this training class, the examples show a grid size that is optimized to fit well on most monitors, and will not adjust dynamically. One of the goals of ongoing development is greater flexibility of tile sizing, placement, and user adjustment.

A. The distance between groups is 80 pixels (MSFT standard). B. The distance between tiles is 5 pixels (MSFT standard). C. 3x2 rows/columns of tiles within groups are based on the MEDIUM Windows 8.1 tile size.

Windows Apportal – Developer Training | 4

D. 6x4 rows/columns of tiles within groups are based on the SMALL Windows 8.1 tile size.

Why Windows Apportals?

Windows Apportals address a long-missed insight in professional organizations: businesses use software from many vendors. Windows Apportals were built in response to numerous requests to create an “on the glass” integration for the wide variety of heterogeneous LOB apps in organizations today. Those applications include legacy Windows 7 desktop applications, newer Windows 8 Modern apps, and web applications.

Enterprise IT professionals began realizing the variety of apps, applications, and services in an organization require a loosely coupled structure. In today’s diverse work environments, a single, monolithic application is not realistic or desired. Windows 8.1 OS gives businesses the flexibility to create a UI-based virtual integration, and continue to gain value from existing legacy technology investments.

Windows Apportals are the solution to this need.

Portal Content Structure

As companies compile financial, sales, product, and other types of data, that data needs organization, structure, and logical presentation in order to be useful. Familiar presentation methods include Intranet portals, application dashboards (Excel, Salesforce, Dynamics CRM, etc.), and printed reports. An Apportal provides a dashboard-like set of behaviors with a Windows 8.1 Start screen look-and-feel.

The heart of an Apportal is the presentation of hierarchical data from a data set, arranged beginning with a single tile at the top level. As this tile is clicked or tapped, lower layers in the branch show the graph, grid, or list view details further down. The presentation of these branches of the data set is done through tile sets.

Data Sets

In an Apportal, a data set contains the data needed to support one or more tile sets, and, typically, resides in a database. Tile sets can display the entire data set or subsets of the dataset determined by a query. These query results can be further filtered as users navigate the data within the Apportal (regional sales within monthly sales data, for example).

Windows Apportals in the Enterprise

[Examples of why, how, and when an Apportal is/can be/has been used] Commented [HC2]: Show Online Apportal constructor (demo) if it is available (seems to be gone). Otherwise, outline Marketing, Sales – the first Apportal was for MSFT Sales.

Windows Apportal – Developer Training | 5

Anatomy of an Apportal

This section goes into further detail on the terms and concepts of how data is presented and navigated by a user within the Apportal interface.

Interface terms and concepts include: - Hub, groups, and tiles - Report views - Drill up, drill down, and deep linking - Filter controls - Navigation controls (such as pinned apps in the app bar, Back button, etc.)

Windows Apportal – Developer Training | 6

Hubs, Groups, and Tiles Commented [HC3]: Refer to the Contoso Apportal sample. Follow the content outline for the Hub, Group, Tiles. Hub View The main view of an Apportal is the Hub View, which consists of groups of tiles. The Hub View functions as a home page of sorts. The Hub View provides the look and feel, and some of the functionality of the Windows 8.1 Start screen in a format tailored for a company's unique needs. Font styles, logos, tile groups, and backgrounds are completely customizable. Each tile connects to and displays information from sources such as a CRM system, Internet pages, other applications, and data sources.

Groups As with the Windows 8.1 Start screen, tiles that have related functionality in the Apportal are arranged in groups. Each group has a heading and associated tiles. Tiles Each Apportal tile is one of three display types: Static, Live, and Snap View.  Static tiles display a static image/logo.  Live display a rotating list of data or images, a video, graph reports, or grid reports.  Snap View tiles are static and, when clicked or tapped, they open external applications such as , Lync, or Outlook in a filled view while the content of the tile moves to a Snap View.

Static and live tiles, when clicked or tapped, can navigate to another (deeper or more detailed) view within the Windows Apportal (such as a graph report view or grid report view).

Each snap view tile has an associated URI. The URI identifies which external application to open via a URI type and file extension that is mapped to applications by the operating system.

For example, if the URI begins with http:// the operating system will attempt to open a browser in the filled view. Windows 8.1 applications can be launched with a URI beginning with the applications name (e.g., skype:/// will launch Skype) An application must register to become the default handler for a certain URI scheme name. This is called Protocol Activation.

Windows Apportal – Developer Training | 7

Tile Sets A tile set is a set of report views that are represented by a single tile on the hub. The tile that visually represents the top level of the tile set is the navigation starting point for one or more associated report views based on a branch of the global data set. In the following example, the live tile on the Hub View presents a subset of the data in a minimal mode and provides an indication of the underlying data. The lower-level report views include a dynamic graph and a grid.

Navigation

The core functionality of an Apportal is to present data in an appropriately navigable format to the user. While native and URI-launched applications may be included as part of a business portal, the ability to view and navigate data is the primary driver for creating an Apportal.

An Apportal tile set presents one report view at each level. A user clicks or taps to move up or down through the designed pattern of navigation.

Windows Apportal – Developer Training | 8

Report View Types A report view is a specific format used to render data in a meaningful and useful way for the user. Some examples of report views include lists, graphs, and grids. Practically, any type of reporting control can be used. List Report View List report views display one or more data points in a simple list. One use for a list view is to display a small set of data points on a live tile.

Graph Report View Graph views organize data in a chart-style format. Graphs can be dynamic; for example, users could drill down by clicking a specific segment in a stacked bar chart, or users could drill up by clicking the Back button. The following are three examples of bar charts presented in a graph view. Stacked

Horizontal

Windows Apportal – Developer Training | 9

Waterfall

Grid Report View The grid report view organizes data into rows and columns. Grid controls can provide many useful features for the user, such as grouping, ordering, searching, and row or column selection.

Windows Apportal – Developer Training | 10

Drill Up and Drill Down Commented [HC4]: Select drill down for regional sales data

To support the drill-up and drill-down capabilities, a hierarchy of business data domains must exist. An example of a typical data domain hierarchy is geography. A geographical hierarchy could consist of multiple data domains such as region, district, and Account Team Unit (ATU), with the sales territory as the lowest level of pertinent business data in the hierarchy. In graph views, users drill through the levels of a domain hierarchy. This special domain hierarchy is also a part of the global filters. Thus, drilling up or down is equivalent to manually changing a global filter for that domain hierarchy. This special domain hierarchy is also referred to as the drill-down filters. An Apportal can support only a single data domain hierarchy for drilling up and down.

If the underlying data source is built on a hierarchy such as the geographic breakdown of sales territories from region to sales territory, this hierarchy can support an Apportal that includes the capability to drill down or up, moving between the levels of a hierarchy. A user can drill up or down using two methods: (1) by changing the global filters, or (2) by selecting segments within a graph to drill down and by selecting the Back button to drill up. The global filters work in tandem with drilling up and down within a graph or a grid. Changing one changes the other.

Providing these two methods gives the user two ways to analyze data. Global filters can be used when a user wants to see a specific data point and knows where it resides in the hierarchy; for example, the current quarter's sales for one sales territory. Moving within a graph can be used when a user wants an overall view or does not know where the data point resides. For example, looking to find which regions, districts, and sales territories have the greatest sales YTD. Drill Down The following example shows a stacked graph view. The underlying geographic hierarchy is this: United States (all), region, district, ATU, and sales territory.

The user selects the East region segment and the Apportal drills down to show the districts within that region.

Windows Apportal – Developer Training | 11

Drill Up Drilling up moves the data back up the hierarchy. In this example, the left arrow is used as the drill up button and moves the grid view up one level in the hierarchy. When the top level of the graph is reached, the function of the left arrow becomes the Back button.

Windows Apportal – Developer Training | 12

Other View Considerations

Filters Local filters set parameters for limiting displayed data only to the data that the user wants to see. Filters apply to any chart view or detail table to further segment the results. These filters are tile-specific, so the options that are available will vary between tile sets. Local filters apply only to the components of a single tile set (for example, a tile set with a live tile, a graph tile, and a grid tile.) Applying a filter immediately updates the data in the view, and applies to all views within the tile set. Snap View Snap View is a Windows 8.1 multitasking feature that supports the use of multiple windows that are open at once. This mode enables side-by-side access from within the Apportal into existing systems and external resources. When you select a Snap View tile, it can open the Internet Explorer Modern UI within the Apportal. You will see Apportal visible in the left window and the resource you have selected in the right window. You are now free to use the tool or resource in the right window as you normally would. After using your resource, you can return to the full- screen Apportal by dragging or swiping the Snap View divider to the right. Deep Link Grids can be configured to open a Snap View when specific data is clicked in the grid. For example, if the grid contains data from a CRM application, the user can select an opportunity ID and the Apportal will open the CRM application in a browser at that specific opportunity instead of landing on the home page of the CRM application. This is a deep link. In this example, when the browser opens to show the details for a selected opportunity, the full grid reconfigures to show a subset of the grid to one side—for instance, the opportunity ID, company name, forecast type, and forecasted revenue. The grid remains active and the user can scroll to another opportunity. Click that row, and the browser will show the newly selected opportunity. To return to the full grid, the user closes the browser window.

Role-Based Views Commented [HC5]: Point out the Role-based selection in the Powered by Active Directory, an Apportal provides the ability to filter, share, and display demo is artificial – if this had been a real demo, the role is already set at logon. information based on a role. The user experience changes based on the role of the currently logged-in user. This may include showing, hiding, or reorganizing tiles; configuring default settings; or pre-applying filters. For example, the views and data presented could be based on the user's job level. In one scenario, an Apportal grants executives (who are members of a specific Active Directory Security Group) access to a tile that displays sensitive data. Members of all other security groups will not see that tile. In the following example, the user's role determines which data is displayed. When an Apportal is launched, a "GetUserRole" method in the service layer is called to determine the user's role and access. Inside that method, the service will check the user’s access against Active Directory and return the user role object to the client

Windows Apportal – Developer Training | 13

application. The Apportal inspects the user role object to determine which tiles the user can view along with other role-specific customizations.

Constrained Delegation A common authorization need is to restrict users' access to data at the row level. Often, authorization rules are embedded in Microsoft SQL Server to accomplish this. In these circumstances, each user's account is granted specific rights within the database. When connecting to data sources configured in this way, a service layer must impersonate the user's account to access data on behalf of the user (because Windows 8.1 applications cannot directly connect to databases).

This creates an authentication double-hop situation. By default, Active Directory will not allow double-hop authentication. To overcome this restriction, the service layer must be granted special permission within Active Directory to impersonate a user when connecting to a remote server (i.e., SQL Server). This is called constrained delegation (CD). When CD is enabled, the service can query the data source on behalf of the user and then pass the data on to the client.

Windows Apportal – Developer Training | 14

Chapter Two: Building an Apportal

In This Chapter It is outside the scope of this course to cover common techniques and well-documented best practices for building Windows 8.1 applications.

This chapter contains the lessons learned when building various types of Apportals, and how goals and objectives were achieved with specific coding techniques.

As each client’s requirements, business, and infrastructure differ, so does each Apportal created for them. As Apportals continue to mature in the marketplace, this course will be adjusted to include the newest lessons learned.

For efficiency, since no one Apportal contains all the possible implementations, the code examples are not printed here, but are provided as digital files for reference and discussion during the course. Details about these files are provided in Appendix A.

Each section of the chapter contains a similar structure: User Experience Goals Developer Objectives Best Practices

Sections in this chapter: Hub and Groups Tiles and Tile Sets Offline

Windows Apportal – Developer Training | 15

Hub and Groups

General Apportal hub and group lessons learned are included in this section.

User Experience Goals

The Apportal application is responsive and intuitive. Group and tile positions are reliable and consistent by role. Developer Objectives

Optimize Apportal functions, data management, and time to develop Logging and data analytics (for exceptions and app usage). Best Practices

XAML/MVVM technologies—XAML is one of the most productive UI platforms in Commented [HC6]: MVVM discussion and demonstration flow existence. For a long time, XAML has had its roots in WPF Desktop Applications, Silverlight, Windows Phone, Windows Embedded, and now Windows 8.1 Store Apps. When paired with MVVM design patterns, applications really start to shine. It can simplify testing, and reduce lines of code as well as the number of bugs, all while keeping up with productivity demands.

Many rich features in XAML are incomparable with other platforms. For example, bindings alone have been greatly beneficial when rendering data along with designs. Even with data being dynamic, XAML has the tools to adjust accordingly so the design is always consistent, even when the underlying data isn’t.

When implementing the MVVM pattern, there is a separation between the view (the XAML code coupled with its code-behind), the ViewModel, and the model. Typically, users should try to develop the ViewModel so that it doesn’t know anything about the view that it drives. This has multiple advantages: the developer team can work independently from the UI team; the ViewModel can be unit-tested easily, simply by calling some commands and methods and asserting the value of properties; and changes can be made to the view without having to worry about affecting the ViewModel and the model.

However, MVVM does have some limitations. For instance, a simple data binding cannot trigger an animation on the UI or cause a dialog to be shown to the user. Simple data binding cannot cause even actions, such as navigation to a different page. The MVVM Light Toolkit has a number of predefined message classes available in the GalaSoft.MvvmLight.Messaging namespace that can address this problem. Any type of message can be sent, and it is very easy to define your own messages. The messaging class is an implementation of an event bus, a decoupled eventing system in which the sender of the event (or message) and the recipient don’t have any knowledge of each

Windows Apportal – Developer Training | 16

other. The application can choose to show status messages to the user without worrying about dependencies.

Windows Apportal – Developer Training | 17

Async/Await—The most recent addition to the C# programming stack is the Commented [HC7]: Async / Await discussion and Async/Await functionality. Traditionally, a lot of time has been spent trying to make demonstration flow. applications asynchronous to allow the UI to update while a long-running operation is occurring. This has required making state managers, callbacks, etc. With Async/Await, the same functionality can be achieved with one line of code. Something similar exists in the HTML5/JavaScript Windows 8.1 app called Promises, but it still takes at least a few lines of code to implement, rather than a single line.

Windows Apportal – Developer Training | 18

WCF Data Services—To expose the data from a WCF Service, a developer must Commented [HC8]: WCF Data Services content and discussion develop a service contract, develop a contract implementation, write business objects to flow expose the data for the client, configure communication binding settings, and add configuration in the Web.config file. Developing a middle tier service with WCF Data Services reduces this complexity and enables more rapid delivery. WCF Data Services supports Open Data Protocol to expose data represented by Entity Data Model via Web Services.

Windows Apportal – Developer Training | 19

LINQ—Language-Integrated Query (LINQ) is an innovation introduced in Visual Studio Commented [HC9]: LINQ content and discussion flow 2008 and .NET Framework version 3.5 that bridges the gap between the world of objects and the world of data. Traditionally, queries against data are expressed as simple strings without type checking at compile time or using IntelliSense support. Furthermore, you have to learn a different query language for each type of data source such as SQL databases, XML documents, and various web services. LINQ makes a query a first-class language construct in C# and . You write queries against strongly typed collections of objects by using language keywords and familiar operators.

Windows Apportal – Developer Training | 20

Expression Trees—Expression trees represent code in a tree-like data structure, Commented [HC10]: Expression Trees content and discussion where each node is an expression; for example, a method call or a binary operation flow such as x < y. You can compile and run code represented by expression trees. This enables dynamic modification of executable code, the execution of LINQ queries in various databases, and the creation of dynamic queries. For more information about expression trees in LINQ, see How to: Use Expression Trees to Build Dynamic Queries (C# and Visual Basic). Expression trees are also used in the (DLR) to provide interoperability between dynamic languages and the .NET Framework and to enable compiler writers to emit expression trees instead of Microsoft intermediate language (MSIL). For more information about the DLR, see Dynamic Language Runtime Overview. You can have the C# or Visual Basic compiler create an expression tree for you based on an anonymous lambda expression, or you can create expression trees manually by using the System.Linq.Expressions namespace.

Windows Apportal – Developer Training | 21

Monitoring and Analysis—An Apportal captures metrics about data download Commented [HC11]: Still need a log file example flow for this. performance and writes application errors to a local log file. Additional metrics about client usage can be captured through the use of Microsoft Application Insights. The data can be used to make business decisions.

An Apportal can continuously log user actions, such as the app version being used, the service endpoint the app is hitting, and how long the app is taking to download the latest data. In addition, if any exception occurs anywhere in the application, a detailed error message with stack trace can be logged along with user parameters at that moment.

A tracing component creates a Logs folder in the LocalState folder (if it is not yet created) using the method ApplicationData.Current.LocalFolder.CreateFolderAsync to create the folder. It creates a new log file each day with the date as the file name under the Logs folder in LocalState.

The method Windows.Storage.StorageFolder.CreateFileAsync is used to create the log file and FileIO.AppendLinesAsync is used to write log messages into the log file. The tracing component exposes methods to the application to use for logging any kind of message (error message, information message, warning message, etc.). Because writing into a file will be done asynchronously by the “awaitable” method, the public methods add the log message to a static list (optionally, a queue can be used). There is a timer inside this component with a timer tick event, which is executed every second. Inside that event handler, a method is called to write the message into the log file. Log files could be purged after seven days. If the application throws an exception, an alert message could be displayed and, behind the scenes, call the tracing component to write the exception details into the log file. A button on the Charm bar could give the user the capability to email the log file to operations.

Windows Apportal – Developer Training | 22

Tiles and Tile Sets

Data presentation and navigation are included in this section.

User Experience Goals View and navigate data using graph and interface elements. Modify data viewed by changing filters; when possible, filters should persist. Developer Objectives Present cycling data on live tiles. Provide for drill up and drill down within filtered data. Set rules and constructions for global and local filters. Best Practices Custom control for cycling data—A custom control is used to select data from the current domain record set, displaying the data at that level in a list report view.

Windows Apportal – Developer Training | 23

Navigation control—Desired actions include results from clicking the Back button, Commented [HC12]: How to use the Live Tile Control. clicking a segment on a stacked chart, and/or clicking when a user is at the extremes of How to use the Chart Control a chart and continues to click.

Design decisions may include: Graphs must have more than one bar. The Back button drills up. The Back button goes to the hub from the highest level on a graph or grid. Drilling down from the lowest level of a chart displays the grid.

Whenever a drill-down filter is applied, an Apportal can apply a set of logic rules. Because one dataset underlies a tile set, these filters can change both the graph view and the grid view and keep the graph and the grid synchronized.

Apply these rules when the user is drilling up (clicks the Back button).

 The drill-up rules apply only to graph and grid views that support the drill-down capability. For all other pages in an Apportal, the Back button simply moves the to the previously displayed application.  If the data level is the highest level of the drill-down filters hierarchy (e.g., country), navigate to the Apportal home page. Don’t make any global filter changes.  Determine the number of possible values that are available in the next higher data level of the hierarchy. For example, if the data level is district, check how many region values are available. If there is only a single value available, go back to the Apportal home page. This means that no higher graph view level is available to be displayed because they all only have a single value to display. Otherwise, change the filter selection to All for that data level and every level below it.

All levels in the drill down are maintained in the .NET collection. A wrapper class holds the details of each domain hierarchy location and its associated aggregation. A PageHeader user control defines the page header title and the subtitle, which is dynamically set based on the drill-down level the user navigated to. The Back button click in this user control initiates the drill-up process.

Windows Apportal – Developer Training | 24

Global Filters—Global filters act on all data across a Windows Apportal. All filter values Commented [HC13]: How filters work, and implementing the in the global filters are loaded from the domain data sets and are applied to the base Search Box control data set before binding the data to all tiles, charts, grids, and more. All the required logic to bind data to filter controls is contained in a single user control.

Local filters—Storing local filter data in the same context and method as global filters is not possible, as local filters are constrained to the page that the user is viewing, not the dataset behind it. Local filter data is not stored globally, but is stored in the view model for the individual page (by page prefix) to which it applies, and will only be refreshed when a filter setting is changed, as opposed to refreshing every time that the user navigates back and forth between pages.

Filter persistence—Saving the filter selections on every Apply click is a very time- consuming process. User-selected filters are saved on an application-suspension event

Windows Apportal – Developer Training | 25

Offline Considerations for using an Apportal in offline mode are included in this section.

User Experience Goals Use an Apportal offline. Developer Objectives Make data available for offline use. Maintain as many online-mode behaviors as possible. Best Practices Reading data offline—Offline data is, obviously, not available online, so it must be maintained locally. The available data is maintained in binary files on the local computer. The same global filters that are used in online mode are applied to the locally stored, offline data that is used to display tile and chart data.

Persisting filters offline—If domain data has changed since the last data synchronization, user-selected filter values will be skipped as the pre-select filters are (re-)constructed.

Additionally, if the application goes from offline to online mode, the persistent filters are passed back to the now-available service for processing.

Stale data—During the synchronization of the many data sets involved in an Apportal, it is possible that a sync failure may occur. To minimize the impact of such failures, the initial data synchronization is done to a temporary folder, which is then duplicated into the live data working set of files. Only in the case of a successful synchronization of all the data sets is the live data overwritten. Simply put, either all of the data is up to date, or none of it is; there is no inconsistent or ambiguous sync state. User-triggered synchronization is possible through the placement of a Sync button in the interface.

Windows Apportal – Developer Training | 26

Appendix A: Resource Files

VS Code Description Folder / Name in Resource Content Reference Kit Telerik Chart TelerikChartControlSample, How to use the chart control Control TelerikGridView How to display data and change bar colors

Callisto Live Tile CallistoLiveTileSample How to use the live tile control Control How to make the control animate through the two faces

Custom Search SearchBoxControlSample How to create a custom control Control How to define custom styles for the control How to use template bindings to pass properties XAML/MVVM MVVMCodeSample How to use bindings Technologies MVVM – Commanding MVVM – INotifyPropertyChanged DefaultViewModel (Windows 8+ apps)

Async/Await AsyncAwaitSample How to use async/await How to return data synchronously from an async method How to convert IAsyncResult type methods to async/await Different types of async calls (IAsyncOperationWithProgress/IAsyncActionWithProgress)

LINQ LinqExpressionTreeSamples Building LINQ queries (Hardcoded) Building dynamic LINQ queries using expression trees Defining a data model that can be saved and later retrieved in order to define dynamic LINQ queries Documents WCF and AD WCF and Active Directory.docx Custom Http Custom HTTP Handler.docx Handler

Windows Apportal – Developer Training | 27

Appendix B: Global Filters Global filters apply against all the data sets that are used for all views across an Apportal, and are much wider in scope than local filters applicable to a single tile set. Great care should be exercised when determining whether or not to implement global filters, as the levels of complexity added can significantly lengthen the development and maintenance cycles.

Global filters act on all data across an Apportal. All filter values in the global filters are loaded from the domain data sets and are applied to the base data set before binding the data to all tiles, charts, grids, and more. All the required logic to bind data to filter controls is contained in a single user control.

Apportals support the concept of having a hierarchal relationship between global filters. For example, sales location data can be grouped into Account Team Units (ATUs), the ATU data can be grouped into districts, district data can be grouped into regions, and regional data can be grouped into countries. Thus, if a user selects a specific district, only the data for that district would be displayed in any view. Data about ATUs and sales locations in other districts would not be displayed.

User changes to the global filters affect all reporting data sets. Changes to global filters are applied after the user clicks Apply.

Global Filter Flyout

Because global filters control the content of the graph and grid charts, design considerations for global filters could include the actions that result from clicking the Back button, clicking a segment on a stacked chart, and/or clicking when a user is at the extremes of a chart and continues to click.

Windows Apportal – Developer Training | 28

In this example of an Apportal implementation, a user can set the global filters by accessing the app bar, selecting Global Filters, making selections in the expanded menu on the right-hand fly-out, and selecting Apply. If a group has more than one data point, users can select more than one global filter (the default is All). For example, if a user selects one district, the graphs and grids would show all the ATUs and sales locations within that district. If the user selected two districts, the graphs and grids would show the ATUs and sales locations for both districts.

These rules are applied while the user is changing values for drill-down filters or cascading filters in the global filters control.

1. When the user selects one or more filter values, all filters in the hierarchy below it are filtered to contain only the related child values of the currently selected filter (cascading filters). For example, if a user selects a single region, the districts are then limited to the districts of that region. 2. When the user selects one or more filter values, all filters below it in the hierarchy will set their default selection to All. All available values will be selected by default and the All value itself will be selected for each of these filters. In essence, changing a filter resets all lower filters to All.

These rules are applied when the user clicks the Apply button of the Global Filters control to determine what graph view level and data level should be displayed.

3. Find the lowest data level of the drill-down filter hierarchy that has been modified (i.e., where All is not selected) and display the chart at the respective graph view level for that data. For example, if the lowest level of the hierarchy modified is region, the data level will be region and the graph view level will be country (which shows all selected regions). Apply rule 4 before displaying the chart. 4. Never show a chart with a single bar except at the lowest data level (e.g., Account)

Logic:

If there is only one data value available at the given graph view level, then lower the graph view level by one. Continue this pattern until either more than one data value is available at the data level or the data level is the last level of the hierarchy.

Windows Apportal – Developer Training | 29

Based on the aforementioned rules 3 and 4, set the graph view level and display the data level.

NOTE: There are three reasons why only one value may be available. First, the user has specifically selected a single value. Second, due to the user’s download filter settings, only a single value is available for this level. Third, there is only one value available based on how the higher levels are filtered. In these last two cases, the filter may be set to All but when applying this to the rule, ignore the All and treat it as having only a single value.

NOTE: When the user manually changes their global filters, the assumption is that they are discarding whatever drill-down/drill-up path they have taken and want to see a new view of the existing tile, graph, or grid they are on. If the user drills down into a chart and then changes their geography filters, the drill-up pattern cannot be a reverse of the drill downs the user previously performed. Instead, the drill-up business rules must be applied to determine what is displayed when a user clicks the Back button. If the user drills down and then drills back up without manually changing the global filters, applying the drill-up business rules will behave as if the user is reversing the previously performed drill-down pattern.

Windows Apportal – Developer Training | 30 18

Appendix C: Offline Much of the functionality of an Apportal can be designed to work when the client device is offline. One approach to accomplish this is to download and store, on the client, the datasets that hold all the data which underlies all reports designed into an Apportal. This allows the user to continue to view their data when network and Internet access is slow or unavailable. Another advantage to storing data offline is that the data can be made quickly available to report views, making the application very responsive. Offline Challenges Providing the ability for the Apportal to store and display data while the application is offline adds significant complexity and challenges.  Offline data can become stale and requires periodic and timely synchronization with the backend. A refresh may need to occur at an inopportune time. The download process may be noticeably slow to the user, depending on data volume.  Storing the sensitive data on the client potentially exposes the data to risk.  There is the potential for a large volume of data to be required, which can become problematic for smaller devices.  A Windows 8.1 application cannot connect directly to client databases, such as SQL Express. Local Data Storage Windows 8.1 requires devices running Modern UI applications to use a service as a proxy for querying a database. An Apportal that works with offline data must store the data locally, which requires an alternative approach to storing and querying local data. Three alternatives to consider are: SQLite, local files, and Brokered Windows Runtime Component (BWRC). SQLite The open source tool SQLite can be used as a local data store. SQLite tends to perform adequately with very small data sets (i.e., less than 20 MB). When the data size increases, querying performance dramatically drops off. Also, SQLite does not support the concept of stored procedures. Local Files To provide performance and flexibility when performing operations on the data in an Apportal, the Apportal can store data in flat files and load them into data objects in memory to make the data accessible to the application. One consideration with this approach concerns sensitive data. Many companies require that sensitive data is encrypted when it is transmitted outside a corporate network. One approach would be to store files in an encrypted format using the Windows 8.1 .NET encryption API. Brokered Windows Runtime Component (BWRC) Brokered Windows Runtime Component is a feature for the Windows 8.1 Update (Build 2014 and later) that allows Windows 8.1 sideloaded applications to use applications and functionalities that were developed for desktop applications. This functionality is only for sideloaded Windows Store applications and does not work on all devices. As an example for using BWRC, the Apportal could communicate with a local SQL Express

Windows Apportal – Developer Training | 31

database on the client. Data could be locally stored and queried from SQL Express and bypass the need for storing the data in files. See this MSDN white paper for more information.

Loading Data into Memory

A main concept behind Apportal reporting is to allow the user to drill up and drill down through the data, aggregating and reporting on data at different levels. With any report (graph, grid, or live tile), the actual number of rows of data displayed is very small— typically less than 50 rows. However, to be able to accomplish dynamic reporting with offline data, it is necessary to bring in every data set across the application at the lowest level of aggregation (i.e., row level data). Having row level data stored locally allows the application to aggregate the data on the fly as the user drills into different levels. When the data is stored locally, performance can be hampered because the client is now required to act like a database server. To overcome this limitation, the data sets can be loaded into memory, which will greatly enhance performance. Data Binding Data sets that underlie the reports can be stored in memory in the ApplicationData.Current.LocalSettings.Values dictionary. When a user enters a graph or grid view, the local filters are applied to the data set, and then any necessary aggregations are performed before binding the data to the graph or grid. Asynchronous Loading Loading data into memory when the application starts can be time consuming. If each data set is loaded asynchronously, each tile can become available to the user as soon as data for that tile is loaded. On-Demand Loading The size of the dataset will differ depending on the user’s role and the amount of data the user has selected. For example, an account manager who wants to look at the past year’s sales of a specific sales location will need a much smaller dataset than the CEO who wants to look at the past year’s sales across the company. If the data set is very large, the amount of available memory on the device may become problematic. In addition to downloading all data for all data sets whenever the user performs a download, aggregated sets of data for the live tiles could also be downloaded and stored. In this case, when the download completes, the Hub View is displayed and the only data loaded into memory is the aggregated data for the live tiles. When the user selects a tile, the specific data set for that tile set is loaded into memory. If the user changes the global filters, the Apportal is designed to calculate new aggregate values for every live tile. Each data set would need to be loaded into memory to calculate the new aggregations. This could be done asynchronously in the background as the new data for each tile set is loaded and calculated, and the new aggregation is stored and the old aggregation is unloaded. While this is going on, the live tile moves into suspend mode.

Windows Apportal – Developer Training | 32

Downloading Stale Data Each organization will need to determine the point at which data is considered stale. This might vary depending on the nature and use of the data. Timing the Data Sync Some factors to consider when determining when to refresh the data would be business needs, the amount of data to refresh, the frequency at which the underlying data source changes, and the convenience or inconvenience of an automatic refresh. It could be possible for an Apportal to automatically refresh the data based on a business-derived schedule when the device is online. If the data is automatically refreshed, some things to consider could include whether to allow users to disable automation because of low bandwidth connection, the amount of data that would be refreshed, whether the refresh schedule would align with business hours, or whether a user would have a business need to keep the data stale for a period of time. The Apportal application could provide a Sync button for users to manually refresh the data at their convenience. A prompt could be set to remind users to refresh the data if a set amount of time has elapsed—for example, 24 hours. Download Preferences Most users of an Apportal application require only a small percentage of an enterprise’s data to perform their jobs. If an Apportal has access to large volumes of data for offline use, a download preferences view can be used to allow users to winnow down the data to only that which they need. This reduces the volume of data that is downloaded for offline storage and improves the application’s performance. Whenever the user changes these filters and clicks Save, the Apportal downloads a new set of data as determined by the new parameters. In the following example, after the user selects their download preferences and clicks Save, the Apportal will navigate to the Hub View and the data download process begins in the background.

Filters Persistence As with global filters, download filters should be persisted so the user doesn’t need to select them each time they download.

Windows Apportal – Developer Training | 33

Sync Component An Apportal can have a custom SyncComponent, which handles the entire download process and saves the data to offline storage. The SyncComponent checks whether offline data is already available. If available, it checks whether the data is stale. It also checks whether the app is currently online. When online, the user can select Sync and the application initiates the synchronization process to update the offline data. A custom NetworkHelper class was written to keep track of the application’s status (online/offline) and update the status immediately if it changes. The SyncComponent reads the download preferences files and passes those user settings as parameters to service calls, which download the offline data. This example uses the HttpClient object and calls the GetAsync method with the URL http://www.msftncsi.com/ncsi.txt and checks the HttpResponseMessage object to verify what was received from the network call. If the whole stream was received and converted into a string, and if the words "Microsoft NCSI" are returned, that means the client has a proper Internet connection. If the client has a proper Internet connection, it will go to the middle tier URL and download the internal ncsi.txt file which had been uploaded in the middle tier service. If the client can download that file, it means that the client device was perfectly connected to the middle tier service. That sets the user status to “Online”. If either of the two checks fails, the user status is set to “Offline”.

See this MSDN article for HttpClient: http://msdn.microsoft.com/en- us/library/system.net.http.httpclient.aspx

See this MSDN article for HttpResponseMessage: http://msdn.microsoft.com/en- us/library/system.net.http.httpresponsemessage

Streaming Binary Files Transporting the data as encrypted binary files provides speedier downloads and quicker storage. Because these files can’t be queried, they have to be transformed into a readable format. This approach works extremely well when the data sets are smaller. It becomes problematic when the data set approaches the full set. There can be a long wait for the data to load and there is the potential for a smaller device to run out of available memory. The following example is one approach to streaming binary files: The ‘DataStreamer’ library is used in the service layer to convert the data into a stream of bytes. BufferedStream is used to send millions of records. The .NET DataReader object is used to read each row. Each row is serialized and sent to the client in binary format. In the client app, SyncComponent gets the stream response and stores it in the LocalState folder with the corresponding data set name and extension .bin. On the client side: A BinaryReader utility is used to parse the binary file and convert the results into the .NET collections classes MemoryStream and System.IO.BinaryReader.

Windows Apportal – Developer Training | 34

The first row of the binary file contains the schema definition that defines the fixed size of each column and enhances the readability of the files. The .NET classes ExpressionTrees, ExpressionVisitor, and Tuple are used when parsing the binary file. The references and samples in these MSND articles show how to use a LocalState folder. http://msdn.microsoft.com/en-us/library/windows/apps/hh464917.aspx http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh700361.aspx http://msdn.microsoft.com/en- us/library/windows/apps/windows.storage.applicationdata.localfolder

HTTPHandler To support downloading data for local storage, an Apportal can use an HTTPHandler for querying a data source and streaming the data to the client. This approach provides much better throughput performance over WCF when delivering larger volume result sets. A data handler (“.ashx”) in the service layer handles the conversion of data to a binary stream. All offline data queries are stored in an XML file on the service layer server. Each SQL query in the XML file has source and ConnectionStringName attributes. The data handler receives the web request from the client along with the source parameter. The source parameter determines which dataset the service needs to expose to the client. It is hosted in Internet Information Service (IIS) and protected with Windows Authentication.

Data source connecting strings are stored in the ConnectionStrings setting of the Web.config file. The data handler retrieves the SQL query and ConnectionStringName from the XML file based on the source parameter. It also retrieves the corresponding data source connecting string from Web.config based on the ConnectionStringName attribute, executes SQL query against the specified data source, and streams the results to the client.

Data handler (“.ashx”) is also secured by an authorization key. When the client is in online mode:

Windows Apportal – Developer Training | 35

Data handler gets an authorization key from the CockpitServiceGetAuthorizationKey web method and stores it in temporary memory on the client. All web requests from the client application will attach the authorization key, and this key will be validated at the data handler. If the authorization key is valid, then the client will be served. Otherwise, it will return an “Invalid Authorization” error message. For general information about ASP.Net HTTP Handlers, see this MSDN article. For information about how to develop a new APS.Net Custom HTTP Handler, see this Microsoft Support article. Commented [TM14]: Provide URLs for articles instead?

Windows Apportal – Developer Training | 36