Tuesday, December 8, 2015

Building Charts using Invoke SharePoint REST API using HTTPClient in SharePoint Online

Building Charts using Invoke SharePoint REST API using HTTPClient in SharePoint Online.
High Chart Site : http://www.highcharts.com/.
First Create a SharePoint List called "Temperature" as shown below.
Open Visual Studio -> File -> New -> Project -> Installed -> Templates ->  Visual C#.
"WebApplication3" web application created. Add below required ddls.
Microsoft.SharePoint.Client.dll
Microsoft.SharePoint.Client.Runtime.dll 
Add one web page and JavaScript files as below.

go to "WebApplication3" -> "WebForm1.aspx" add below code.
--------------------------------------------------------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication3.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script type="text/javascript" src="https://code.highcharts.com/highcharts.js"></script>
    <script type="text/javascript" src="https://code.highcharts.com/modules/exporting.js"></script>
    <script type="text/javascript" src="JavaScript1.js"></script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:HiddenField ID="hdnFld1" runat="server" />
            <table>
                <tr>
                    <td>
                        <div id="div1"></div>
                    </td>
                    <td>
                        <div id="container"></div>
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>
--------------------------------------------------------------------
go to "WebApplication3" -> "WebForm1.aspx.cs" add below code.
--------------------------------------------------------------------
using System;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security;
namespace WebApplication3
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Task<string> result = getTemperatureListItems();
            result.Wait();
            hdnFld1.Value = result.Result;
        }
        private static async Task<string> getTemperatureListItems()
        {
            const string webUrl = "https://sreekanth2.sharepoint.com/";
            const string USER = "sreekanth@sreekanth2.onmicrosoft.com";
            const string PWD = "password";
            const string REST_URL = "{0}/_api/web/lists/getbytitle('Temperature')/Items?$select=ID,Month,Temperature,City";
            var passWord = new SecureString();
            foreach (var c in PWD)
            {
                passWord.AppendChar(c);
            }
            var credential = new SharePointOnlineCredentials(USER, passWord);
            using (var handler = new HttpClientHandler() { Credentials = credential })
            {
                Uri uri = new Uri(webUrl);
                handler.CookieContainer.SetCookies(uri, credential.GetAuthenticationCookie(uri));
                using (var client = new HttpClient(handler))
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    HttpResponseMessage response = await client.GetAsync(string.Format(REST_URL, webUrl)).ConfigureAwait(false);
                    response.EnsureSuccessStatusCode();
                    string jsonData = await response.Content.ReadAsStringAsync();
                    return jsonData;
                }
            }
        }
    }
}
--------------------------------------------------------------------
go to "WebApplication3" -> "JavaScript1.js" add below code.
--------------------------------------------------------------------
var arrayTemperatureListItems = [];
var arrayCity = [];
var arrarMonth = [];
var seriesData = [];
var tempArray = [];
var temCity;
$(document).ready(function () {
    var data = $("[id$=hdnFld1]").val();
    var jsonObject = JSON.parse(data);
    var listInfo = '';
    listInfo += "<table border='1'><tr><td>ID</td><td>City</td><td>Month</td><td>Temperature</td></tr>";
    for (var i = 0; i < jsonObject.value.length; i++) {
        listInfo += '<tr><td>' + jsonObject.value[i]['ID'] + "</td><td>" + jsonObject.value[i]['City'] + "</td><td>" + jsonObject.value[i]['Month'] + "</td><td>" + jsonObject.value[i]['Temperature'] + '</td></tr>';
        arrayCity.push(jsonObject.value[i]['City']);
        arrarMonth.push(jsonObject.value[i]['Month']);
        arrayTemperatureListItems.push([jsonObject.value[i]['City'], jsonObject.value[i]['Month'], jsonObject.value[i]['Temperature']]);
    }
    listInfo += "</tr></table>";
    document.getElementById("div1").innerHTML = 'List Items found:<br/>' + listInfo;
    arrayCity = jQuery.unique(arrayCity);
    arrayCity.reverse();
    arrarMonth = jQuery.unique(arrarMonth);
    arrarMonth.reverse();
    for (var i = 0; i < arrayCity.length; i++) {
        for (var j = 0; j < arrarMonth.length; j++) {
            for (var k = 0; k < arrayTemperatureListItems.length; k++) {
                if (arrayCity[i] == arrayTemperatureListItems[k][0] && arrarMonth[j] == arrayTemperatureListItems[k][1]) {
                    temCity = arrayCity[i];
                    tempArray.push(arrayTemperatureListItems[k][2]);
                }
            }
        }
        seriesData.push({ name: temCity, data: tempArray });
        temCity = "";
        tempArray = [];
    }
    showChart();
});
function showChart() {
    $('#container').highcharts({
        title: {
            text: 'Monthly Average Temperature',
            x: -20 //center
        },
        subtitle: {
            text: 'Source: Temperature List',
            x: -20
        },
        xAxis: {
            categories: arrarMonth
        },
        yAxis: {
            title: {
                text: 'Temperature (°C)'
            },
            plotLines: [{
                value: 0,
                width: 1,
                color: '#808080'
            }]
        },
        tooltip: {
            valueSuffix: '°C'
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'middle',
            borderWidth: 0
        },
        series: seriesData
    });
}
--------------------------------------------------------------------
now deploy(F5) and check.
--------------------------------------------------------------------

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