Thursday, December 17, 2015

Authenticating .NET Client Object Model CSOM in Office 365 in SharePoint 2013

Authenticating .NET Client Object Model CSOM in Office 365 in SharePoint 2013
--------------------------------------------------------
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            const string webUrl = "https://sreekanth2.sharepoint.com/";
            const string USER = "sreekanth@sreekanth2.onmicrosoft.com";
            const string PWD = "password";
            var listInfo = ""; 
            using (ClientContext clientContext = new ClientContext(webUrl))
            {
                SecureString passWord = new SecureString();
                foreach (char c in PWD.ToCharArray())
                {
                    passWord.AppendChar(c);
                }
                clientContext.Credentials = new SharePointOnlineCredentials(USER, passWord);
                Microsoft.SharePoint.Client.List spList = clientContext.Web.Lists.GetByTitle("Temperature");
                clientContext.Load(spList);
                clientContext.ExecuteQuery();
                if (spList != null && spList.ItemCount > 0)
                {
                    Microsoft.SharePoint.Client.CamlQuery camlQuery = new CamlQuery();
                    camlQuery.ViewXml = @"<View><Query><Where><IsNotNull><FieldRef Name='ID' /></IsNotNull></Where><OrderBy><FieldRef Name='ID' /></OrderBy></Query><ViewFields><FieldRef Name='ID' /><FieldRef Name='City' /><FieldRef Name='Month' /><FieldRef Name='Temperature' /></ViewFields></View>";
                    SP.ListItemCollection listItems = spList.GetItems(camlQuery);
                    clientContext.Load(listItems);
                    clientContext.ExecuteQuery();
                    listInfo += "<table border='1'><tr><td>ID</td><td>City</td><td>Month</td><td>Temperature</td></tr>";
                    foreach (SP.ListItem oListItem in listItems)
                    {
                        listInfo += "<tr><td>" + oListItem.Id + "</td><td>" + oListItem["City"] + "</td><td>" + oListItem["Month"] + "</td><td>" + oListItem["Temperature"] + "</td></tr>";
                    }
                    listInfo += "</tr></table>";
                    div1.InnerHtml = "List Items found:<br/>" + listInfo;
                }
            }
        }
    }
}
--------------------------------------------------------
--------------------------------------------------------

Bulk Upload Files to SharePoint remotely using CSOM in SharePoint Online

Bulk Upload Files to SharePoint remotely using CSOM in SharePoint Online
Using PowerShell: https://gallery.technet.microsoft.com/PowerShell-Bulk-Upload-b9e9d600
------------------------------------------------------------------------------------------------
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;
using System;
using System.IO;
using System.Linq;
using System.Security;
namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        const string webUrl = "https://sreekanth2.sharepoint.com/";
        const string USER = "sreekanth@sreekanth2.onmicrosoft.com";
        const string PWD = "Password";
        const string parent_dir = @"D:\ToUploadFilesFolder";
        const string listTitle = "MyDocuments"; // Library Display Name and Url should be same.
        public string parent_folderName = "";
        public string sub_folderName = "";
        public string fileName = "";
        public string file_relativeUrl = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            using (ClientContext clientContext = new ClientContext(webUrl))
            {
                SecureString passWord = new SecureString();
                foreach (char c in PWD.ToCharArray())
                {
                    passWord.AppendChar(c);
                }
                clientContext.Credentials = new SharePointOnlineCredentials(USER, passWord);
                var arrayfolderName = parent_dir.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
                parent_folderName = arrayfolderName[arrayfolderName.Length - 1];
                if (!FolderExists(clientContext.Web, listTitle, parent_folderName))
                {
                    CreateFolder(clientContext.Web, listTitle, parent_folderName);
                }
                DirSearch(clientContext, parent_dir);
            }
        }
        private void DirSearch(ClientContext clientContext, string dir)
        {
            try
            {
                foreach (string f in Directory.GetFiles(dir))
                {
                    fileName = f.Split(new string[] { dir }, StringSplitOptions.RemoveEmptyEntries)[0].Replace("\\", "/");
                    file_relativeUrl = parent_folderName + "/" + f.Split(new string[] { parent_dir + "\\" }, StringSplitOptions.RemoveEmptyEntries)[0].Replace("\\", "/");
                    //div1.InnerHtml += "/" + file_relativeUrl + "</br>";
                    using (FileStream fs = new FileStream(dir + "\\" + fileName, FileMode.Open))
                    {
                        SP.File.SaveBinaryDirect(clientContext, "/" + listTitle + "/" + file_relativeUrl, fs, true);
                    }
                }
                foreach (string d in Directory.GetDirectories(dir))
                {
                    sub_folderName = d.Split(new string[] { parent_dir + "\\" }, StringSplitOptions.RemoveEmptyEntries)[0].Replace("\\", "/");
                    //div1.InnerHtml += parent_folderName + "/" + sub_folderName + "</br>";
                    if (!FolderExists(clientContext.Web, listTitle, parent_folderName + "/" + sub_folderName))
                    {
                        CreateFolder(clientContext.Web, listTitle, parent_folderName + "/" + sub_folderName);
                    }
                    DirSearch(clientContext, d);
                }
            }
            catch (System.Exception ex)
            {
                div1.InnerHtml += ex.Message + " " + ex.StackTrace;
            }
        }
        public static bool FolderExists(Web web, string listTitle, string folderUrl)
        {
            var list = web.Lists.GetByTitle(listTitle);
            var folders = list.GetItems(CamlQuery.CreateAllFoldersQuery());
            web.Context.Load(list.RootFolder);
            web.Context.Load(folders);
            web.Context.ExecuteQuery();
            var folderRelativeUrl = string.Format("/{0}/{1}", list.RootFolder.Name, folderUrl);
            return Enumerable.Any(folders, folderItem => (string)folderItem["FileRef"] == folderRelativeUrl);
        }
        private static void CreateFolder(Web web, string listTitle, string folderName)
        {
            var list = web.Lists.GetByTitle(listTitle);
            var folderCreateInfo = new ListItemCreationInformation
            {
                UnderlyingObjectType = FileSystemObjectType.Folder,
                LeafName = folderName
            };
            var folderItem = list.AddItem(folderCreateInfo);
            folderItem.Update();
            web.Context.ExecuteQuery();
        }
    }
}
------------------------------------------------------------------------------------------------

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

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