Showing posts with label JS. Show all posts
Showing posts with label JS. Show all posts

Wednesday, November 27, 2013

MVVM – Windows 8 Store App using HTML5/WinJS Primer

MVVM – Windows 8 Store App using HTML5/WinJS Primer
 
Purpose: The purpose of this document is to illustrate how to how to apply MVVM (Model-View-ViewModel) architectural pattern when developing Windows 8 Store Product catalog App using HTML5/WinJS
 
Challenge: You may need to develop a modern application integrated with Microsoft Dynamics AX 2012 for the purposes of demonstration, POC or to be deployed in production environment. The question is what technology and architectural pattern to use in order to facilitate application development and maintenance efforts  
 
Solution: In this scenario we'll develop Windows 8 Store App using HMTL5/WinJS
 
Walkthrough
 
First off let's create a new project using Other Languages > JavaScript > Windows Store > Blank App template
 
New Project
 
 
Then we'll apply MVVM (Model-View-ViewModel) architectural pattern for development of Product catalog app
 
Solution Explorer
 
 
Please note that Windows provides two sets of APIs for building Windows Store apps: the Windows Runtime and the Windows Library for JavaScript. Windows Runtime JavaScript, C#, Visual Basic, and C++ APIs provide access to all core platform features. WinJS JavaScript APIs provide controls, CSS styles, and helper functions that help you write object-oriented code. The WinJS namespace covers functionality that is similar to the Windows.UI.XAML namespaces in the Windows Runtime.
 
By other words WinJS is essentially JavaScript library developed by Microsoft which greatly facilitates your efforts in building authentic Windows 8 apps
 
Now let's review how I implemented Model, View and ViewModel
 
The model encapsulates business logic and data. Please see below how I define Product class (define) which has 2 attributes: ID and Name as a part of the model. For this purpose I introduce WinJS Namespace "Products" and declare Product class. Please find more info about WinJS Namespaces here: http://msdn.microsoft.com/en-us/library/windows/apps/hh967793.aspx
 
The view model encapsulates presentation logic and state. Please see below how I introduce another WinJS Namespace "ProductsViewModel", declare products variable and assign the list of products to it
 
Model and ViewModel: WinJS
 
// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
    "use strict";
 
    WinJS.Binding.optimizeBindingReferences = true;
 
    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;
 
    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }
            args.setPromise(WinJS.UI.processAll());
        }
    };
 
    app.oncheckpoint = function (args) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. You might use the
        // WinJS.Application.sessionState object, which is automatically
        // saved and restored across suspension. If you need to complete an
        // asynchronous operation before your application is suspended, call
        // args.setPromise().
    };
 
    WinJS.Namespace.define("Products", {
        Product: WinJS.Class.define(function (id, name) {
            this.id = id;
            this.name = name;
        })
    });
 
    var productsList = new WinJS.Binding.List();
    productsList.push(new Products.Product("X", "AlexProductX"));
 
    WinJS.Namespace.define("ProductsViewModel", { products: productsList });
 
    app.start();
})();
 
 
Please note that Model and ViewModel definition is done using WinJS Namespaces
MVVM (Model-View-ViewModel) pattern implementation using WinJS conceptually will look similar to classic object-oriented languages such as C#.NET because we can introduce Namespaces and define necessary Classes. Please note that pure JavaScript (JS) does not have a notion of class, but it does have a notion of object
 
Now let's review a view
 
Important to mention is that in order to link view and view model by means of binding I used standard capabilities of WinJS library (data-win-bind property). Please find more info about data-win-bind property here: http://msdn.microsoft.com/en-us/library/windows/apps/hh440968.aspx
You will also notice that I'm using more WinJS properties such as data-win-control, data-win-options, etc. For example, using data-win-control property I define that <div> will behave as ListView (WinJS.UI.ListView). ListView is one of standard controls in WinJS library for Windows 8 apps. Please find more info about ListView control here: http://msdn.microsoft.com/en-us/library/windows/apps/br211837.aspx
 
The view encapsulates the UI and any UI logic (specifically binding details). Please see below how easy it is to bind appropriate view model elements with UI controls for display. All I had to do was to specify the data source using win-data-options property and then implement binding using win-data-bind property. You will also notice that I applied a template to display catalog products in a form of grid
 
View: HTML
 
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Products</title>
 
    <!-- WinJS references -->
    <link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet" />
    <script src="//Microsoft.WinJS.1.0/js/base.js"></script>
    <script src="//Microsoft.WinJS.1.0/js/ui.js"></script>
 
    <!-- App3 references -->
    <link href="/css/default.css" rel="stylesheet" />
    <script src="/js/default.js"></script>
</head>
<body>
    <h1>Products</h1>
    <div id="mediumListIconTextTemplate" data-win-control="WinJS.Binding.Template">
        <div style="width: 282px; height: 70px; padding: 5px; overflow: hidden; display: -ms-grid;">       
            <div style="margin: 5px; -ms-grid-column: 2">
                <h4 data-win-bind="innerText: id"></h4>
                <h6 data-win-bind="innerText: name"></h6>
            </div>
        </div>
    </div>
    <div id="basicListView" data-win-control="WinJS.UI.ListView"
        data-win-options="{itemDataSource : ProductsViewModel.products.dataSource,
        itemTemplate: select('#mediumListIconTextTemplate'),
        layout : {type: WinJS.UI.GridLayout}}">
    </div>
</body>
</html>
 
Please note that I also did one small change to CSS file to define background color (darkgrey)
 
Style: CSS (Default.css)
 
body {
    background-color: darkgrey;
}
 
@media screen and (-ms-view-state: fullscreen-landscape) {
}
 
@media screen and (-ms-view-state: filled) {
}
 
@media screen and (-ms-view-state: snapped) {
}
 
@media screen and (-ms-view-state: fullscreen-portrait) {
}
 
 
Please note that for each product I display its product ID and Name, and the style of ListView elements is pre-defined by WinJS library that's why I didn't even need to style ListView in CSS
As the result our Product catalog application will look like below
 
Result
 
 
Please review the following article to learn how to quickly connect your application to Microsoft Dynamics AX 2012 Demo VM to test out the integration: http://ax2012aifintegration.blogspot.com/2013/04/microsoft-dynamics-ax-2012-windows-8.html
 
In case you are developing a mobile application for production please review the best practice guidance on Developing Mobile apps for Microsoft Dynamics AX 2012 here: http://www.microsoft.com/en-us/download/details.aspx?id=38413
 
Summary: This document describes how to apply MVVM (Model-View-ViewModel) architectural pattern when developing Windows 8 Store Product catalog sample App using HTML5/WinJS.
 
Author: Alex Anikiev, PhD, MCP
 
Tags: MVVM, Model-View-ViewModel, Windows 8 Store App, HTML5, WinJS, JavaScript, JS, Microsoft Dynamics AX 2012.
 
Note: This document is intended for information purposes only, presented as it is with no warranties from the author. This document may be updated with more content to better outline the concepts and describe the examples.

Monday, November 18, 2013

MVVM – Windows Phone 8 App using HTML5/JavaScript Primer

MVVM – Windows Phone 8 App using HTML5/JavaScript Primer
 
Purpose: The purpose of this document is to illustrate how to how to apply MVVM (Model-View-ViewModel) architectural pattern when developing Windows Phone 8 Product catalog App using HTML5/JavaScript
 
Challenge: You may need to develop a modern application integrated with Microsoft Dynamics AX 2012 for the purposes of demonstration, POC or to be deployed in production environment. The question is what technology and architectural pattern to use in order to facilitate application development and maintenance efforts        
 
Solution: In this scenario we'll develop Windows Phone 8 App using HMTL5/JavaScript based on Windows Phone HTML5 App template
 
Walkthrough
 
First off let's create a new project using Visual C# > Windows Phone > Windows Phone HTML5 App template
 
New Project
 
 
Please note that essentially it is C#.NET App which wraps up HTML5 code with Web browser control. As opposed to Windows Store Apps written in HTML5/JavaScript where JavaScript (WinJS) is hosted in Windows runtime/OS, Windows Phone 8 Apps written in HTML5/JavaScript are not natively integrated with OS 
 
Solution Explorer
 
 
Then we'll apply MVVM (Model-View-ViewModel) architectural pattern for development of Product catalog app
 
Solution Explorer
 
 
In order to execute JavaScript in Web browser control in Windows Phone 8 App I'll need to enable scripting (IsScriptEnabled="true") as showed below
 
MainPage.xaml
 
<phone:PhoneApplicationPage
    x:Class="HTML5App1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">
 
    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <phone:WebBrowser x:Name="Browser"
                          HorizontalAlignment="Stretch"
                          VerticalAlignment="Stretch"
                          Loaded="Browser_Loaded"
                          NavigationFailed="Browser_NavigationFailed"
                          IsScriptEnabled="true" />
    </Grid>
 
    <!-- ApplicationBar -->
    <phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True" Mode="Minimized">
            <shell:ApplicationBarIconButton IconUri="/Assets/AppBar/appbar.back.rest.png" IsEnabled="True" Text="back" Click="BackApplicationBar_Click"/>
            <shell:ApplicationBarIconButton IconUri="/Assets/AppBar/appbar.next.rest.png" IsEnabled="True" Text="forward" Click="ForwardApplicationBar_Click"/>
            <shell:ApplicationBar.MenuItems>
                <shell:ApplicationBarMenuItem Text="home" Click="HomeMenuItem_Click" />
            </shell:ApplicationBar.MenuItems>
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>
 
</phone:PhoneApplicationPage>
 
As soon as I'm not going to use ApplicationBar I can delete this entire section
Please note that index.html will look like this by default and I'm going to change it later
 
index.html
 
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <link rel="stylesheet" type="text/css" href="/html/css/phone.css" />
        <title>Windows Phone</title>
    </head>
    <body>
        <div>
            <p>MY APPLICATION</p>
        </div>
        <div id="page-title">
            <p>page title</p>
        </div>
    </body>
</html>
 
Now let's review how I implemented Model, View and ViewModel
The model encapsulates business logic and data. Please see below how I define Product object (function) which has 2 attributes: ID and Name as a part of the model
 
The view model encapsulates presentation logic and state. Please see below how I define ObservableArray of products with respective function(s) (GetProducts) as a part of the view model
 
Model and ViewModel:  JS (JavaScript.js)
function Product(id, name) {
    var self = this;
    self.id = ko.observable(id);
    self.name = ko.observable(name);
}
 
function ProductViewModel() {
    var self = this;
    self.products = ko.observableArray();
    self.GetProducts = function () {
        self.products.push(new Product("X", "AlexProductX"));
    }
}
 
Please note that Model and ViewModel definition is done in JavaScript (JS)
MVVM (Model-View-ViewModel) pattern implementation is different in JavaScript (JS) comparing to classic object-oriented languages such as C#.NET. Please note that JavaScript (JS) has objects which can contain data and methods that act upon that data. Objects can contain other objects. JavaScript (JS) does not have classes, but it does have constructors which do what classes do, including acting as containers for class variables and methods. JavaScript (JS) does not have class-oriented inheritance, but it does have prototype-oriented inheritance
 
Now let's review a view
 
Important to mention is that in order to link view and view model by means of binding I used the capabilities of knockout.js JavaScript (JS) library
 
Knockout (ko) is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically (e.g., changing depending on the user's actions or when an external data source changes), Knockout (ko) can help you implement it more simply and maintainably
 
Please find more info about Knockout (ko) JavaScript (JS) library here: http://knockoutjs.com
 
The view encapsulates the UI and any UI logic, and this is when I changed index.html populated by default from the template. Please see below how I iterate through the list of products and map view model object properties with elements of UI for display
 
View: HTML (index.html)
 
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Product Catalog</title>       
    <script src="js/jquery-1.10.2.min.js"></script>
   <script src="js/knockout-2.3.0.js"></script>
    <script src="js/JavaScript.js"></script>
    <script>
        $(document).ready(function () {
            var productViewModel = new ProductViewModel();
            productViewModel.GetProducts();
            ko.applyBindings(productViewModel);
        })
    </script>  
    <link href="css/StyleSheet.css" rel="stylesheet" />
</head>
<body>
<h1>Product Catalog</h1>
<table>   
    <tbody data-bind="foreach: products">
        <tr>
            <td id="id" data-bind="text: id"></td>
            <td id="name" data-bind="text: name"></td>
        </tr>   
    </tbody>
</table>
</body>
</html>
 
Please note that I also used JQuery JavaScript (JS) library because it is needed to be able to use $document variable. jQuery is a multi-browser (cf. cross-browser) JavaScript library designed to simplify the client-side scripting of HTML. Please find more info about JQuery JavaScript (JS) library here: http://jquery.com
 
Please note that I created a CSS file to define a style
 
Style: CSS (StyleSheet.css)
 
table {
   margin-top: 50px;
   margin-left: 50px;
}
td {
   border-width:1px;
   border-style: solid;
   height: 100px;
   text-align: center;
}
#id {
   width: 100px;
   color: white;
   background-color: black;
}
#name {
   width: 400px;
   color: black;
   background-color: white;
}
 
Please note that I defined different styles to display product ID and Name
As the result our Product catalog application will look like below
 
Result
 
 
Please review the following article to learn how to quickly connect your application to Microsoft Dynamics AX 2012 to test out the integration: http://ax2012aifintegration.blogspot.com/2013/04/microsoft-dynamics-ax-2012-windows-8.html
 
In case you are developing a mobile application for production please review the best practice guidance on Developing Mobile apps for Microsoft Dynamics AX 2012 here: http://www.microsoft.com/en-us/download/details.aspx?id=38413
 
Summary: This document describes how to apply MVVM (Model-View-ViewModel) architectural pattern when developing Product catalog sample Windows Phone 8 App using HTML5/JavaScript.
 
Author: Alex Anikiev, PhD, MCP
 
Tags: MVVM, Model-View-ViewModel, Windows Phone 8 App, HTML5, JavaScript, JS, Microsoft Dynamics AX 2012.
 
Note: This document is intended for information purposes only, presented as it is with no warranties from the author. This document may be updated with more content to better outline the concepts and describe the examples.