Contents Contents ...... 1 1 Introduction ...... 4 Samples and Examples ...... 4 2 Prerequisites ...... 4 3 Architecture ...... 4 Direct to On-Prem ...... 4 Azure Cloud ...... 5 Service On-Prem ...... 6 4 Why Choose the Technology Stack? ...... 7 Rapid Application Development ...... 7 C# ...... 7 LINQ ...... 8 Async/Await ...... 8 XAML/MVVM technologies ...... 8 Less Code ...... 8 Superior Development Tools and Environment Integration ...... 8 Strongly-Typed Programming ...... 9 Source Control/Project Management ...... 9 Windows 8 Cost-Saving Solutions ...... 9 File Open Picker ...... 9 Share Charm ...... 9 Middle-Tier ...... 9 Security ...... 10 IIS ...... 10 ...... 10 WCF Data Services ...... 10 Client Connectivity ...... 10 Azure ...... 10 Database Technology ...... 10 Security ...... 11 Big Data ...... 11

1

Adoption/Familiarity ...... 11 The Bigger Picture ...... 11 5 UX Capabilities ...... 11 Hub View ...... 11 Groups ...... 12 Tiles ...... 12 Tile Sets ...... 13 Data Sets ...... 13 Report View Types ...... 14 List Report View ...... 14 Graph Report View ...... 14 Grid Report View ...... 15 Deep Link...... 16 Navigating to the Home Page ...... 16 Filters...... 16 Global Filters ...... 16 Local Filters ...... 17 Drill Down and Drill Up ...... 18 Drill Down ...... 18 Drill Up ...... 19 Graph View Levels ...... 19 Data Level ...... 19 6 Design Considerations ...... 20 Determining What the User Sees ...... 20 AuthN/AuthZ model ...... 20 Role-Based Views ...... 21 Constrained Delegation ...... 22 UI ...... 23 Hub View Parallax Scrolling ...... 23 Creating Tiles and Groups ...... 23 Dynamically Configurable Tiles ...... 25 Graphing the Grid and Graph Report Views ...... 25 Auto Scroll to Grid ...... 26

2

Data Storage Considerations ...... 26 Dedicated Data Warehouse ...... 26 Filters Persistence ...... 26 Global Filters ...... 27 Global Filter Control ...... 27 Filter Rules Applied ...... 28 Data transport ...... 29 WCF Data Services ...... 29 Entity Framework ...... 30 Monitoring ...... 30 Instrumentation Monitoring and Alerting in the UI...... 30 Instrumentation Monitoring and Alerting in the Service Layer ...... 31 7 Offline Capability ...... 32 Offline Challenges ...... 32 Local Data Storage ...... 32 Loading Data into Memory ...... 33 Downloading ...... 33 Stale Data ...... 33 Timing the Data Sync ...... 34 Download Preferences ...... 34 Sync Component ...... 34 8 End to End Example ...... 38 Creating an Entity ...... 39 OData ...... 40 Calling the WCF Data Service ...... 40 Binding the Data ...... 41 9 Deployment ...... 44

3

1 Introduction An Apportal is a collection of Microsoft technologies, third-party tools, and code that aggregate data from diverse sources and display the data in a Windows 8 hub view to create a work environment tailored to a company’s unique needs. It’s called Apportal because it combines the best elements of an application with the deep, integrated resources of a portal.

This document describes the concept, architecture, and functionality available through an Apportal and provides some technical guidance on how an organization can employ these technologies to create an Apportal. An Apportal is not limited to the capabilities discussed in this document, and can be tailored according to an organization’s needs. Samples and Examples The figures shown in this document represent an example Apportal and serve as a starting point for a concept and design discussion.

2 Prerequisites The information in this document assumes that developers have experience developing Windows 8 applications using XAML and C#. Familiarity with Visual Studio, WCF Data Services and Active Directory is recommended.

3 Architecture Using Microsoft technologies, Apportals can be integrated into an enterprise’s existing infrastructure. The following three reference architectures provide a glimpse into the multitude of ways to make integration possible.

Any aspect of these three reference architectures can be combined into the right solution at the right time for an enterprise. As an enterprise’s infrastructure expands and matures, so too can the capabilities of the Apportal. Direct to On-Prem Apportals can run within corporate firewalls to connect directly to and leverage services in an existing on-premises infrastructure. Examples of existing services could be corporate application service layers, content management services, web services, file shares, SharePoint services, or data services layers using technologies such as WCF Data Services. See Figure 1.

4

On-Prem

Existing Infrastructure

Services

Web Server CMS Server Database Server File Server

Data Stores

Figure 1

Azure Cloud An additional service layer can be created for the Apportal to facilitate integration of services and/or data sources across the existing corporate infrastructure. The Apportal service layer can be deployed to and run in the Azure Cloud. Corporate data sources can be copied or moved into Azure, as well, which can minimize or eliminate the need to invest in additional on-premises infrastructure. The Apportal can also connect directly to and integrate with other third-party services in the cloud. See Figure 2.

5

Azure Apportal Services

Third Party Services

On-Prem Existing Infrastructure

Data Stores

Figure 2

Service On-Prem If an enterprise is not yet ready for a cloud implementation, an Apportal service layer can be deployed within the on-premises infrastructure. See Figure 3.

6

On-Prem

Apportal Services

Existing Infrastructure

Data Stores

Figure 3

4 Why Choose the Microsoft Technology Stack? When evaluating a technology on a project basis there are many considerations to take in mind. Sometimes a decision on technology is not the easiest decision to make. In corporate environments, it is very common to already have the supporting infrastructure for Microsoft technologies in place. In addition, the development and server technologies in the Microsoft portfolio add several cost-saving benefits during the entire life-cycle of a project. Rapid Application Development This is a term that has lived at Microsoft for many years. A lot of investment has gone into researching and understanding development to create tools and techniques that rapidly accelerate the time it takes to develop solutions. C# Developers have many choices for programming languages. Even if the field is narrowed to .NET technologies, there are still many choices (i.e. VB.NET, C++/CLI). (For modern apps there is also the option of going with HTML5/CSS/JavaScript.)

7

C# has many benefits over the other options. C++ can execute much faster than C#. But when developing applications with lots of API calls and few low-level calls, there is little performance gain. In addition, C# applications can be written in far fewer lines of code than C++; so there is a developer productivity improvement. It is also very readable compared to most languages.

C# is also the most popular Microsoft programming language. This meant there are many talented developers already familiar with it. There are also many third-party tools available for improving productivity. LINQ One of the most time-saving features is LINQ (Language-Integrated Native Query). This technology saves lines of code in the factor of hundreds. A developer can create LINQ functionality to expose . This allows a developer to create very complex tools that are highly customizable. An example approach is using Fluent API techniques for defining behaviors of an application.

LINQ also works as an interface to data sources, like SQL via Entity Framework or Entity Framework via WCF Data Services and OData. The main advantage is being able to analyze code expressions to generate some sort of definition, whether that definition is a SQL statement or a UI behavior. Async/Await The most recent addition to the C# programming stack is the Async/Await functionality. Like LINQ it saves lines of code by a factor of hundreds. Traditionally, a lot of time has been spent on applications and trying to make them 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 apps called promises. But these still take at least a few lines of code to implement, rather than a single line. XAML/MVVM technologies XAML is one of the most productive UI platforms that exists. For a long time XAML has had its roots in WPF Desktop Applications, Silverlight, Windows Phone, Windows Embedded, and now Windows 8 Store Apps. When paired with MVVM design patterns, applications really start to shine. It can simplify testing, reducing 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, like bindings. Bindings alone have been a great benefit 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. Less Code With everything mentioned about saving lines of code, it’s important to understand why this is desirable. There is a certain elegance to code in its simplicity. It’s generally faster, has fewer bugs and is easier to read. These are all things that can affect many aspects of a project’s life-cycle. Superior Development Tools and Environment Integration With all the solutions provided by Microsoft, tooling is extremely important. Having the right tools can also accelerate productivity, especially when they integrate between different scenarios or environments.

8

Strongly-Typed Programming Visual Studio provides many language analysis tools that can identify potential problems before an application is ever built. Relying on the strongly-typed nature of C# with the tools Visual Studio maximizes productivity at the same time as removing some of the more mundane tasks developers are faced with coding (in any language). Source Control/Project Management Source control is an imperative piece for any software project. Team Foundation Services provides this functionality plus much more. In addition to being the source control management solution, it also supports project/task management. These projects also integrate with SharePoint in a way that allows for a document repository on a per-project basis. Visual Studio is largely integrated with Team Foundation Services and provides additional developer tools. Windows 8 Cost-Saving Solutions There are many interactions and APIs for those interactions in Windows 8 that can drastically reduce the scope of an application. These also enable extreme multitasking and maximize the use of several apps rather than just a single app. File Open Picker Opening files from different locations can be a mundane task. Take for example, attaching a file that exists in a cloud-storage location: a user may have to navigate to that site, download the file to their local storage, and then choose how to attach it within the application. That entire action can be simplified if an app for that cloud-storage vendor exists which implements the file open picker contract. By implementing this contract, any application can open a file via the application whether it exists locally or not.

From an application perspective, this means a team could implement the ability to open files from numerous services just by using the file open picker. A great example is the Windows 8 email application. Attaching a file in an email is done using the file open picker. The interaction is simple, and each application that implements this contract has full control over the UI for picking these files. Share Charm The share charm, like the file open picker, is an excellent way to maximize app interactions and reduce scope of an application. Applications can be designed to use the send/receive end of this contract and allow data to easily be passed between applications. For line-of-business applications where the same record may exist in several different applications, identifying that record in each application can be tedious for a user. Sharing data between apps can also create new workflows in the scope of an application. Middle-Tier Microsoft has many products in the middle-tier space. Many of these products have more than a decade of history behind them. Over the years they have been adapted, extended, and optimized to meet the standards of the Internet and the intranet. A developer can look at it as though the middle-tier is simply there to connect client applications to back-end data, understanding that many technologies go into making an acceptable middle-tier.

9

Security For many organizations, security is extremely important, and many organizations already have security mechanisms in place. Active Directory is commonplace at companies. This is extremely important because a computer joined to a Windows Active Directory domain can offer a single-sign-on experience, superior to anything on the public Internet. Connecting to internal resources can be done with ease. From a development perspective, there is never a need to create login screens or store usernames and passwords. Authentication is performed on the Windows lock screen, and all applications that have enrolled in the Enterprise Authentication capability are allowed to use (not see) these credentials for communications with internal resources. IIS One of the necessary components of a strong middle-tier is Internet Information Services. It has built-in functionality that supports all the necessary components for an internal middle-tier solution (Authentication, Encryption, Load-Balancing, etc.). Entity Framework For middle-tiers that need a means of communication with a back-end (typically SQL), Entity Framework is extremely flexible and powerful. Because it exposes its own LINQ-layer, SQL queries can be generated completely from .NET code. This allows developers to control exactly how the back-end is queried and translated into their code. It also has many time saving features that allow developers to connect to different data sources in minutes. WCF Data Services Exposing data from a middle-tier to a client application is something companies spend millions of dollars on. Traditionally, simple technologies have been created to achieve this. They have always existed with many shortcomings: filtering, sorting, paging, relationships, etc. All of these are capable with WCF Data Services. Exposing an entity framework dataset with WCF Data Services can be done in minutes. Client Connectivity Connecting to services like WCF Data Services or SOAP services can be automated in Visual Studio. This saves days of development work. All of the types and code necessary to establish communications with these services are generated automatically by the metadata exposed from the service. LINQ layers exist to facilitate advanced queries to this service much like querying SQL via Entity Framework from code. This provides a level of commonality to developers which allows them to leverage more reusable code. Azure When using cloud services, Azure is a premier provider. It allows all the technologies described to be used. Azure provides a level of integration with these existing technologies that automates scalability and maintenance. Visual Studio integrates with Azure in a way that allows very little overhead. With little extra work, a regular application that has been created to run in IIS can be modified to run in Azure. Database Technology At times an application needs to reach many different types of storage mechanisms. These are often defined by the customer. When a developer has the ability to create a database for a solution, SQL is a

10 strong choice. When the customer’s technology already is SQL, the developer has an added benefit immediately. Both Entity Framework and Azure services can leverage Microsoft SQL technologies. Security With sensitive data, security is extremely important. This can vary by industry and is sometimes dictated by industry-specific regulations. SQL can provide authentication for data based on an end-user’s Active Directory credentials. Big Data The amount of data that exists and can be collected by applications is incredible. Having a common technology that can store and query that data becomes even more important. SQL has been optimized to handle many of these big data concerns. When tested under situations with terabytes of data, SQL is a top performer. Adoption/Familiarity There are many types of SQL available. That is a strong advantage to Microsoft SQL Server. SQL as a language is very commonplace. It is unheard of for a DBA to not have any SQL experience. In addition, Microsoft’s SQL technologies provide superior capabilities compared to others. The Bigger Picture Not all of the advantages of each of Microsoft’s technologies has been described here. But hopefully is enough to support a decision to use them. Each of the technologies or advantages described probably have a counterpart from another vendor. But from the different layers described, finding just one vendor that can supply the end-to-end technologies can be difficult. In addition, the level of integration between these different layers is incomparable.

5 UX Capabilities Hub View The main view of an Apportal is the hub view which consists of groups of tiles and functions as a home page. The hub view does not replicate the desktop. It provides the look, feel, and some of the functionality of the Windows 8 start screen in a format tailored for a company’s unique needs. The tiles connect to and display information from sources such as a CRM system, Internet pages, other applications, and data sources. See Figure 4.

Figure 4

11

Groups As with the Windows 8 start screen, tiles that have related functionality in the Apportal are arranged in groups. Each group has a heading and the associated tiles. In this example, tiles are grouped in a 2- column, 3-row grid which works well in many resolutions. See Figure 4.

Tiles As with the groups, an Apportal hub view has tiles that function in a very similar manner to tiles on the Windows 8 start screen.

Apportal tiles are one of three display types: static, live, and snap view. For example:

Static tiles display a static image/logo.

Live tiles function similarly to live tiles on the Windows start screen. They can display a rotating list of data or images, a video, graph reports, or grid reports.

Static and live tiles, when clicked, navigate to another view within the application (such as a graph report view or grid report view).

Snap view tiles are either static or live tiles but instead of navigating to another view when clicked, they open external applications such as , Lync, or Outlook in a filled view and the content of the tile moves to a snap view.

Each snap view tile has an associated URL. The URL identifies which external application to open via a URL type and file extension that is mapped to applications by the operating system. For example, if the URL begins with http:// the operating system will attempt to open a browser in the filled view.

In this example, the user clicked the Field Dashboard tile, and the Field Dashboard opened in a browser. See Figure 5.

Snapped view Filled view Full screen

Figure 5

12

If the operating system can’t find an association, a dialog box will pop up. See Figure 6.

Figure 6

For information about snap view, see this MSDN article: http://msdn.microsoft.com/en- us/library/windows/apps/xaml/hh465371.aspx

And this MSDN article: http://msdn.microsoft.com/en-us/library/windows/apps/bg182890.aspx 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 tile set is the navigation starting point for one or more associated report views based on a single data set. In this 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 set. The data set is presented in a dynamic graph and in a grid format. See Figure 7

Figure 7 Data Sets In an Apportal, a data set contains the data needed to support one or more tile sets. It consists of a schema and is populated with data determined by a query. The query is formulated from parameters set when the user selects data filters.

13

Report View Types A report view is a specific format used to render data in a meaningful and useful way for the user. The three report view types available in an Apportal are list, graph, and grid. List Report View List Report views are used to display one or more data points in a simple list. One use for a list view would be to display a small set of data points on a live tile. See Figure 8.

Figure 8

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.

Here are three examples of bar charts presented in a graph view.

Stacked

Figure 9

Horizontal

14

Figure 10

Waterfall

Figure 11

Waterfall charts are normal stacked charts where some of the series are defined with a transparent color so some of the bars appear to not start from the bottom of the Y-axis. This expands a stacked bar to look as though it is cascading across the chart. 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. See Figure 12.

15

Figure 12

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, 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.

Navigating to the Home Page A user can return directly to the hub view from within graph or grid views by bringing up the app bar and clicking the Home icon at the upper left corner of the screen. Filters Filters set the parameters for the query to extract only the data which the user wants to see. There are two types of filters in an Apportal: global and local. Global Filters Global filters determine the data sets that are used for all views across an Apportal.

Apportal supports the concept of having a hierarchal relationship between global filters. For example, sales location data can be grouped into 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 on any view. Data about ATUs and sales locations in other districts would not be displayed. See Figure 13.

16

USA - Central

Figure 13

User Actions In an Apportal, 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 (see Figure 14), 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 location within that district. If the user selected two districts, the graphs and grids would show the ATUs and sales locations for both districts.

Figure 14

Local Filters 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.

17

Drill Down and Drill Up To support the drill-up/down capability, 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, ATU, with 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 Drilldown 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) 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/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, sales territory. See Figure 15.

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

18

Figure 16

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. See Figure 17.

Figure 17

Graph View Levels Given a geographical hierarchy consisting of the data domains Country, Region, District, and Sales Territory, the highest level a graph view can display is country which would show all the regions. Moving down the hierarchy, a graph level showing region would show all the districts for the selected region. This would continue down through the hierarchy until the graph level ATU shows the data for the Sales Territories within that ATU. Data Level The data level of a graph is the data domain for which the graph displays information. For example, a graph level showing the USA-Central region would show the data level for the districts within the USA- Central region. See Figure 18.

Graph Level Data Level

19

Country displays Region Region displays District District displays ATU ATU displays Sales Territory (lowest data domain level)

Figure 18

6 Design Considerations Throughout the design and development phase, designers, stakeholders, and developers will encounter some or all of these considerations. While this list is not exhaustive, it can be a springboard for discussion. Determining What the User Sees AuthN/AuthZ model Microsoft SQL Server data sources use Windows Authentication. The data sources grant access to users that reside in specific Active Directory Security Groups. Some of the data sources grant users access to all data. Other data sources restrict users’ data access at the row level. In these cases, different security groups get access to different data through filtering that is applied at the database.

20

Role-Based Views Powered by Active Directory, an Apportal provides the ability to filter, share, and display information based on 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 this example, the user’s role determines which data is displayed.

When an Apportal is launched, the “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 access against Active Directory and return the user role object to the client application. The Apportal inspects the user role object to determine which tiles the user can view along with other role-specific customizations.

The following code is an example for interacting with the Active Directory from the WCF Data Service to validate that the user is part of a security group.

Code snippet : DirectoryEntry object is available in System.DirectoryServices namespace

//The below code interacts with Active Directory

DirectoryEntry usersEntry = new DirectoryEntry("LDAP://" + );

DirectorySearcher search = new DirectorySearcher(usersEntry);

search.SearchScope = SearchScope.Subtree;

search.ReferralChasing = System.DirectoryServices.ReferralChasingOption.All;

search.Filter = string.Format(CultureInfo.InvariantCulture, "(&(objectClass=user)(sAMAccountName={0}))", );

SearchResult result = search.FindOne();

DirectoryEntry user = new DirectoryEntry(result.Path);

//Retrieving user’s attributes from Active Directory

PropertyValueCollection userProperties = user.Properties["memberOf"];

//Checking user belongs to a Security Group using Linq

bool isUserBelongsToSecurityGroup = (from userProperty in userProperties.Cast()

where

userProperty.Contains("CN=" + + ",OU=UserAccounts") == true

21

select userProperty

).Count() > 0

This code example shows how the “GetUserRole” is called from the client. It wraps around the previous example and delivers the UserRole class object and service deployment to a WCF service end point “CockpitService.svc”.

SalesCockpitEntities cockPitContext = new SalesCockpitEntities(new Uri(string.Format("{0}/CockpitService.svc", Utilities.webserviceRoot)));

cockPitContext.Credentials = CredentialCache.DefaultCredentials;

DataServiceQuery query = cockPitContext.CreateQuery("GetUserRole");

var result = await Task.Factory.FromAsync>(query.BeginExecute, query.EndExecute, null);

if (result != null)

{

this.userRole = result.ToList().FirstOrDefault();

ApplicationData.Current.LocalSettings.Values["Is

ExecutiveUser"] = this.userRole.IsExecutiveUser;

ApplicationData.Current.LocalSettings.Values["Us erAlias"] = this.userRole.UserAlias != null ? this.userRole.UserAlias : string.Empty; 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

22

(because Windows 8 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. UI Hub View Parallax Scrolling Parallax scrolling could add a unique aspect to the hub view. A consideration might be whether it would add to the user’s experience. For more information about parallax scrolling, see this MSDN article. Creating Tiles and Groups Tiles and groups are generated as observable collections that are bound to the GridView. This collection could contain only the tile title, template, and group name, etc. Each tile should have its own XAML template so individual tiles can be modified without affecting other tiles. Tile structure and tile content are maintained separately so an organization can have a single hub view structure across all Apportals in the organization.

The live data appearing on tiles is bound by the tile or group collections. Usually, every tile’s data has been bound by its own view model’s collection (except for snap view tiles). For example, a Sales Stage tile would display data in the same manner as the Sales Stage page view model.

For example, tiles and groups are created in GridView using a normal Windows 8 project by extending the normal GridView control into the VariableSizeGridView control. A column span was assigned for each of the tiles based on the tile size defined in the tile template. Windows 8.1 tiles have four sizes: small (70x70 pixels), medium (150x150 pixels), wide (30x150 pixels), and large (310x310 pixels). The hub view examples in this document use the medium and wide tile sizes.

This is an example of how tiles like static or snap view tiles were created using normal XAML grids in the tile item template to show the image.

23

This is an example of how a custom tile control could be written in XAML to cycle five different data points on a live tile.

For more information about Gridview, see these resources

GridView : http://msdn.microsoft.com/library/windows/apps/windows.ui.xaml.controls.gridview.Aspx GridView Example : http://code.msdn.microsoft.com/wpapps/ListViewSimple-d5fc27dd

24

Dynamically Configurable Tiles Tiles can be dynamically defined and configured through the service layer. This gives the developer the flexibility to change tiles and their behavior and appearance from the service layer. This avoids having to perform a new app release for small tile-related changes. An AppSettings.XML file in the service layer defines the tile name, group name, URL that will be opened when the user clicks that tile, tile order, tile color, tile icon, etc.

A consideration would be whether to add a snap view to a live tile, which has extensive code behind it. A static tile does not have that code and is more easily configured as a snap view tile.

Graphing the Grid and Graph Report Views The dynamic report views in an Apportal require robust charting capabilities. The chart and grid examples in this document were created using a chart control.

Another consideration could be whether to have the developer create a chart control or whether to use a third-party chart control. Third-party chart controls add functionality without additional developer resources. The choice of a specific third party chart control depends on the developer’s preference and business needs. Alternatively, a developer could create a chart control that exactly meets the organization’s needs.

Using bar chart color to add a layer of information

Charts can be configured to provide additional information via bar colors, tool tips, or legends.

The third-party chart control assigns distinct colors to distinct data series using its own default colors. Those colors may or may not align with business requirements.

Custom templates can be inserted into the control to assign a color to the bars in a chart according to specific criteria. For example, in this chart, the green bars represent a specific forecast type. The CustomPalette object in the chart control uses data sets like AddColorByForecastType or AddColorByOutcomeName to get the predetermined color codes from a template and assign them to the CustomPalette object. See Figure 19.

Figure 19

25

Auto Scroll to Grid Because the graph and grid views link to the same data set, automatic navigation between the two views is possible.

As an example, if a user has drilled down to the lowest level of detail in a stacked bar chart and clicks on the chart bar, an Apportal can automatically scroll to the corresponding grid view. To use this function, the tile set must have a stacked bar chart, drill-down capabilities, and a grid.

This is one method for creating this function. A chart and details grid are maintained in an XAML pivot control. For the lowest drill-down level, the second pivot item is the grid control. On the chart’s tap event, the chart scrolls to the grid. Data Storage Considerations Dedicated Data Warehouse When an enterprise does not have data sources that are conducive to SOA or are not intended for use in reporting, an application-specific data warehouse can be created. ETL processes will need to be developed for gathering the data from existing data sources.

Filters Persistence An Apportal persists the global, and local filters the user has selected so the filters are remembered the next time the application is started.

After the user selects the global filters and clicks Apply, the filter values are saved in an XML file in the LocalState folder of the Apportal. The AppDataManger stores and retrieves the persisted XMLs for the global filters. This component serializes the filter data object into the XML file and deserializes the XML file back to a filter data object. .NET XML serialization could be used for this feature. This file is read every time the user opens the Apportal.

The XML file can be saved in the RoamingState folder from which it can be read by other devices. This is effective for small data sets, and the user must be logged into a Microsoft account. One consideration would be how much data can be stored in the RoamingState folder.

Local filters are persisted but not as XML files. They are stored in the ApplicationData.Current.LocalSettings.Values dictionary and are reapplied when the user restarts the application.

See these MSDN articles for information and samples about roaming state data storage. http://msdn.microsoft.com/en-us/library/windows/apps/hh464917.aspx http://msdn.microsoft.com/en-us/library/windows/apps/hh465123.aspx

For more information, see this MSDN article.

26

For information about authentication methodologies supported by Analysis Services, see this MSDN article.

For information about impersonation and delegation in WCF applications, see this MSDN article. Global Filters Global filters act on all data across an Apportal. Changes to the global filters affect all reporting data sets. Global filters are applied after the user clicks Apply.

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, etc. All the required logic to bind data to filter controls is contained in a single user control. See Figure 20.

Global Filter Flyout

Figure 20

Global Filter Control 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.

This is an example of how global filter controls could be used to select data for the graph and grid views. The design decisions for this example 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

27

Filter Rules Applied Whenever a drilldown filter or a global 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.

These rules are applied while the user is changing values for Drilldown 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 on 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 drilldown 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 lowest data level (e.g., Account).1

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.

5. Based on rules 3 and 4 above, set the graph view Level and display the Data Level.

1 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.

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

28

18 6. 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 application to the previously displayed page and does not change the global Filter values.

7. If the Data Level is the highest level of the Drilldown Filters hierarchy (e.g., Country), navigate to the Apportal home page. Don’t make any global Filter changes.

8. 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.1. 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. Treat the drill up exactly the same as if the user modified the filters and clicked “Apply”.2 Apply rules 3, 4, and 5 above.

2 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, 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.

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. Data transport WCF Data Services WCF Data Services is a highly effective method for working with online data. This is a brief overview. For more information, see the links at the end of this section.

To expose the data from a WCF service, a developer must develop a service contract, develop a contract implementation, write business objects to 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 . By default, WCF Data Services exposes data as an ATOM, which is a Representational State Transfer architecture. Data can be queried via Web URL.

More information about WCF Data Services can be found this MSDN article. For general information about installing a WCF Data Services framework, including sample code, see this MSDN article.

29

For general information about Linq, see this MSDN article. Entity Framework WCF Data Services uses the Entity Data Model (Entity framework). In general, an entity framework can be treated as a data access layer which interacts with data sources and populates data in business objects (entities).

For information about entity framework see this MSDN article.

For information about creating a data service using WCF Data Services, see this MSDN article.

For information about authentication methodologies supported by Analysis Services, see this MSDN article.

For information about impersonation and delegation in WCF applications, see this MSDN article. Monitoring An Apportal captures metrics about data download 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. Instrumentation Monitoring and Alerting in the UI An Apportal can continuously log user actions such as the app version is being used, the service end point 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.

Tracing component This is one method for creating log files. The Tracing component creates a “Logs” folder in the LocalState folder if it is not yet created. The Apportal uses 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, it calls 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.

The alerting component could be used to show messages to the user. The standard class from the framework to show messages is Windows.UI.Popups.MessageDialog.ShowAsync(). As this is an awaitable method, it can’t be called from any Catch Blocks in the case of exceptions occurring. So, from the Catch clocks, the method Alertuser is called. Inside that method, the message is added to a stack. There is a timer inside this component with a timer tick event, which is executed every millisecond.

30

21 Inside that event handler, a message will be popped from the stack and shown in the alert dialog box. This component will show all information type, warning or error messages. Inside the Catch Block, the exception is logged using the trace component and shows the error message using the alerting component.

Application Insights Application Insights is a Microsoft technology that logs information about an application which can be used to make business decisions. This is the main command to call Application Insights.

ClientAnalyticsChannel.Default.LogEvent("StoreApp/" + tileGroupName + "/" + tileName);

For more information, see these articles.

http://msdn.microsoft.com/en-us/library/dn481095.aspx http://msdn.microsoft.com/en-us/library/dn509554.aspx http://www.codeproject.com/Articles/729578/Using-Application-Insights-with-an-existing-Window

Instrumentation Monitoring and Alerting in the Service Layer In an Apportal, the service layer can capture and write application errors to an application-specific log in the event log. SCOM is used to read the event log and generate alerts. Performance metrics are taken from IIS logs.

This example gives one option to capturing and writing application errors in an Apportal.

Event Logs EventLogInstaller is a console application used to create a specific log in the Event Log. The service layer logs application exceptions in the specific logs based on the data sets with the appropriate event IDs. SCOM monitors these event IDs and alerts the operation team to take the next step to resolve the exception.

IIS Logs IIS Logs are processed to capture these metrics to show in Excel PivotTable Reports

 How many users have installed Client App?

 How many users have downloaded the data from Service Layer?

IIS Logs are captured and parsed using the LogParser tool which can be downloaded from http://toolbox. The LogParser output is then imported to a SQL Server database. These steps are automated and configured to run under SSIS Packages. Excel PivotTable Reports are fed by running the SQL queries against the database where IIS logs are imported.

This MSDN article provides information about how to create a custom Windows Event Log and how to write the exception in the custom Windows Event Log.

31

22 7 Offline Capability 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 offline adds significant complexity and challenges to the application.

 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.  Windows 8 application cannot connect directly to client databases such as SQL Express.

Local Data Storage Windows 8 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 .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 sideloaded applications 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 database on the client. Data could be locally stored and queried from SQL Express and bypass the need for storing the data in files.

32

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, 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, calculated, the new aggregation is stored, and the old aggregation is unloaded. While this is going on, the live tile moves into suspend mode. Downloading Stale Data Each organization will need to determine the point at which data is considered stale. This might vary depending on the nature of the data and the use to which it is put.

33

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 would be 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 this 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. See Figure 21.

Figure 21

Filters Persistence As with global filters, Download filters should be persisted so the user doesn’t need to select them each time they download. 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

34 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 word "Microsoft NCSI" is 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 fail, 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 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. This 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 Data reader 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:

35

 A BinaryReader utility is used to parse the binary file and convert the results into the .NET collections classes MemoryStream and System.IO.BinaryReader.  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 data set 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:

36

19  Data Handler gets an authorization key from 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.

This code sample shows how to push data to the client device in 4K chunks of data in the binary file using ASP.Net Custom Http Handler.

public void ProcessRequest(HttpContext context)

{

string httpHandlerEventLogSourceName =

ConfigurationManager.AppSettings["HttpHandlerEventLogSourceName"];

context.Response.Clear();

context.Response.ContentType = "application/octet-stream";

context.Response.Buffer = false;

context.Response.BufferOutput = false;

context.Response.AddHeader("Content-Disposition",

"attachment;filename=results");

using (Stream outputStream = new BufferedStream(context.Response.OutputStream, 0x4000))

{

//Instantiating Binary Writer

BinaryWriter writer = new BinaryWriter(outputStream);

//Write data

Writer.Write(“Some data”);

//Closing and Disposing BinaryWriter

writer.Close();

37

writer.Dispose();

}

outputStream.Flush();

context.Response.OutputStream.Flush();

context.Response.Flush();

context.Response.End();

}

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.

8 End to End Example Apportal end to end example for getting online data from backend to front end chart.

 This section covers a scenario to demonstrate an end to end example of obtaining and presenting data in a chart.

 WCF Data services is used, as the idea is to transfer summarized, filtered and reportable data which is just enough to bind it to the chart. WCF data services provide great querying capabilities and can expose the table as entities with all filtering capabilities through query strings.

 In this example, the below sales stage revenue data is in a database. The table name is ‘Sales Stage’

Region District ATU SalesLocation SalesStage Revenue USA - Central USA - Heartland HLD.001.Disp.CTM HLD.001.Disp.CTM Develop 20% 204,428 USA - Central USA - Heartland HLD.002.Disp.CAM HLD.002.Disp.CAM Solution 40% 294,293 USA - Central USA - Midwest MWA.001.Disp.CTM MWA.001.Disp.CTM Proof 60% 202,690 USA - Central USA - Midwest MWA.002.Disp.CTM MWA.002.Disp.CTM Close 80% 50,325 USA - East USA - MidAtlantic MAD.001.Dsip.CTM MAD.001.Dsip.CTM Develop 20% 21,658 USA - East USA - MidAtlantic MAD.002.Dsip.CTM MAD.002.Dsip.CTM Develop 20% 42,822 USA - East USA - NorthEast NED.003.Cent.CTM NED.002.Disp.CTM Develop 20% 35,940 USA - East USA - NorthEast NED.004.Cent.CTM NED.003.Cent.CTM Solution 40% 39,198 USA - East USA - NY Metro NYD.003.Disp.CAM NYD.003.Disp.CAM Proof 60% 829,633 USA - East USA - NY Metro NYD.003.Disp.CTM NYD.003.Disp.CTM Solution 40% 140,358 USA - West USA - Northwest NWD.002.Disp.CTM NWD.002.Disp.CTM Develop 20% 23,172 USA - West USA - Northwest NWD.003.Cent.CTM MWD.008.Cent.CAM Develop 20% 2,343

38

USA - West USA - Southwest SWD.002.MIX SWD.001.Disp.CTM Solution 40% 168,442 USA - West USA - Southwest SWD.002.Disp.CTM SWD.002.Disp.CTM Proof 60% 1,990

 The purpose is to expose this data to the client app and report the total sales stage revenue by Region.  The following MSDN article tells how to develop WCF data service with different application scenarios:

WCF Data Service Application Scenarios: http://msdn.microsoft.com/en-us/library/vstudio/dd672589(v=vs.110).aspx

 The below links will help in understanding how to create endpoints on a WCF data service to enable custom service behaviors:

How to define WCF Data service operation: http://msdn.microsoft.com/en-us/library/vstudio/dd744841(v=vs.103).aspx

Service Operation: http://msdn.microsoft.com/en-us/library/vstudio/cc668788(v=vs.103).aspx Creating an Entity

 For the above demo scenario, a developer can create an entity called “SalesStage” and expose this entity in SalesStages.svc WCF Data Service.  Please refer to how to expose entities in WCF Data Service here.  Sales Stage Entity

After exposing the SalesStages entity in SalesStages.svc , when browsing the service end point the SalesStages entity will be exposed in the SalesStages.svc . In Entity Framework, when an entity is a collection of entities the name is pluralized like SalesStages. When an entity is just one record the name is not pluralized.

39

OData  The below is a couple of ODATA queries from SalesStages.svc against SalesStages Entity.

http://localhost:9940/SalesStages.svc/SalesStages

http://localhost:9940/SalesStages.svc/SalesStages?filter=Region eq 'USA - East'

http://localhost:9940/SalesStages.svc/SalesStages?filter=Region eq 'USA - East'&District eq 'USA - Heartland'

http://localhost:9940/SalesStages.svc/SalesStages?filter=Region eq 'USA - East'&District eq 'USA - Heartland'$orderby=ATU

 The below MSDN article will assist in understanding how to access WCF Data Service resources

http://msdn.microsoft.com/en-us/library/dd728283(v=vs.110).aspx

 Now, from the windows 8 app, a developer can consume the WCF Data services by using WCF Data Services 5.0 for OData V3.  For detailed step by step by procedure on writing a Windows Store App that consumes an OData Service, check here.

Calling the WCF Data Service  This is the critical piece of code that calls the WCF data service and get the data to bind:

DataServiceEntities cockPitContext = new DataServiceEntities (new Uri(string.Format("http://localhost:9940/SalesStages.svc", Utilities.webserviceRoot))); var results = await Task.Factory.FromAsync>(query.BeginExecute, query.EndExecute, null); List SalesStageDataCollection = results.ToList();

 The data is now in a C# collection. The chart will show the revenue as a stacked bar chart as shown in Figure 22. It shows total/stacked sales stage revenue by Region on the x-Axis.

40

Figure 22 Binding the Data  To bind the aggregated data to the chart, a developer can use a model class like this: public class TotalRevenueByRegion {

public string Region { get; set; }

public string SalesStage { get; set; }

public double TotalRevenueAmount { get; set; }

}

 To aggregate the data at region level by using LINQ query as below: var totalRevenueByRegions = new ObservableCollection(

SalesStageDataCollection.GroupBy(r => new { r.Region, r.SalesStage }) .Select(result => new TotalRevenueByRegion() { Region = result.Key.Region, SalesStage = result.Key.SalesStage, TotalRevenueAmount = (double)result.Sum(r => r.Revenue) }).OrderBy(r => r.Region).OrderBy(r => r.SalesStage).ToList());

);

 The exact data is ready to be bound to the chart.  Here is the XAML code for the above chart control :

41

Text="{Binding}"

Margin="0,20,0,0"

FontSize="16.667"

Foreground="{StaticResource SalesCockpitForegroundStyle}"/>

Text="{Binding}"

Margin="0,0,0,0"

FontSize="16.667"

Foreground="{StaticResource SalesCockpitForegroundStyle}"/>

42

 Each series was added to the chart using the code behind. This can also be done through XAML binding.  To bind data thru code, a developer can use a generic model like this, which can be used across the app for different charts:

public class CockpitCategoricalDataPoint { public double Value { get; set; } public object Category { get; set; }

public string Tooltip { get; set; }

public string TooltipVisibility { get; set; }

public bool IsOpen { get; set; }

public string Label { get; set; }

public int ID { get; set; }

public string OpportunityID { get; set; }

}  Here is the core data binding logic.

foreach (IGrouping indicator in totalRevenueByRegions) { BarSeries series = new BarSeries(); series.IsHitTestVisible = true; series.CategoryBinding = new PropertyNameDataPointBinding("Category"); series.ValueBinding = new PropertyNameDataPointBinding("Value"); series.CombineMode = ChartSeriesCombineMode.Stack; series.LegendTitle = indicator.Key;

series.Background = new SolidColorBrush(Windows.UI.Colors.PaleVioletRed); Style style = new Style(typeof(Border)); style.Setters.Add(new Setter(Border.BackgroundProperty, new SolidColorBrush(Windows.UI.Colors.PaleVioletRed))); series.DefaultVisualStyle = style;

ChartSeriesLabelDefinition labelDefinition = new ChartSeriesLabelDefinition(); labelDefinition.HorizontalAlignment = HorizontalAlignment.Center;

43

labelDefinition.Binding = new PropertyNameDataPointBinding("Value"); labelDefinition.VerticalAlignment = VerticalAlignment.Center; labelDefinition.Format = "{0:C0}"; series.ShowLabels = true; series.LabelDefinitions.Add(labelDefinition);

categoricalDataPointcollection = new ObservableCollection();

foreach (TotalRevenueByGeoLevel item in indicator) { categoricalDataPointcollection.Add(new CockpitCategoricalDataPoint() { Tooltip = String.Format(CultureInfo.CurrentCulture, "Revenue: {0:C0}\nSales Stage: {1}", item.TotalRevenueAmount, indicator.Key), Value = item.TotalRevenueAmount, Category = item.AggregatedBy }); }

series.ItemsSource = categoricalDataPointcollection; this.pipelineBySalesStageBarChart.Series.Add(series); } 9 Deployment Windows 8 Modern UI applications are designed to be deployed through a public Windows Store. Typically, internal line of business applications need to be distributed within a limited and secure environment. To accomplish this, enterprises typically choose one of two environments: creating an internal Windows store or sideloading.

Internal Windows stores can be created internally to work just as the public Windows Store but access to applications are controlled by the enterprise.

Sideloading installs applications without going through a Windows Store. They do not need to be certified by Microsoft, but there are other restrictions, such as they must be signed with a certificate chained to a trusted root certificate and require specific global policy settings established on each device. Sideloading also requires the enterprise to devise their own process for distributing the installation bits to each device.

For more information about sideloading, see this MSDN article and this Technet article.

44