Sunday, November 10, 2013

SharePoint 2013 Visualize data from a SharePoint list in an app

SharePoint 2013 Visualize data from a SharePoint list in an app
http://code.msdn.microsoft.com/office/SharePoint-2013-Visualize-1b15aa69
vs2012 -> file -> new -> project c# -> office/SharePoint -> apps -> apps for SharePoint 2013 -> "SP_SharePointDataVisualization_js"

SP_SharePointDataVisualization_js -> Right Click -> Add -> New Item -> Select 'List' Template and give name it as "PopulationData"

SP_SharePointDataVisualization_js -> Double Click "PopulationData" List
Now Add new column "Country"(Single Line of Text)(Required) and "Population"(Single Line Text)(Required)
Delete default Title column by right click on column and select delete option.

SP_SharePointDataVisualization_js -> PopulationData -> PopulationDataInstance -> Elements.xml
Add some custom date to list instance
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <ListInstance Title="PopulationData" OnQuickLaunch="TRUE" TemplateType="10000" Url="Lists/PopulationData" Description="My List Instance">
         <Data>
                <Rows>
                       <Row>
                             <Field Name="Country">China</Field>
                             <Field Name="Population">1347350000</Field>
                       </Row>
                       <Row>
                             <Field Name="Country">Brazil</Field>
                             <Field Name="Population">193946886</Field>
                       </Row>
                       <Row>
                             <Field Name="Country">Japan</Field>
                             <Field Name="Population">127530000</Field>
                       </Row>
                       <Row>
                             <Field Name="Country">Indonesia</Field>
                             <Field Name="Population">237641326</Field>
                       </Row>
                       <Row>
                             <Field Name="Country">Russia</Field>
                             <Field Name="Population">143300000</Field>
                       </Row>
                       <Row>
                             <Field Name="Country">Pakistan</Field>
                             <Field Name="Population">181319000</Field>
                       </Row>
                       <Row>
                             <Field Name="Country">Bangladesh</Field>
                             <Field Name="Population">152518015</Field>
                       </Row>
                       <Row>
                             <Field Name="Country">India</Field>
                             <Field Name="Population">1210193422</Field>
                       </Row>
                       <Row>
                             <Field Name="Country">Nigeria</Field>
                             <Field Name="Population">167629000</Field>
                       </Row>
                       <Row>
                             <Field Name="Country">USA</Field>
                             <Field Name="Population">314826000</Field>
                       </Row>
                </Rows>
         </Data>
  </ListInstance>
</Elements>

SP_SharePointDataVisualization_js -> Pages -> Default.aspx
Add below custom code to "PlaceHolderMain" place holder in Default.aspx page
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <div>
        <p id="message">
            initializing...
        </p>
    </div>
    <div id="Div1" style="float: left; width: 300px; height: 400px;">
        Top 10 Countries by Population:
        <input type="button" id="viewStacked" onclick="stack();" runat="server" value="Visualize Stacked" />
        <input type="button" id="viewTiled" onclick="tile();" runat="server" value="Visualize Tiled" />
    </div>
    <div id="populationVisualization" style="float: left; width: 500px; height: 800px;">
    </div>
    <div id="populationData" style="float: right;">
    </div>
</asp:Content>

SP_SharePointDataVisualization_js -> Scripts -> App.js
Add below custom javascript code to App.js file
'use strict';
var context;
var list;
var listItems;
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();

$(document).ready(function () {
    getUserName();
    context = new SP.ClientContext.get_current();
    list = context.get_web().get_lists().getByTitle('PopulationData');
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View><RowLimit>10</RowLimit></View>');
    listItems = list.getItems(camlQuery);
    context.load(listItems, 'Include(Country, Population)');
    context.executeQueryAsync(
        function () {
            startTable();
        },
        function (sender, args) {
            var dataArea = document.getElementById("populationData");
            while (dataArea.hasChildNodes()) {
                dataArea.removeChild(dataArea.lastChild);
            }
            dataArea.appendChild(document.createTextNode("Failed to get population data. Error: " + args.get_message()));
        });
}); 
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());
} 
function startTable() {
    var tableArea = document.getElementById("populationData");
    while (tableArea.hasChildNodes()) {
        tableArea.removeChild(tableArea.lastChild);
    }
    var leftColumn = document.createElement("div");
    leftColumn.setAttribute("style", "float:left;width:100px;background-color:#AFAFAF");
    var rightColumn = document.createElement("div");
    rightColumn.setAttribute("style", "float:left;width:100px;background-color:#FAFAFA");
    var listItemEnumerator = listItems.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var listItem = listItemEnumerator.get_current();
        var countryName = listItem.get_fieldValues()["Country"];
        var countryPopulation = listItem.get_fieldValues()["Population"];
        var countryLabel = document.createElement("div");
        countryLabel.setAttribute("style", "float:none;margin:5px;height:25px;width:120px;background-color:#AFAFAF;color:#FFFFFF");
        countryLabel.appendChild(document.createTextNode(countryName));
        leftColumn.appendChild(countryLabel);
        var populationLabel = document.createElement("div");
        populationLabel.setAttribute("style", "float:none;margin:5px;height:25px;width:120px;background-color:#FAFAFA");
        populationLabel.appendChild(document.createTextNode(countryPopulation));
        rightColumn.appendChild(populationLabel);
    }
    tableArea.appendChild(leftColumn);
    tableArea.appendChild(rightColumn);
}
function stack() {
    buildChart("Stacked");
}
function tile() {
    buildChart("Tiled");
}
function buildChart(visualSetting) {
    var chartArea = document.getElementById("populationVisualization");
    while (chartArea.hasChildNodes()) {
        chartArea.removeChild(chartArea.lastChild);
    }
    var countryData = [];
    var listItemEnumerator = listItems.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var listItem = listItemEnumerator.get_current();
        var countryName = listItem.get_fieldValues()["Country"];
        var countryPopulation = listItem.get_fieldValues()["Population"];
        countryData.push({ "countryName": countryName, "population": countryPopulation });
    }
    var tempData = countryData.slice(0);
    tempData.sort(sort_by('population', true, parseInt));
    var largestPopulation = tempData[0].population;
    if (visualSetting == "Stacked") {
        countryData.sort(sort_by('population', true, parseInt));
    }
    var countryCount = countryData.length;
    for (var country = 0; country < countryCount; country++) {
        var proportionalSize;
        if (visualSetting == "Stacked") {
            proportionalSize = Math.sqrt((countryData[country].population / largestPopulation) * 160000);
        }
        else {
            proportionalSize = Math.sqrt((countryData[country].population / largestPopulation) * 50000);
        }
        var countryDiv = document.createElement("div");
        if (visualSetting == "Stacked") {
            countryDiv.setAttribute("style", "text-align:right;color:#ffffff;padding:10px;margin:10px;float:left;width:"
                + proportionalSize + "px;height:"
                + proportionalSize + "px;background-color:#00"
                + (100 + (parseInt((155 / countryCount) * country))).toString(16) + "00");
        }
        else {
            countryDiv.setAttribute("style", "text-align:right;color:#ffffff;padding:5px;margin:2px;float:left;width:"
                + proportionalSize + "px;height:"
                + proportionalSize + "px;background-color:#00"
                + (100 + (parseInt((155 / countryCount) * country))).toString(16) + "00");
        }
        countryDiv.setAttribute("title", countryData[country].population);
        countryDiv.appendChild(document.createTextNode(countryData[country].countryName));
        chartArea.appendChild(countryDiv);
        if (visualSetting == "Stacked") {
            chartArea = countryDiv;
        }
    }
}
var sort_by = function (field, reverse, primer) {
    var key = function (country) { return primer ? primer(country[field]) : country[field] };
    return function (a, b) {
        var A = key(a), B = key(b);
        return ((A < B) ? -1 : (A > B) ? +1 : 0) * [-1, 1][+!reverse];
    }
}

SP_SharePointDataVisualization_js -> Right Click -> Deploy  
 
 
Thank You.

No comments:

Post a Comment

Featured Post

Protect an API by using OAuth 2.0 with Azure Active Directory and API Management

Protect an API by using OAuth 2.0 with Azure Active Directory and API Management https://docs.microsoft.com/en-us/azure/api-management/api-...

Popular posts