Friday, November 8, 2013

Northwind Traders Dashboard apps for SharePoint 2013, BCS Dashboard with REST apps for SharePoint 2013

vs2012 -> file -> new -> project c# -> office/SharePoint -> apps -> apps for SharePoint 2013 -> "BCSDashboardREST"

BCSDashboardREST -> Right Click -> Add -> 'Content Type for an External Data Source..'

BCSDashboardREST -> Script -> Add -> Existing Item -> "knockout-2.1.0.js" [we can download this js file from http://knockoutjs.com/ site]

BCSDashboardREST -> Script -> Add -> New Item -> select 'Java Script File' Template and name it as 'northwind.query.js'
Add below custom JavaScript code to 'northwind.query.js' file
"use strict";

var Northwind = window.Northwind || {};
Northwind.CategoryQuery = function () {
    var deferred = $.Deferred(),
        execute = function () {
            $.ajax({
                url: _spPageContextInfo.webServerRelativeUrl +
                    "/_api/lists/getByTitle('Categories')/items?$select=CategoryID,CategoryName",
                headers: {
                    "accept": "application/json;odata=verbose",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val()
                },
                success: onSuccess,
                error: onError
            });
            return deferred;
        },
        onSuccess = function (data) {
            deferred.resolve(data);
        },
        onError = function (err) {
            deferred.reject(err);
        };
    return {
        execute: execute
    }
}();

Northwind.CategorySalesQuery = function () {
    var deferred = $.Deferred(),
        execute = function (categoryName) {
            $.ajax({
                url: _spPageContextInfo.webServerRelativeUrl +
                    "/_api/lists/getByTitle('Category_Sales_for_1997')/items?$select=CategoryName,CategorySales&$filter=CategoryName eq '" +
                    categoryName + "'",
                headers: {
                    "accept": "application/json;odata=verbose",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val()
                },
                success: onSuccess,
                error: onError
            });
            deferred.categoryName = categoryName;
            return deferred;
        },
        onSuccess = function (data) {
            deferred.resolve(data);
        },
        onError = function (err) {
            deferred.reject(err);
        };
    return {
        execute: execute
    }
};

BCSDashboardREST -> Script -> Add -> New Item -> select 'Java Script File' Template and name it as 'northwind.viewmodel.js'
Add below custom JavaScript code to 'northwind.viewmodel.js' file
"use strict";

var Northwind = window.Northwind || {};
Northwind.Category = function (id, name) {
    var categoryId = id,
        get_categoryId = function () { return categoryId; },
        set_categoryId = function (v) { categoryId = v; },
        categoryName = name,
        get_categoryName = function () { return categoryName; },
        set_categoryName = function (v) { categoryName = v; };
    return {
        get_categoryName: get_categoryName,
        set_categoryName: set_categoryName,
        get_categoryId: get_categoryId,
        set_categoryId: set_categoryId
    }
}

Northwind.CategorySale = function (name, value) {
    var saleValue = value,
        get_saleValue = function () { return saleValue; },
        set_saleValue = function (v) { saleValue = v; },
        categoryName = name,
        get_categoryName = function () { return categoryName; },
        set_categoryName = function (v) { categoryName = v; };
    return {
        get_categoryName: get_categoryName,
        set_categoryName: set_categoryName,
        get_saleValue: get_saleValue,
        set_saleValue: set_saleValue
    }
}

Northwind.CategoryViewModel = function () {
    var categories = ko.observableArray(),
        get_categories = function () { return categories; },
        load = function () {
            Northwind.CategoryQuery.execute().promise().then(
                function (data) {
                    $.each(data.d.results, function (key, val) {
                        categories.push(new Northwind.Category(val.CategoryID, val.CategoryName));
                    });
                },
                function (err) {
                    alert(JSON.stringify(err));
                }
            );
        };
    return {
        load: load,
        get_categories: get_categories
    }
}();

Northwind.CategorySalesViewModel = function () {
    var categorySales = ko.observableArray(),
        get_categorySales = function () { return categorySales; },
        remove_categorySale = function (categoryName) {
            var categorySale = ko.utils.arrayFirst(categorySales(), function (currentCategorySale) {
                return currentCategorySale.get_categoryName() === categoryName;
            });
            if (categorySale) {
                categorySales.remove(categorySale);
            }
        },
        deferreds = [],
        load = function (categoryName) {
            var activeDeferred;
            for (var i = 0; i < deferreds.length; i++) {
                if (deferreds[i].categoryName === categoryName) {
                    activeDeferred = deferreds[i];
                    break;
                }
            }
            if (!activeDeferred) {
                activeDeferred = new Northwind.CategorySalesQuery().execute(categoryName);
                deferreds[deferreds.length] = activeDeferred;
            }
            activeDeferred.promise().then(
                function (data) {
                    $.each(data.d.results, function (key, val) {
                        categorySales.push(new Northwind.CategorySale(
                                           val.CategoryName,
                                           Northwind.Utilities.formatCurrency(val.CategorySales)));
                    });
                },
                function (err) {
                    alert(JSON.stringify(err));
                }
            );
        };
    return {
        load: load,
        get_categorySales: get_categorySales,
        remove_categorySale: remove_categorySale
    }
}();

Northwind.Utilities = function () {
    var formatCurrency = function (amount) {
        var i = parseFloat(amount);
        if (isNaN(i)) { i = 0.00; }
        var minus = '';
        if (i < 0) { minus = '-'; }
        i = Math.abs(i);
        i = parseInt((i + .005) * 100);
        i = i / 100;
        var s = new String(i);
        if (s.indexOf('.') < 0) { s += '.00'; }
        if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
        s = minus + s;
        s = "$" + formatCommas(s);
        return s;
    },
    formatCommas = function (amount) {
        var delimiter = ",";
        amount = new String(amount);
        var a = amount.split('.', 2)
        var d = a[1];
        var i = parseInt(a[0]);
        if (isNaN(i)) { return ''; }
        var minus = '';
        if (i < 0) { minus = '-'; }
        i = Math.abs(i);
        var n = new String(i);
        var a = [];
        while (n.length > 3) {
            var nn = n.substr(n.length - 3);
            a.unshift(nn);
            n = n.substr(0, n.length - 3);
        }
        if (n.length > 0) { a.unshift(n); }
        n = a.join(delimiter);
        if (d.length < 1) { amount = n; }
        else { amount = n + '.' + d; }
        amount = minus + amount;
        return amount;
    };
    return {
        formatCurrency: formatCurrency
    }

}();

BCSDashboardREST -> Pages -> Default.aspx 
Add javascript file references to 'PlaceHolderAdditionalPageHead' place holder
<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <script type="text/javascript" src="../Scripts/jquery-1.8.2.min.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.js"></script>

    <script type="text/javascript" src="../Scripts/knockout-2.1.0.js"></script>
    <script type="text/javascript" src="../Scripts/northwind.query.js"></script>
    <script type="text/javascript" src="../Scripts/northwind.viewmodel.js"></script>

    <!-- Add your CSS styles to the following file -->
    <link rel="Stylesheet" type="text/css" href="../Content/App.css" />

    <!-- Add your JavaScript to the following file -->
    <script type="text/javascript" src="../Scripts/App.js"></script>
</asp:Content>

BCSDashboardREST -> Pages -> Default.aspx 
Add custom code to 'PlaceHolderMain' place holder
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <div>
        <p id="message">
            initializing...
        </p>
    </div>
    <div class="dashboard-Container">
        <div class="dashboard-Title">Northwind Traders Dashboard</div>
        <div class="dashboard-Left">
            <div class="dashboard-Header">Categories</div>
            <div>
                <ul id="categoryList" data-bind="foreach: get_categories()">
                    <li>
                        <input type="checkbox" />
                        <span data-bind="text: get_categoryName()"></span>
                    </li>
                </ul>
            </div>
        </div>
        <div class="dashboard-Right">
            <div class="dashboard-Header">Sales Figures</div>
            <div>
                <table id="salesTable">
                    <thead>
                        <tr>
                            <th>Category</th>
                            <th>Sales</th>
                        </tr>
                    </thead>
                    <tbody id="salesTableBody" data-bind="foreach: get_categorySales()">
                        <tr>
                            <td data-bind="text: get_categoryName()"></td>
                            <td data-bind="text: get_saleValue()"></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</asp:Content>

BCSDashboardREST -> Scripts -> App.js
Add below custom javascript code to App.js file
'use strict';
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
var Northwind = window.Northwind || {};
$(document).ready(function () {
    getUserName();
    $("input").live("click", function (e) {
        if ($(this).attr("type") === "checkbox") {
            if ($(this).attr("checked") === "checked") {
                Northwind.CategorySalesViewModel.load($(this).siblings().first().text());
            }
            else {
                Northwind.CategorySalesViewModel.remove_categorySale($(this).siblings().first().text());
            }
        }
    });
    Northwind.CategoryViewModel.load();
    ko.applyBindings(Northwind.CategoryViewModel, $get("categoryList"))
    ko.applyBindings(Northwind.CategorySalesViewModel, $get("salesTableBody"))
});
function getUserName() {
    context.load(user);
    context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}
function onGetUserNameSuccess() {
    $('#message').text('Hello ' + user.get_title());
}
function onGetUserNameFail(sender, args) {
    alert('Failed to get user name. Error:' + args.get_message());
}

BCSDashboardREST -> Content -> App.css
Add below custom css to App.css file
#categoryList {
    list-style-type:none;
    color: #039;
}
.dashboard-Container {
    height:300px;
    width:600px;
    margin-top:20px;
       font-family: "Lucida Sans Unicode", "Lucida Grande", Sans-Serif;
}
.dashboard-Title {
    font-size:20px;
    margin-bottom:15px;
}
.dashboard-Left {
    float:left;
}
.dashboard-Right {
    float:right;
}
.dashboard-Header {
    font-size:14px;
    font-weight:bold;
    margin-bottom:10px;
    color: #039;
}
#salesTable
{
       font-size: 12px;
       background: #fff;
       margin: 0px;
       width: 100%;
       border-collapse: collapse;
       text-align: center;
}
#salesTable th
{
       font-size: 12px;
       font-weight: normal;
    color: #039;
       padding: 10px 8px;
       border-bottom: 2px solid #6678b1;
}
#salesTable td
{
    color: #669;
       padding: 18px 16px 0px 16px;
}

#salesTable tbody tr:hover td
{
       color: #009;
}

BCSDashboardREST -> Right Click -> Deploy
Thank You.

No comments:

Post a Comment

Featured Post

Sent Email in C#

Sent Email in C# : //Option 1: using S ystem; using System.Net.Mail; using System.Security; using System.Text; using System.Threading.T...

Popular posts