Friday, February 3, 2017

Change Language for current user with JSOM in SharePoint Online

Hi,

Here is code which can change language for current user with JSOM :


<script type="text/javascript" charset="utf8" src="/sites/BizDev/Style%20Library/SPS/jquery-1.11.3.min.js"></script>
<select id='LangSelect' onchange="SetUserLanguage(this.value);"></select>

<script type="text/javascript">

function SetUserLanguage(lCode)
{
    var call = $.ajax({
            url: _spPageContextInfo.siteAbsoluteUrl + "/_api/Web/Lists/GetByTitle('Languages')/items?" + "$select=Title,Code,LCode,ID&$top=5000&$filter=Code eq "+lCode,
            type: "GET",
            dataType: "json",
            headers: {
                Accept: "application/json;odata=verbose"
            }
        });

        call.done(function (data, textStatus, jqXHR) {
            var multipleValues = [];
            for (var i=0;i<data.d.results.length;i++){
                console.log(data.d.results[i].LCode);
               multipleValues.push(data.d.results[i].LCode);
            }
            //setTimeout(Blank, 2000);
           
            console.log(lCode);
            SP.SOD.executeFunc("sp.js", "SP.ClientContext", function(){
            SP.SOD.registerSod("sp.userprofiles.js", SP.Utilities.Utility.getLayoutsPageUrl("sp.userprofiles.js"));
            SP.SOD.executeFunc("sp.userprofiles.js", "SP.UserProfiles.PeopleManager", SetCurrentUserProperties);
            });
       
        var userProfileProperties;
       
        function SetCurrentUserProperties(){
           
            console.log( typeof lCode);
            //Get Current Context   
            var clientContext = SP.ClientContext.get_current();
           
            //Get Instance of People Manager Class
            var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
           
            //Get properties of the current user
            userProfileProperties = peopleManager.getMyProperties();
           
            //Get only the accountname instead of all the properties.
            clientContext.load(userProfileProperties, "AccountName");
           
            //Execute the Query.
            clientContext.executeQueryAsync(function(){
               
                //Get the account name of the current user. It will be in the following format: "i:0#.f|membership|username@yoursite.onmicrosoft.com"
                var currentUserAccountName = userProfileProperties.get_accountName();
               
                console.log(currentUserAccountName);
                //Set a single value property
                peopleManager.setSingleValueProfileProperty(currentUserAccountName, "SPS-Locale", lCode);
               
                //Set a multivalue property
                //var multipleValues = ["SharePoint", "Office 365", "Architecture"];
                console.log(multipleValues);
                peopleManager.setMultiValuedProfileProperty(currentUserAccountName, "SPS-MUILanguages", multipleValues);
               
                peopleManager.setSingleValueProfileProperty(currentUserAccountName, "AboutMe", "Value updated from JSOM!");
                //Execute the Query.
                clientContext.executeQueryAsync(function(){
                   
                    console.log("properties updated!");
                },
                function(sender,args){
                    //On Error
                    console.log(args.get_message());
                });
               
            }, function(sender,args){
                //On Error
                console.log(args.get_message());
            });
           
        }
    });

}

</script>

Change Site Language with JSOM

Hi,

Here is code which can change site language with JSOM :

<script type="text/javascript" charset="utf8" src="/Style%20Library/SPS/jquery-1.11.3.min.js"></script>

<select id='LangSelect' onchange="SetLanguage();"></select>


<script type="text/javascript">


$( document ).ready(function() {
    LoadLanguages();
    setTimeout(GetUpdatedLangulage, 2000);
});

function LoadLanguages()
{
        var call = $.ajax({
            url: _spPageContextInfo.siteAbsoluteUrl + "/_api/Web/Lists/GetByTitle('Languages')/items?" + "$select=Title,Code,ID&$top=5000",
            type: "GET",
            dataType: "json",
            headers: {
                Accept: "application/json;odata=verbose"
            }
        });

        call.done(function (data, textStatus, jqXHR) {
            var option = '';
            for (var i=0;i<data.d.results.length;i++){
               option += '<option value="'+ data.d.results[i].Code + '">' + data.d.results[i].Title + '</option>';
            }
            $('#LangSelect').append(option);
        });
}

function SetLanguageInRegionalSettings()
{
    var context = SP.ClientContext.get_current();

    var web = context.get_web();

    var regionalSettings = web.get_regionalSettings();

    context.load(regionalSettings)

    context.executeQueryAsync(function () {

            var sel = document.getElementById('LangSelect');
            console.log( sel.value );

            regionalSettings.set_localeId(sel.value); //English (UK)
   
            regionalSettings.update();
   
            context.executeQueryAsync(function () {
                console.log("success");
            }, function (sender, args) {
                console.log(args.get_message());
            });
        }, function (sender, args) {
            console.log(args.get_message());
    });
}

function GetUpdatedLangulage()
{
    var context = SP.ClientContext.get_current();
    var web = context.get_web();
    var regionalSettings = web.get_regionalSettings();
    context.load(regionalSettings,  "LocaleId");

    context.executeQueryAsync(function () {

        //Locale Id
        console.log(regionalSettings.get_localeId()); //2057
        var sel = document.getElementById('LangSelect');
        sel.value = regionalSettings.get_localeId();
    }, function (sender, args) {
        console.log(args.get_message());
    });
}


function SetLanguage()
{
    var context = SP.ClientContext.get_current();

    var web = context.get_web();

    //This is important. Wont work otherwise.
    web.set_isMultilingual(true);
   
    var sel = document.getElementById('LangSelect');
    console.log( sel.value );
    web.addSupportedUILanguage(sel.value); //Dutch
   
    //The full list of SharePoint 2013 and SharePoint Online LCIDs is here:
    //https://technet.microsoft.com/en-us/library/ff463597.aspx
   
    web.update();
   
    context.executeQueryAsync(function(){
        console.log("Language Added");
        SetLanguageInRegionalSettings();
    },function(sender,args){
        console.log(args.get_message());
        SetLanguageInRegionalSettings();
    });   
}

</script>

Remove App from SharePoint Online with Powershell

Hi,

Today I was facing some issues in installed custom app. I was not able to get App Details & also not able to remove the app. I tried alot from interface but I couldn't remove the app. Then I move to Powershell scripts.

Here is the powershell script which can remove the app from SharePoint Online. Only prerequisite is you must have SharePoint Online Client Components SDK installed on the system.

cls
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")


Function Get-ClientContext([string]$Url,[string]$UserName,[string]$Password)
{
    $context = New-Object Microsoft.SharePoint.Client.ClientContext($Url)
    $context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $Password)
    return $context
}


Function Uninstall-AppInstance([Microsoft.SharePoint.Client.ClientContext]$Context,[Guid]$AppInstanceId)
{
    $appInst = $Context.Web.GetAppInstanceById($AppInstanceId)
    $appInst.Uninstall()
    $context.ExecuteQuery()
 }




$UserName = "gaurav.goyal@myorgs.com"
$Password=Read-Host -Prompt "Password" -AsSecureString;

$Url = "https://mytenant.sharepoint.com"
$AppInstanceid = New-Object Guid("XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")  #you need to specify App Instance Id here

$context = Get-ClientContext -Url $Url -UserName $UserName -Password $Password

Uninstall-AppInstance -Context $context -AppInstanceId $AppInstanceid
$context.Dispose()

Tuesday, January 10, 2017

Tasks List with PNP JS & DataTable in SharePoint

Hi ,

I have created one example for SharePoint with pnp-js & datatable. 
Features which I have covered in this example :
  • Open task display page in new tab.
  • Show Priorities in different colors.
  • Show Percent Completed as Progress Bar
  • Show dates in proper formats.
  • Show Assigned To (Multi-people)


Here is the code :

You need to add following references :
<script src="https://code.jquery.com/jquery-2.2.0.min.js" integrity="sha256-ihAoc6M/JPfrIiIeayPE9xjin4UWjsx2mjW/rtmxLM4=" crossorigin="anonymous"></script>

<!-- DataTables CSS -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- DataTables -->
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.js"></script>

<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/plug-ins/1.10.12/sorting/datetime-moment.js"></script>

You need to download following files & add the reference :
 <script type="text/javascript" charset="utf8" src="/sites/MyDev/Style%20Library/SPS/pnp.js"></script>
<script type="text/javascript" charset="utf8" src="/sites/MyDev/Style%20Library/SPS/es6-promise.min.js"></script>
<script type="text/javascript" charset="utf8" src="/sites/MyDev/Style%20Library/SPS/fetch.js"></script>

Now you need to create HTML table with required columns :

<table width="100%" cellpadding="0" cellspacing="0" border="0" class="display" id="exampleTask">
    <thead>
    <th>Task Name</th>
    <th>Due Date</th>
    <th>Assigned To</th>
    <th>Priority</th>
    <th>Start Date</th>
    <th>Task Status</th>
    <th>Progress</th>
    </thead>

</table>


 This is the function which fill the data & format the datatable :
function LoadTaskItems()
{
        $pnp.setup({
            headers: {
                "Accept" : "application/json; odata=verbose",
            },
        });
        var baseUrl=_spPageContextInfo.siteAbsoluteUrl;
        var MyWeb = new $pnp.Web(baseUrl);
        //$pnp.sp.web.lists.getByTitle('Tasks').items.expand('AssignedTo').select('ContentTypeId,Title,Priority,Status,PercentComplete,AssignedTo/ID,AssignedTo/Title,StartDate,DueDate,ParentID,ID,Modified,Created,Author,Editor,FileDirRef').orderBy('ID').get().then(function (response) {
        MyWeb.lists.getByTitle('Tasks').items.expand('AssignedTo').select('ContentTypeId,Title,Priority,Status,PercentComplete,StartDate,DueDate,ID,Modified,Created,AssignedTo/ID,AssignedTo/Title,FileDirRef').orderBy('ID').get().then(function (response) {
            //alert(JSON.stringify( response[0].AssignedTo.results[0].Title));
            var generateCustomerTable = $("#exampleTask")
            .dataTable({
              "aaData": response,
              "processing": true,
              "autoWidth": true,
              "bDestroy": true,
              "aoColumns": [
                { "mData": "Title",  "width": "20%","fnCreatedCell" :
                    function (nTd, sData, oData, iRow, iCol)
                    {
                        $(nTd).html("<a href='"+ oData.FileDirRef +"/DispForm.aspx?ID="+oData.ID+"' target='_blank'>"+oData.Title+"</a>");
                    }
                },
                { "data": "DueDate", "stype": "date",
                    "render": function( data, type, row, meta){
                            var ThisDate = moment(new Date(data)).format("Do MMM YYYY");
                            return ThisDate
                    }
                },
                { "data": "AssignedTo.results[, ].Title"

                },
                { "data": "Priority" ,"fnCreatedCell" :
                    function (nTd, sData, oData, iRow, iCol)
                    {
                        var displayValue='';
                        switch (oData.Priority) {
                            case "(1) High":
                                displayValue="<span style='color :#f00'>" + oData.Priority + "</span>";
                                break;
                            case "(2) Normal":
                                displayValue="<span style='color :#ff6a00'>" + oData.Priority + "</span>";
                                break;
                            case "(3) Low":
                                displayValue="<span style='color :#cab023'>" + oData.Priority + "</span>";
                        }
                        $(nTd).html(displayValue);
                    }
                },
                { "data": "StartDate" , "stype": "date",
                    "render": function( data, type, row, meta){
                            var ThisDate = moment(new Date(data)).format("Do MMM YYYY");
                            return ThisDate
                    }
                },
                { "data": "Status"
                },
                { "data": "PercentComplete","width": "150px;" ,"fnCreatedCell" :
                    function (nTd, sData, oData, iRow, iCol)
                    {
                        var val= ((oData.PercentComplete * 100));
                        var tt= "<div style='background-color: #e5e5e5; width: 100px;  display:inline-block;'><div style='width: " + val + "px; background-color: #0094ff;'>&nbsp;</div></div>&nbsp;" + (oData.PercentComplete * 100);
                        $(nTd).html(tt);
                    }

                }
              ],
              "language": {
                "emptyTable": "There are no tasks at present.",
                "zeroRecords": "There were no matching tasks found."
              },
              "caseInsensitive": false,
              "searching": true,
              "pageLength": 50,
              "ordering": true,
              "paging": true,
              "order": [0, "asc"],
            });
        });

}

Wednesday, November 30, 2016

Organization Chart with AngularJS



What is Organization Chart?

An Organizational Chart shows the internal structure of an organization or company. The employees and positions are represented by boxes or other shapes, sometimes including photos, contact information, email and page links, icons and illustrations. Straight or elbowed lines link the levels together.  This creates a clear visual depiction of the hierarchy and ranks of different people, jobs and departments that make up the organization.
Organizational Charts also are known as Organization Charts, Org Charts, Organograms, Organogram Charts (sometimes spelled Organigrams or Organigrammes) and Hierarchy Charts. Don’t be fooled: Despite all the different names, they’re all the same thing.

How to create with angularjs & google chart?

First you need to create one JS file: OrgChart.JS & copy below text :
var app = angular.module('OrgChartApp', []);
app.controller('OrgChartController', ['$scope', '$http', function ($scope, $http) {
    //here http get method for get data from database
    $scope.chartData = [['Name', 'ReportsTo', 'JobTitle']];
    var data = [{ ID: 1, EmployeeName: 'Gaurav Goyal', Title: 'Product Archtech', ReportsTo: 0, img_url: '//lh5.googleusercontent.com/-evpjmrDWNMQ/AAAAAAAAAAI/AAAAAAAAAcY/d7qvMNmJlNw/s80-c/photo.jpg' },
        { ID: 2, EmployeeName: 'David Verti', Title: 'SSE', ReportsTo: 1, img_url: '//lh5.googleusercontent.com/-evpjmrDWNMQ/AAAAAAAAAAI/AAAAAAAAAcY/d7qvMNmJlNw/s80-c/photo.jpg' },
        { ID: 3, EmployeeName: 'Rahul Khanna', Title: 'SSE', ReportsTo: 1, img_url: '//lh5.googleusercontent.com/-evpjmrDWNMQ/AAAAAAAAAAI/AAAAAAAAAcY/d7qvMNmJlNw/s80-c/photo.jpg' },
        { ID: 4, EmployeeName: 'Tarun Sharma', Title: 'SE', ReportsTo: 2, img_url: '//lh5.googleusercontent.com/-evpjmrDWNMQ/AAAAAAAAAAI/AAAAAAAAAcY/d7qvMNmJlNw/s80-c/photo.jpg' },
        { ID: 5, EmployeeName: 'Yaman Raj', Title: 'SE', ReportsTo: 2, img_url: '//lh5.googleusercontent.com/-evpjmrDWNMQ/AAAAAAAAAAI/AAAAAAAAAcY/d7qvMNmJlNw/s80-c/photo.jpg' },
        { ID: 6, EmployeeName: 'Sanjay Jain', Title: 'SE', ReportsTo: 3, img_url: '//lh5.googleusercontent.com/-evpjmrDWNMQ/AAAAAAAAAAI/AAAAAAAAAcY/d7qvMNmJlNw/s80-c/photo.jpg' },
        { ID: 7, EmployeeName: 'Om Prakash', Title: 'SE', ReportsTo: 3, img_url: '//lh5.googleusercontent.com/-evpjmrDWNMQ/AAAAAAAAAAI/AAAAAAAAAcY/d7qvMNmJlNw/s80-c/photo.jpg' }
    ];

    var newobject = [['Name', 'ReportsTo', 'JobTitle']];
    angular.forEach(data, function (val) {
        newobject.push(
            [
                {
                    v: val.ID.toString(),
                    f: '<div class="parent">'
                        + '<div> '
                        + '<img src="' + val.img_url + '" class="iconDetails">'
                        + ' </div>'
                        + ' <div class="text">'
                        + '<h4><b>' + val.EmployeeName + '</b></h4>'
                        + '<div >' + val.Title + '</div>'
                        + '<div >gauravgoyal_5@yahoo.com</div>'
                        + '</div>'
                        + '</div>'
                },
                (val.ReportsTo.toString() === "0" ? "" : val.ReportsTo.toString()),
                (val.EmployeeName)
            ]
            );

    })
    $scope.chartData = newobject;

}])
app.directive('orgChart', function () {
    function link($scope, element, attrs) {
        var chart = new google.visualization.OrgChart(element[0]);
        $scope.$watch('chartData', function (value, oldvalue) {
            if (!value) {
                return;
            }
            var data = google.visualization.arrayToDataTable(value);
            var options = {
                'title': '',
                'allowHtml': true
            }
            chart.draw(data, options);
        })
    }
    return {
        link: link
    };
})

Now you need to create HTML file :  OrgChart.html & copy below text :
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1','packages':['corechart','orgchart']}]}"></script>
<script src="//SiteAssets/OrgChart-3.js"></script>
    <style>
        .iconDetails {
   float: left;
    height: 75px;
       width: 75px;
   padding:10px;
  }
.parent{
      
    display:table;
    width:300px;
      
}
.text{
display: table;
text-align:left;
}

        .google-visualization-orgchart-node-medium {
            width: 200px;
        }

        .ms-rtestate-field h4, h4.ms-rteElement-H4 {
            font-size: 1.3em;
            color: brown;
            padding-top:10px;
            padding-left:0px;
            margin-left:0px;
        }

        .google-visualization-orgchart-node {
            background: transparent;
        }
    </style>

</head>

<body ng-app="OrgChartApp">
    <div ng-controller="OrgChartController">
                <div id="chart" ng-model="chartData" org-chart="chartData" style="text-align:center">
           
        </div>
    </div>
</body>
</html>






Here is final outcome :