Sunday, June 25, 2017

Get User Profile Properties By JSOM Code in Sharepoint 2013


//SP.SOD.executeOrDelayUntilScriptLoaded(getUserProperties, 'SP.UserProfiles.js');
// SP.SOD.executeFunc('userprofile', 'SP.UserProfiles.PeopleManager',getUserProperties);

var userProfileProperties;

function getUserProperties()
{
 var clientContext = new SP.ClientContext.get_current();
 var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
 userProfileProperties = peopleManager.getMyProperties();
 clientContext.load(userProfileProperties);
 clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
}
function onRequestSuccess()
{
var userName = userProfileProperties.get_userProfileProperties()['PreferredName'];
var Officelocation = userProfileProperties.get_userProfileProperties()['Office'];
alert(userName);
alert(Officelocation);
}

function onRequestFail(sender, args)
{ }

Sunday, May 28, 2017

Multiple Approval for “Assign Flexi Task” in Nintex using JQuery/Javascript

Source:  https://wearetechie.wordpress.com/2014/03/07/multiple-approval-for-assign-flexi-task-in-nintex-using-jqueryjavascript/comment-page-1/#comment-82
-----------------------------------------------------------------------------------------------------------------------



<script language=”javascript” type=”text/javascript” src=”/sites/jdp/Shared%20Documents/jquery.SPServices-0.7.2.min.js”></script>
<script language=”javascript” type=”text/javascript”>
function ApproveRejectTask(status) {
debugger;
var comments = $(‘#TextAreaComment’)[0].value;
var items = getQuerystring(“Items”);
var currentListGUID = getQuerystring(“ListGUID”);
var taskItems = items.split(‘;’)
var updateString = “<Batch OnError=’Continue’>”;
for (var i = 0; i < taskItems.length – 1; i++) {
updateString += “<Method ID=’1′ Cmd=’Update’>” +
“<Field Name=’ID’>” + taskItems[i] + “</Field>” +
“<Field Name=’Decision’>” + status + “</Field>” +
“<Field Name=’ApproverComments’>” + comments + “</Field>” +
“</Method>”;
}
updateString += “</Batch>”;
$().SPServices({
operation: “UpdateListItems”,
async: false,
batchCmd: “Update”,
listName: currentListGUID,
updates: updateString,
completefunc: function (xData, Status) {
}
});
SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, “”);
}
function getQuerystring(key, default_) {
if (default_ == null) default_ = “”;
key = key.replace(/[\[]/, “\\\[“).replace(/[\]]/, “\\\]”);
var regex = new RegExp(“[\\?&]” + key + “=([^&#]*)”);
var qs = regex.exec(window.location.href);
if (qs == null)
return default_;
else
return qs[1];
}
</script>
<table width=”100%” cellpadding=”0″>
<tr>
<td>
Comments :
</td>
<td>
<textarea name=”TextAreaComment” id=”TextAreaComment” cols=”30″ rows=”3″></textarea>
</td>
</tr>
<tr>
<td>
</td>
<td align=”right”>
<input name=”ApproveBTN” type=”button” value=”Approve” onclick=”javascript:ApproveRejectTask(1)”/>
<input name=”RejectBTN” type=”button” value=”Reject” onclick=”javascript:ApproveRejectTask(2)”/>
</td>
</tr>
</table>
Step 2: Edit your Task view page and add a content editor Web Part. Open the content editor WebPart and add the below script. On click of the Approve/Reject button on the List view ribbon, the below script takes the ID of all the task item selected to
<script language=”javascript” type=”text/javascript”>
var siteUrl;
$(document).ready(function () {
siteUrl = _spPageContextInfo.siteServerRelativeUrl;
});
function ApproveRejectMulti() {
var selectedItems = SP.ListOperation.Selection.getSelectedItems();
var currentListGUID = SP.ListOperation.Selection.getSelectedList();
if (selectedItems.length > 0) {
var itemIDs = “”;
for (var i in selectedItems) {
itemIDs += selectedItems[i].id + “;”;
}
var optionsForm = { url: siteUrl + “/SitePages/ApproveRejectMulti.aspx?Items=” + itemIDs + “&ListGUID=” + currentListGUID, title: “Approve/Reject Multiple FSR”, allowMaximize: false, width: 400, height: 200, showClose: true, dialogReturnValueCallback: refreshCallback };
SP.UI.ModalDialog.showModalDialog(optionsForm);
} else {
alert(“Select at least one Task to Approve/Reject”);
}
}
function refreshCallback(dialogResult, returnValue) {
SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);
}
</script>

Sunday, May 21, 2017

Updating task item from javascript Rest API SharePoint // Working code


// ---------------Updating task item from javascript Rest API SharePoint // Working code

//--------Check for  SP.Data.WorkflowTasksItem     //item type
// http://win12sp13:40/_api/web/lists/GetByTitle('Workflow%20Tasks')/ListItemEntityTypeFullName

//--------Check for all properties of list metadata------
//http://win12sp13:40/_api/Web/Lists/GetByTitle('Workflow%20Tasks')/getItemById('5')

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

<script type="text/javascript">
var item = {
    "__metadata": { "type": "SP.Data.WorkflowTasksItem" },
    "WorkflowOutcome" : "Completed",
    "Status" : "Completed",
    "PercentComplete" : 1
   
};

function appTask()
{
 var testUrl = _spPageContextInfo.webAbsoluteUrl+"/_api/Web/Lists/GetByTitle('Workflow%20Tasks')/getItemById(7)";

alert(testUrl);
$.ajax({
    url: testUrl,
    type: "PATCH",
    contentType: "application/json;odata=verbose",
    data: JSON.stringify(item),
     headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "content-Type": "application/json;odata=verbose",
            "X-Http-Method": "PATCH",
            "If-Match": "*"
        },
    data: JSON.stringify(item),
        success: function (data) {
            console.log(data);
alert('success'+ data);
        },
        error: function (error) {
            alert(JSON.stringify(error));
}
});
}
</script>


<div><input type='button' onclick="Javascript:appTask()"  value='Approve'></div>




Saturday, May 20, 2017

Software keys

Name:SharePoint Server 2010, Standard
key: HQ937-PP69X-8K3KR-VYY2F-RPHB3

-------------------------------------

Name:SharePoint Server 2013 Enterprise (TechNet)
key: 43KK8-NC7MG-3RHCH-3JVTC-V8M4V


------------------------------------


Name:SharePoint Server 2013 Standard (TechNet)
key: PP6N9-FRKQF-QRJWY-276K4-JHRRK

-------------------------------------

Name:Project Server 2013 (TechNet)
key: 4JY2P-PNH4R-WJQ77-8V2FJ-29VTC

-----------------------------------------

Name:Project Server 2010
key: GVW7M-WFRY6-QRGWM-QV97D-JP6XT

-----------------------------------------

Name:Office Web Apps 2013 (TechNet)
key: BN6K7-YT664-XFJJF-6FD38-WB3CM

------------------------------------------


Name:Office Web Apps 2010
key: 7MXKC-26TBD-D6GJ6-GCGCK-4C9TF

------------------------------------------

Name:Office Pro Plus 2013 (TechNet Standard)
key: BY473-NCBY3-P6KGB-BY7VC-J42C9


--------------------------------------------

Name:Office Professional Plus 2010 (TechNet Standard)
key: MC2BB-FXHJM-7CPTJ-K2P2H-9JKWP

Sunday, May 7, 2017

Callouts popups example in SharePoint 2013 in Javascript



<script type="text/javascript" src="/_layouts/15/callout.js"></script>

<script type="text/javascript">

//This functions makes the request to the RESTful ListData service
function getListItems() {

var Url = "https://SPSite/_vti_bin/ListData.svc/Announcements";

//Create a WebRequest object
var request = new Sys.Net.WebRequest();

//Specify the verb
request.set_httpVerb("GET");


//Use the URL we already formulated
request.set_url(Url);


//Set the Accept header to ensure we get a JSON response
request.get_headers()["Accept"] = "application/json";


//Add a callback function that will execute when the request is completed
request.add_completed(onCompletedCallback);


//Run the web requests
request.invoke();

}

function onCompletedCallback(response, eventArgs) {

//Parse the JSON reponse into a set of objects by using the JavaScript eval() function

var announcements = eval("(" + response.get_responseData() + ")");

var newAnnouncement = document.createElement("div"); 

for (var i = 0; i < announcements.d.results.length; i++) {

//Display some properties
_announTitle = announcements.d.results[i].Title;
_announID = announcements.d.results[i].Id;
_announBody = announcements.d.results[i].Body;

announcementsList.appendChild(newAnnouncement); 

var calloutLink = document.createElement("div"); 
            calloutLink.id = _announID; 
            calloutLink.onmouseover = function () { 
                curListUrl = this.id; 
            } 

calloutLink.innerHTML = "<div class=\"ms-commandLink\" style=\"text-align: left;font-size: 14px;\"><b>" + _announTitle + "</b><br/><br/></div>"; 

announcementsList.appendChild(calloutLink); 

var listCallout = CalloutManager.createNew({ 
                launchPoint: calloutLink,
                beakOrientation: "leftRight", 
                ID: _announID, 
                title: _announTitle, 
                content: "<div class=\"ms-soften\" style=\"margin-top:13px;\">" 
                        + "<hr/></div>" 
                        + "<div class=\"callout-section\" style=\"margin-top:13px;\">" + _announBody + "</div>", 
            }); 

}

}


</script>

<div id="announcementsList"></div>
<a href="Javascript:getListItems()">Click Here to Display Announcements</a>

Friday, February 3, 2017

Rest Syntax for filtering Listitems from SharePoint 2013

Get all tasks assigned to me:
----------------------------------

/_api/web/lists/getbytitle('Development Tasks')/items?$expand=AssignedTo&amp;$select=Title,AssignedTo/Title&amp;$filter=AssignedTo/Title eq 'Anderson, Marc'


Get all tasks that have not been completed, showing the status and the % complete:
-----------------------------------------------------------------------------------------------------

/_api/web/lists/getbytitle('Development Tasks')/items?$expand=AssignedTo&amp;$select=Title,AssignedTo/Title,Status,PercentComplete&amp;$filter=Status ne 'Completed'


Source:
========
https://msdn.microsoft.com/en-us/library/gg309461.aspx

http://sympmarc.com/2016/09/07/retrieving-the-content-type-in-a-rest-call-in-sharepoint-2013-on-premises/


REST Call Syntax
----------------------------











Monday, January 23, 2017

Paging in JSOM in SharePoint

Sample one (Basic Paging)

This code sample request a list in chunks of 4 items, then the items are written on the page inside html table as the following image & code:


JavaScript
var context, 
    web, 
    spItems, 
    position, 
    nextPagingInfo, 
    previousPagingInfo, 
    listName = 'ContactsList', 
    pageIndex = 1// default page index value 
    pageSize = 4// default page size value 
    list, 
    camlQuery; 
 
// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model  
$(document).ready(function () { 
    context = SP.ClientContext.get_current(); 
    list = context.get_web().get_lists().getByTitle(listName); 
    camlQuery = new SP.CamlQuery(); 
 
    $("#btnNext").click(function () { 
        pageIndex = pageIndex + 1; 
        if (nextPagingInfo) { 
            position = new SP.ListItemCollectionPosition(); 
            position.set_pagingInfo(nextPagingInfo); 
        } 
        else { 
            position = null; 
        } 
 
        GetListItems(); 
    }); 
 
    $("#btnBack").click(function () { 
        pageIndex = pageIndex - 1; 
        position = new SP.ListItemCollectionPosition(); 
        position.set_pagingInfo(previousPagingInfo); 
        GetListItems(); 
    }); 
 
    GetListItems(); 
}); 
 
function GetListItems() { 
    //Set the next or back list items collection position 
    //First time the position will be null 
    camlQuery.set_listItemCollectionPosition(position); 
 
    // Create a CAML view that retrieves all contacts items  with assigne RowLimit value to the query 
    camlQuery.set_viewXml("<View>" + 
                              "<ViewFields>" + 
                                     "<FieldRef Name='FirstName'/>" + 
                                     "<FieldRef Name='Title'/>" + 
                                     "<FieldRef Name='Company'/>" + 
                                "</ViewFields>" + 
                             "<RowLimit>" + pageSize + "</RowLimit></View>"); 
 
    spItems = list.getItems(camlQuery); 
 
    context.load(spItems); 
    context.executeQueryAsync( 
            Function.createDelegate(this, onSuccess), 
            Function.createDelegate(this, onFail) 
        ); 
} 
 
// This function is executed if the above OM call is successful 
// This function render the returns items to html table 
function onSuccess() { 
 
    var listEnumerator = spItems.getEnumerator(); 
    var items = []; 
    var item; 
 
    while (listEnumerator.moveNext()) { 
        item = listEnumerator.get_current(); 
        items.push("<td>" + item.get_item('FirstName') + "</td><td>" + item.get_item('Title') + "</td><td>" + item.get_item('Company') + "</td>"); 
    } 
 
    var content = "<table><tr><th>First Name</th><th>Last Name</th><th>Company</th></tr><tr>" 
                + items.join("</tr><tr>") + "</tr></table>"; 
    $('#content').html(content); 
 
    managePagerControl(); 
} 
 
function managePagerControl() { 
 
    if (spItems.get_listItemCollectionPosition()) { 
        nextPagingInfo = spItems.get_listItemCollectionPosition().get_pagingInfo(); 
    } else { 
        nextPagingInfo = null; 
    } 
 
    //The following code line shall add page information between the next and back buttons 
    $("#pageInfo").html((((pageIndex - 1) * pageSize) + 1) + " - " + ((pageIndex * pageSize) - (pageSize - spItems.get_count()))); 
 
    previousPagingInfo = "PagedPrev=TRUE&Paged=TRUE&p_ID=" + spItems.itemAt(0).get_item('ID'); 
 
    if (pageIndex <= 1{ 
        $("#btnBack").attr('disabled''disabled'); 
    } 
    else { 
        $("#btnBack").removeAttr('disabled'); 
    } 
 
    if (nextPagingInfo) { 
        $("#btnNext").removeAttr('disabled'); 
    } 
    else { 
        $("#btnNext").attr('disabled''disabled'); 
    } 
 
}

Sample two (Paging with CAML Sorting)



JavaScript
var context, 
    web, 
    spItems, 
    position, 
    nextPagingInfo, 
    previousPagingInfo, 
    listName = 'ContactsList', 
    pageIndex = 1// default page index value 
    pageSize = 4// default page size value 
    list, 
    camlQuery, 
    sortColumn = 'FirstName'// this is sort column, you can add more than one column, but you should add it also to CAML Query & managePagerControl function 
 
// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model  
$(document).ready(function () { 
    context = SP.ClientContext.get_current(); 
    list = context.get_web().get_lists().getByTitle(listName); 
    camlQuery = new SP.CamlQuery(); 
 
    $("#btnNext").click(function () { 
        pageIndex = pageIndex + 1; 
        if (nextPagingInfo) { 
            position = new SP.ListItemCollectionPosition(); 
            position.set_pagingInfo(nextPagingInfo); 
        } 
        else { 
            position = null; 
        } 
 
        GetListItems(); 
    }); 
 
    $("#btnBack").click(function () { 
        pageIndex = pageIndex - 1; 
        position = new SP.ListItemCollectionPosition(); 
        position.set_pagingInfo(previousPagingInfo); 
        GetListItems(); 
    }); 
 
    GetListItems(); 
}); 
 
function GetListItems() { 
    //Set the next or back list items collection position 
    //First time the position will be null 
    camlQuery.set_listItemCollectionPosition(position); 
 
    // Create a CAML view that retrieves all contacts items  with assigne RowLimit value to the query 
    camlQuery.set_viewXml("<View>" + 
                                "<ViewFields>" + 
                                       "<FieldRef Name='FirstName'/>" + 
                                       "<FieldRef Name='Title'/>" + 
                                       "<FieldRef Name='Company'/>" + 
                                  "</ViewFields>" + 
                               "<Query>" + 
                                    "<OrderBy>" + 
                                      "<FieldRef Name='" + sortColumn + "' Ascending='true' />" + 
                                    "</OrderBy>" + 
                               "</Query>" + 
                               "<RowLimit>" + pageSize + "</RowLimit></View>"); 
 
    spItems = list.getItems(camlQuery); 
 
    context.load(spItems); 
    context.executeQueryAsync( 
            Function.createDelegate(this, onSuccess), 
            Function.createDelegate(this, onFail) 
        ); 
} 
 
// This function is executed if the above OM call is successful 
// This function render the returns items to html table 
function onSuccess() { 
 
    var listEnumerator = spItems.getEnumerator(); 
    var items = []; 
    var item; 
 
    while (listEnumerator.moveNext()) { 
        item = listEnumerator.get_current(); 
        items.push("<td>" + item.get_item('FirstName') + "</td><td>" + item.get_item('Title') + "</td><td>" + item.get_item('Company') + "</td>"); 
    } 
 
    var content = "<table><tr><th>First Name</th><th>Last Name</th><th>Company</th></tr><tr>" 
                + items.join("</tr><tr>") + "</tr></table>"; 
    $('#content').html(content); 
 
    managePagerControl(); 
} 
 
function managePagerControl() { 
 
    if (spItems.get_listItemCollectionPosition()) { 
        nextPagingInfo = spItems.get_listItemCollectionPosition().get_pagingInfo(); 
    } else { 
        nextPagingInfo = null; 
    } 
 
    $("#pageInfo").html((((pageIndex - 1) * pageSize) + 1) + " - " + ((pageIndex * pageSize) - (pageSize - spItems.get_count()))); 
 
    previousPagingInfo = "PagedPrev=TRUE&Paged=TRUE&p_ID=" + spItems.itemAt(0).get_item('ID') + "&p_" + sortColumn + "=" + encodeURIComponent(spItems.itemAt(0).get_item(sortColumn)); 
 
    if (pageIndex <= 1{ 
        $("#btnBack").attr('disabled''disabled'); 
    } 
    else { 
        $("#btnBack").removeAttr('disabled'); 
    } 
 
    if (nextPagingInfo) { 
        $("#btnNext").removeAttr('disabled'); 
    } 
    else { 
        $("#btnNext").attr('disabled''disabled'); 
    } 
 
}