Wednesday, November 29, 2017

Content Search configuration query


Content Search configuration query in panel
-----------------------------------------------------

contentclass:STS_ListItem AND (path:https://eappsq13.wr.com/apps/ust/rev/Lists/REV%20Test or path:https://eappsq13.wr.com/apps/ust/rev/Lists/Access%20Vault1 or path:https://eappsq13.wr.com/apps/ust/rev/Lists/KCCELAPPS%20Vault)  AND {SearchBoxQuery}

Sunday, July 30, 2017

What's new in authentication for SharePoint 2013

User authentication and authorization in SharePoint 2013

source: https://technet.microsoft.com/en-in/library/jj219758.aspx
User authentication in SharePoint 2013 is the process that verifies the identity of a user who requests access to a SharePoint web application. An authentication provider issues the authenticated user a security token that encapsulates a set of claims-based assertions about the user and is used to verify a set of permissions that are assigned to the user. User authorization in SharePoint 2013 is the process that determines the users who can perform defined operations on a specified resource within a SharePoint web application. SharePoint 2013 supports user authentication based on the following methods:
  • Windows claims
  • Security Assertion Markup Language (SAML)-based claims
  • Forms-based authentication claims
These claims-based authentication methods are now the recommended authentication methods for SharePoint 2013.

The app authentication and server-to-server authentication features of SharePoint 2013 require claims-based authentication. Because of this, claims-based authentication is the default for new web applications in SharePoint 2013. When you create a web application in Central Administration, you can only specify authentication methods for claims-based authentication. Although Windows Classic mode authentication is still available in SharePoint 2013 and can be configured through Windows PowerShell, we recommend that you use claims-based authentication. Windows Classic mode authentication is deprecated in SharePoint 2013.

Improvements in claims infrastructure

SharePoint 2013 also includes the following improvements in claims authentication infrastructure:
  • Easier migration from classic mode to Windows-based claims mode with the new Convert-SPWebApplication Windows PowerShell cmdlet
    Migration can be run against each content database and each web application. This is in contrast to SharePoint 2010 Products, in which the migration was run against each web application. For more information, see Migrate from classic-mode to claims-based authentication in SharePoint 2013.
  • Login tokens are now cached in the new Distributed Cache Service
    SharePoint 2013 uses a new Distributed Cache Service to cache login tokens. In SharePoint 2010 Products, the login token is stored in the memory of each web front-end server. Each time a user accesses a specific web front-end server, it needs to authenticate. If you use network load balancers in front of your web front-ends, users need to authenticate for each web front-end server that is accessed behind the load balancer, causing possible multiple re-authentications. To avoid re-authentication and its delay, it is recommended to enable and configure load balancer affinity (also known as sticky sessions). By storing the login tokens in the Distributed Cache Service in SharePoint 2013, the configuration of affinity in your load balancing solution is no longer required. There are also scale-out benefits and less memory utilization in the web front-ends because of a dedicated cache service.
  • More logging makes the troubleshooting of authentication issues easier
    SharePoint 2013 has much more logging to help you troubleshoot authentication issues. Examples of enhanced logging support are the following:
    • Separate categorized-claims related logs for each authentication mode
    • Information about adding and removing FedAuth cookies from the Distributed Cache Service
    • Information about the reason why a FedAuth cookie could not be used, such as a cookie expiration or a failure to decrypt
    • Information about where authentication requests are redirected
    • Information about the failures of user migration in a specific site collection

Server-to-server authentication

SharePoint 2013 extends OAuth to implement a server-to-server authentication protocol that can be used by services such as SharePoint 2013 to authenticate other services such as Exchange Server 2013 or Lync Server 2013 or services that are compliant with the server-to-server authentication protocol.
SharePoint 2013 has a dedicated local server-to-server security token service (STS) that provides server-to-server security tokens that contain user identity claims to enable cross-server authenticated access. These user identity claims are used by the other service to lookup the user against its own identity provider. A trust established between the local STS (the SharePoint 2013 server-to-server STS) and other server-to-server compliant services (the Exchange Server 2013 or Lync Server 2013 server-to-server STS) is the key functionality that makes server-to-server possible. For on-premises deployments, you configure the JavaScript Object Notation (JSON) metadata endpoint of the other server-to-server compliant service to establish this trust relationship. For online services, an instance of the Azure Access Control Service (ACS) acts as a trust broker to enable cross-server communications among the three types of servers.
The new server-to-server STS in SharePoint 2013 issues access tokens for server-to-server authentication. In SharePoint 2013 (and also in SharePoint 2010 Products), trusted identity providers that are compliant with the WS-Federation protocol are supported. However, the new server-to-server STS in SharePoint 2013 performs only the functionality that enables temporary access tokens to access other services such as Exchange Server 2013 and Lync Server 2013. The server-to-server STS is not used for user authentication and is not listed on the user sign-in page, the Authentication Provider UI in Central Administration, or in the People Picker in SharePoint 2013 Products.

App authentication

SharePoint 2013 uses OAuth 2.0 to authorize requests by apps in the SharePoint Store and App Catalog to access SharePoint resources on behalf of a user. The user grants permission to apps in the SharePoint Store and App Catalog to access SharePoint resources on the user's behalf when they are installed. For example, a user installs an app from the SharePoint Store. A SharePoint site contains an embedded HTML inline frame (IFRAME) that the app renders and that requires the app to access a user list. When a Web browser displays the site, the app then calls back to the server running SharePoint 2013 to access the list on behalf of the user. After the app obtains the data from the list, it displays the contents of the IFRAME.
The app authentication process in SharePoint 2013 uses OAuth to verify a claim that an app makes and assert that the app can act on behalf of an authenticated user. In SharePoint 2013, an instance of the Azure ACS acts as the app identity provider. You can also use app authentication without ACS. The authorization process verifies that an authenticated app has permission to perform a defined operation or to access a specified resource.

Sunday, July 23, 2017

Nintex form javascript code(NDP)


 var listName = 'Approval Limits';
 var taskListName = 'NDPTasks';

 var ndpList = 'List Name';
 var ndpListUrl ='Item URL';
 var requestor ='Requestor';

 var approvers = [];
 
NWF$(document).ready(function()
{NWF$(".apnl").hide();
NWF$(".bpnl").hide();
var isContainDispForm = ndpListUrl.indexOf("DispForm");if(isContainDispForm > -1)
{
  ndpListUrl = ndpListUrl.substring(0,isContainDispForm);}
var isEditMode = document.location.pathname.indexOf("/EditForm.aspx") > -1;
var isDispMode = document.location.pathname.indexOf("/DispForm.aspx") > -1;
if(isEditMode)
{
 ClearAllFields();
 GetApproversInAppLimits();

 GetAllTasksComments();
}
 var checked =  NWF$('#' + TabControl).find("input:checked").val();
 if(!checked)
 {
  NWF$('.AppPnlClass').hide();
 } });
 
 NWF$('#' + TabControl).change(function() {
  var checked =  NWF$('#' + TabControl).find("input:checked").val();
  if(checked == 'Approval')
  {
    NWF$('.AppPnlClass').show();
  }
   
 });

 function DisplaySavePnlToInitaitorREQ()
 {
  var isREQ =  NWF$('#' +REQ).val();
  var isSubmitForApproval =  NWF$('#' +SubForApproval).val();
  var currentUid = _spPageContextInfo.userId;
 
  if((isSubmitForApproval == 'No') && (currentUid == initiatorId))
  {
   NWF$('.pnlSaveCss').show();
  }
  else
  {
   NWF$('.pnlSaveCss').hide();
   NWF$('.ms-cui-ctl-large').eq(0).hide();    

  }
 
 
  if((currentUid == initiatorId) && (isREQ == 'Yes') && (isSubmitForApproval == 'Yes'))
  {
   NWF$('.pnlSaveCss').show();
   NWF$('.btnSubmitWFCss').hide();
   NWF$('.REQCss').hide();
   NWF$('.btnSubmitWFCssAppUI').show();
   NWF$('.ApproveBtnPnlClass').hide();
   NWF$("#"+NotionalVal).prop('readonly', true);
   NWF$("#"+NotionalVal).attr('style', 'background-color: #e5e9ec !important; border:none !important;');
 
  }
  else if(isSubmitForApproval == 'Yes')
  {
    NWF$('.pnlSaveCss').hide();
    NWF$('.inputControlCss').attr('style', 'background-color: #e5e9ec !important; border:none !important;');
    NWF$('.inputControlCss').prop('readonly', true);
    NWF$('.ms-cui-ctl-large').eq(0).hide();      NWF$('#'+TitleText).attr('style', 'background-color: #e5e9ec !important; border:none !important; width:310px');
   

 NWF$('#aspnetForm select').attr('style', 'background-color: #e5e9ec !important; border:none !important;');
 NWF$('#'+NotionalVal).attr('style', 'background-color: #e5e9ec !important; border:none !important;');
 NWF$('#'+ddlProductA).attr('disabled',true);
 NWF$('#'+productddlB).attr('disabled',true);
 NWF$('#'+ddlProductA).attr('style', 'background-color: #e5e9ec !important; border:none !important;');
 NWF$('#'+productddlB).attr('style', 'background-color: #e5e9ec !important; border:none !important;');
 NWF$('#'+BuyRadioBtn).find('input[type="radio"]').attr('disabled',true);
 NWF$('#'+deal18Radio).find('input[type="radio"]').attr('disabled',true);
 NWF$('#'+startDt).attr('disabled',true);
 NWF$('#'+endDt).attr('disabled',true);
 NWF$('#'+startDt).attr('style', 'background-color: #e5e9ec !important; border:none !important;');
 NWF$('#'+endDt).attr('style', 'background-color: #e5e9ec !important; border:none !important;');
 NWF$('#'+ NDPFormLogBox).closest('tr').find('div[id$="_inplacerte"]').eq(0).attr('style', 'background-color: #e5e9ec !important; border:none !important;');
 NWF$('#'+ NDPFormLogBox).closest('tr').find('div[id$="_inplacerte"]').eq(0).attr("contentEditable","false");
 NWF$('.propertysheet').hide();
 NWF$('.nf-attachmentsLink').hide();
 NWF$('.ui-datepicker-trigger').hide();

  NWF$('#'+bkddl).hide();
  NWF$('.bkcss').hide();
  NWF$('.productddl').hide();

  NWF$('#'+ddlProductA).hide();
  NWF$('#'+productddlB).hide();
 
  NWF$('.ms-rtestate-field').eq(0).attr('style', 'background-color: #e5e9ec !important; border:none !important;');
 
 NWF$('#'+NotionalVal).prop('readonly', true);
 NWF$('#'+TitleText).prop('readonly', true);

var isReviewStart = NWF$('#'+isRevStart).val();
  if(isReviewStart == 'Yes')
  {
     NWF$('.reviewPnlClass').show();
     NWF$('.ApproveBtnPnlClass').hide();  
  }
  else
  {
     NWF$('.ApproveBtnPnlClass').show();  
     NWF$('.reviewPnlClass').hide();
  }

   
  }
 
 
 }


 var getInitiatorIditems; var initiatorId;


function GetInitiatorIdForSubmitForAppWFBtn()
{
 var ctx = new SP.ClientContext.get_current();
 var oList = ctx.get_web().get_lists().getByTitle(ndpList);
 var ID = getParam("ID");
 var camlQuery = new SP.CamlQuery();
 var query = "<View><Query><Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>"+ID+"</Value></Eq></Where>";
     query += "<ViewFields> <FieldRef Name='ID' /><FieldRef Name='Author' /><FieldRef Name='Status' /></ViewFields></View></Query>";
 camlQuery.set_viewXml(query);
 getInitiatorIditems = oList.getItems(camlQuery);
 ctx.load(getInitiatorIditems);
 ctx.executeQueryAsync(OnSuccessGetInitiatorId,OnFailGetInitiatorId);

}
function OnSuccessGetInitiatorId()
{
 var count = getInitiatorIditems.get_count();
 if(count>0)
 {
 
  var items = getInitiatorIditems.getEnumerator();
  while (items.moveNext())
     {
     var listItem = items.get_current();
     initiatorId = listItem.get_item("Author").get_lookupId();
  var statusValue = listItem.get_item("Status");
  NWF$('#'+FinalApproval).val(statusValue);
     DisplaySavePnlToInitaitorREQ();
  }
 }
}

function OnFailGetInitiatorId()
{

}

 function RedirectToAllitemsView()
 {
     window.location = ndpListUrl;
 }



 NWF.FormFiller.Events.RegisterAfterReady(function ()
 {
    var isNewMode = document.location.pathname.indexOf("/NewForm.aspx") > -1;
    var isEditMode = document.location.pathname.indexOf("/EditForm.aspx") > -1;
    var isDispMode = document.location.pathname.indexOf("/DispForm.aspx") > -1;
    NWF$('.btnSubmitWFCssAppUI').hide();

 if(isNewMode)
 {
  try
  {
        CheckForRequestorNameInAppLimits();
  }
  catch(e)
  {
   alert("Something wrong went...");
  }
 }

 if(isEditMode)
 {
 try
 {
      DisplayPanalCheckForApproval();

    GetApproversOutCome();
    SP.SOD.executeOrDelayUntilScriptLoaded(GetInitiatorIdForSubmitForAppWFBtn,"sp.js");
 
   var isSubmitForApproval =  NWF$('#' +SubForApproval).val();
   var isREQ =  NWF$('#' +REQ).val();
 if((isSubmitForApproval == 'Yes') && (isREQ == 'No'))
   {
  NWF$('.nf-textbox-wrapper').eq(0).attr('style', 'top: -5px !important;');
  NWF$('.nf-textbox-wrapper').eq(11).attr('style', 'top: -3px !important;');
  NWF$('.nf-textbox-wrapper').eq(2).attr('style', 'top: -3px !important;');
  NWF$('.nf-textbox-wrapper').eq(3).attr('style', 'top: -3px !important;');
  NWF$('.nf-textbox-wrapper').eq(4).attr('style', 'top: -3px !important;');
  NWF$('.nf-textbox-wrapper').eq(5).attr('style', 'top: -3px !important;');
  NWF$('.nf-textbox-wrapper').eq(7).attr('style', 'top: -3px !important;');
  NWF$('.nf-textbox-wrapper').eq(8).attr('style', 'top: -3px !important;');
  NWF$('.nf-textbox-wrapper').eq(9).attr('style', 'top: -3px !important;');
  NWF$('.nf-textbox-wrapper').eq(10).attr('style', 'top: -3px !important;');
   }
   else if((isSubmitForApproval == 'Yes') && (isREQ == 'Yes'))
   {
    NWF$('.nf-textbox-wrapper').eq(0).attr('style', 'top: 0px !important;');
    NWF$('.nf-textbox-wrapper').eq(11).attr('style', 'top: -3px !important;');
   }
 }
   catch(e)
 {
  alert("Something wrong went...");
 }
 }
 });





 function MakeTextReadOnly()
 {

 NWF$('#'+App1).prop("readonly", true);
 NWF$('#'+App2).prop("readonly", true);
 NWF$('#'+App3).prop("readonly", true);
 NWF$('#'+App4).prop("readonly", true);
 NWF$('#'+Rev1).prop("readonly", true);
 NWF$('#'+Rev2).prop("readonly", true);  
 NWF$('#'+App1).attr('style', 'background-color: #e5e9ec !important; border:none !important; width:210px !important');
 NWF$('#'+App2).attr('style', 'background-color: #e5e9ec !important; border:none !important; width:210px !important');
 NWF$('#'+App3).attr('style', 'background-color: #e5e9ec !important; border:none !important; width:210px !important');
 NWF$('#'+App4).attr('style', 'background-color: #e5e9ec !important; border:none !important; width:210px !important');
 NWF$('#'+Rev1).attr('style', 'background-color: #e5e9ec !important; border:none !important; width:210px !important');
 NWF$('#'+Rev2).attr('style', 'background-color: #e5e9ec !important; border:none !important; width:210px !important');

 NWF$('#'+out1).attr('style', 'background-color: #e4e4e4 !important; border:none !important; width:175px !important');
 NWF$('#'+out2).attr('style', 'background-color: #e4e4e4 !important; border:none !important; width:175px !important');
 NWF$('#'+out3).attr('style', 'background-color: #e4e4e4 !important; border:none !important; width:175px !important');
 NWF$('#'+out4).attr('style', 'background-color: #e4e4e4 !important; border:none !important; width:175px !important');
 NWF$('#'+out5).attr('style', 'background-color: #e4e4e4 !important; border:none !important; width:175px !important');
 NWF$('#'+out6).attr('style', 'background-color: #e4e4e4 !important; border:none !important; width:175px !important');

 NWF$('#'+FinalApproval).attr('style', 'background-color: #e4e4e4 !important; border:none !important; width:175px !important; font-weight: bold !important;');  
 NWF$('#'+FinalApproval).prop("readonly", true);  }
 
 var itemAppLimits; var notionalVal;


 function GetApproversInAppLimits()
 {
  notionalVal = NWF$('#' + NotionalVal).val();
  var context  = new SP.ClientContext.get_current();
  var list     = context.get_web().get_lists().getByTitle(listName);
  var camlQuery = new SP.CamlQuery();
  currentWeb = _spPageContextInfo.webServerRelativeUrl;
  var initiatorID = NWF$('.ms-subtleLink').eq(0).attr('href').split('=')[1];
 
 var query ="<View><Query><Where><And><Leq><FieldRef Name='Notional_x0020_Value_x003e_'  /><Value Type='Currency'>"+notionalVal+"</Value>";
    query += "</Leq><And><Geq><FieldRef Name='Notional_x0020_Value_x003c__x003'  /><Value Type='Currency'>"+notionalVal+"</Value>";
    query += "</Geq><Eq><FieldRef Name='TraderID' /><Value Type='Text'>"+initiatorID+"</Value></Eq></And></And></Where></Query></View>";
 
  camlQuery.set_viewXml(query);
  itemAppLimits = list.getItems(camlQuery);
  context.load(itemAppLimits);
  context.executeQueryAsync(onSuccesAppLimitsCall, OnFaiAppLimtslCall);
  }

 var app1;
 function onSuccesAppLimitsCall(sender, args)
 {  
   var count = itemAppLimits.get_count();
   var userId;
   if(count > 0)
   {
     var items = itemAppLimits.getEnumerator();
     while (items.moveNext())
     {
    var listItem = items.get_current();
   
     app1 = listItem.get_item("_x0031_st_x0020_Level_x0020_Appr");
   
    if(app1)
    {
     app1 = listItem.get_item("_x0031_st_x0020_Level_x0020_Appr").get_lookupValue();
  userId = listItem.get_item("_x0031_st_x0020_Level_x0020_Appr").get_lookupId();
     NWF$('#' + App1).val(app1);
  approvers.push(userId+";"+app1+";app1");
    }
    else
      NWF$('#' + App1).val("");
 
    var app2 = listItem.get_item("_x0032_nd_x0020_Level_x0020_Appr");
    if(app2)
    {
      app2 = listItem.get_item("_x0032_nd_x0020_Level_x0020_Appr").get_lookupValue();
   userId = listItem.get_item("_x0032_nd_x0020_Level_x0020_Appr").get_lookupId();
      NWF$('#' + App2).val(app2);
   approvers.push(userId+";"+app2+";app2");
    }
    else
     NWF$('#' + App2).val("");
 
    var app3 = listItem.get_item("_x0033_rd_x0020_Level_x0020_Appr");
    if(app3)
    {
     app3 = listItem.get_item("_x0033_rd_x0020_Level_x0020_Appr").get_lookupValue();
  userId = listItem.get_item("_x0033_rd_x0020_Level_x0020_Appr").get_lookupId();
     NWF$('#' + App3).val(app3);
  approvers.push(userId+";"+app3+";app3");
    }
    else
     NWF$('#' + App3).val("");
 
    var app4 = listItem.get_item("_x0034_th_x0020_Level_x0020_Appr");
    if(app4)
    {
      app4 = listItem.get_item("_x0034_th_x0020_Level_x0020_Appr").get_lookupValue();
   userId = listItem.get_item("_x0034_th_x0020_Level_x0020_Appr").get_lookupId();
      NWF$('#' + App4).val(app4);
   approvers.push(userId+";"+app4+";app4");
    }
    else
    NWF$('#' + App4).val("");
 
       var rev1 = listItem.get_item("_x0031_st_x0020_Level_x0020_Revi");
    if(rev1)
    {
     rev1 = listItem.get_item("_x0031_st_x0020_Level_x0020_Revi").get_lookupValue();
  userId = listItem.get_item("_x0031_st_x0020_Level_x0020_Revi").get_lookupId();
     NWF$('#' + Rev1).val(rev1);
  approvers.push(userId+";"+rev1+";rev1");
    }
    else
     NWF$('#' + Rev1).val("");
 
    var rev2 = listItem.get_item("_x0032_nd_x0020_Level_x0020_Revi");
    if(rev2)
    {
      rev2 = listItem.get_item("_x0032_nd_x0020_Level_x0020_Revi").get_lookupValue();
   userId = listItem.get_item("_x0032_nd_x0020_Level_x0020_Revi").get_lookupId();
      NWF$('#' + Rev2).val(rev2);
   approvers.push(userId+";"+rev2+";rev2");
    }
    else
     NWF$('#' + Rev2).val("");     }
   
   }
 
   MakeTextReadOnly();
 }
 function OnFaiAppLimtslCall(sender, args)
 { }



 var finalApprovers =[]; var appName;


 function ClearAllFields()
 {
  NWF$('#' + App1).val("");
  NWF$('#' + App2).val("");
  NWF$('#' + App3).val("");
  NWF$('#' + App4).val("");
  NWF$('#' + Rev1).val("");
  NWF$('#' + Rev2).val("");
 }

 function SetWFApproversOutcome()
 {
   var i; var j; var WFOut;

    for(i = 0; i < approvers.length; i++)
    {
        for(j = 0; j < WFUsers.length; j++)
        {
             appName = approvers[i].split(';')[0];
             if(appName == WFUsers[j])
              {
      var reviewer = approvers[i].split(';')[2];
      if(reviewer == "rev1")
      {
      if(WFUsersOutcome[j] == "Approve")
      {
    NWF$(".revCss1").val("Reviewed");
   }
      else
      {
    NWF$(".revCss1").val(WFUsersOutcome[j]);
   }
      }
      else if(reviewer == "rev2")
      {
      if(WFUsersOutcome[j] == "Approve")
      {
    NWF$(".revCss2").val("Reviewed");
    }
      else
      {
    NWF$(".revCss2").val(WFUsersOutcome[j]);
   }
      }
      else
      {                
     var apps = "outCss"+(i+1);
     if(WFUsersOutcome[j] == "Approve")
     {
      NWF$("."+apps).val("Approved");
     }
     else
    {
     NWF$("."+apps).val(WFUsersOutcome[j]);
     }
   
      }
                  break;
              }
        }
 
  if(WFUsersOutcome[j])
  { WFOut = WFUsersOutcome[j]; }
  else{ WFOut ='0';}
 
  finalApprovers.push({
      key:  approvers[i].split(';')[0],
      value:WFOut,
      UName: approvers[i].split(';')[1],
   type: approvers[i].split(';')[2]
   });
    console.log(finalApprovers);
  }
   NWF$('#'+out1).prop("readonly", true);
   NWF$('#'+out2).prop("readonly", true);
   NWF$('#'+out3).prop("readonly", true);
   NWF$('#'+out4).prop("readonly", true);
   NWF$('#'+out5).prop("readonly", true);
   NWF$('#'+out6).prop("readonly", true);

 }  
 
 var outcomeItems; var outcomeResult;

 function GetApproversOutCome(userId)
 {
  var ID = getParam("ID");
  var ctx = new SP.ClientContext.get_current();
  var list = ctx.get_web().get_lists().getByTitle(taskListName);
  currentWeb = _spPageContextInfo.webServerRelativeUrl;
  var camlQuery = new SP.CamlQuery();
 
  var query  = "<View><Query><Where><Eq><FieldRef Name='WorkflowItemId' /><Value Type='Text'>"+ID+"</Value></Eq></Where>";
       query += "<OrderBy><FieldRef Name='ID' Ascending='False' /></OrderBy></Query></View>";  
  camlQuery.set_viewXml(query);
  outcomeItems = list.getItems(camlQuery);
  ctx.load(outcomeItems);
  ctx.executeQueryAsync(onSuccesApproversOutComeCall,onfailOutComeCall);
 }

 var WFUsers = [];
 var WFUsersOutcome = [];


 function onSuccesApproversOutComeCall()
 {
   var count = outcomeItems.get_count();
   var userId;
   if(count > 0)
   {
     var items = outcomeItems.getEnumerator();
     while (items.moveNext())
     {
    var listItem = items.get_current();
    outcomeResult = listItem.get_item("WorkflowOutcome");
    var uId  = listItem.get_item("AssignedTo").get_lookupId();
    WFUsers.push(uId);
    WFUsersOutcome.push(outcomeResult);
     }
  try
  {
     SetWFApproversOutcome();
  }
    catch(e)
    {
     alert("Something went wrong... ");
    }
   }
 }
 function onfailOutComeCall()
 {
 }
  function getParam(param) {
  var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
  for (var i=0;i<url.length;i++) {
         var params = url[i].split("=");
         if(params[0] == param)
          return params[1];
  }
 }
 
  var pendingItems; var taskItemId;
 
 function DisplayPanalCheckForApproval()
 {
  var ID = getParam("ID");
  var ctx = new SP.ClientContext.get_current();
  var list = ctx.get_web().get_lists().getByTitle(taskListName);
  currentWeb = _spPageContextInfo.webServerRelativeUrl;
  var camlQuery = new SP.CamlQuery();
 
 var query = "<View><Query><Where><And><Eq><FieldRef Name='AssignedTo' LookupId='True'/><Value Type='User'>"+_spPageContextInfo.userId+"</Value></Eq><And><Eq><FieldRef Name='WorkflowOutcome' />";
        query += "<Value Type='Text'>Pending</Value></Eq><Eq><FieldRef Name='WorkflowItemId' /><Value Type='Text'>"+ID+"</Value></Eq></And></And>";
  query += "</Where></Query></View>";
   
  camlQuery.set_viewXml(query);
  pendingItems = list.getItems(camlQuery);
     ctx.load(pendingItems);
     ctx.executeQueryAsync(onSuccesPendingTasksCall, OnFailPendingTasksCall);
 
 }


 function onSuccesPendingTasksCall()
 {
  var count = pendingItems.get_count();
  if(count > 0)
  {
  var items = pendingItems.getEnumerator();
  while (items.moveNext())
  {
    var listItem = items.get_current();
    taskItemId = listItem.get_id();
 
  }
   
   NWF$(".ApprovalPnlClass").show();
   NWF$('#'+Appbtn).val("1");
  }
  else
  {
   NWF$(".ApprovalPnlClass").hide();
   NWF$('#'+Appbtn).val("0");
  }
 }
 function OnFailPendingTasksCall()
 {}
   

//-------------------------------Tasks Logs ---------------------------
var tasklistItems;
function GetAllTasksComments()
{
  var ID = getParam("ID");
  var ctx = new SP.ClientContext.get_current();
  var list = ctx.get_web().get_lists().getByTitle(taskListName);
  var camlQuery = new SP.CamlQuery();
  var query = "<View><Query><Where><Eq><FieldRef Name='WorkflowItemId'/><Value Type='text'>"+ID+"</Value></Eq></Where><OrderBy><FieldRef Name='ID' Ascending='True' /></OrderBy>";
      query += "<ViewFields><FieldRef Name='Title' /><FieldRef Name='AssignedTo' /><FieldRef Name='ApproverComments' /><FieldRef Name='WorkflowOutcome' /></ViewFields></Query></View>";
  camlQuery.set_viewXml(query);
  tasklistItems = list.getItems(camlQuery);
  ctx.load(tasklistItems);
  ctx.executeQueryAsync(OnSuccessGetTaskComments,OnfailGetTaskComments);
}  function OnSuccessGetTaskComments()
 {
  var itemCount = tasklistItems.get_count();
  if(itemCount > 0)
  {
   var divHtml ="<table class='CommentTable '><thead><tr><th>Approvers</th><th>Log</th><th>Comments</th></tr></thead><tbody>";
   var items = tasklistItems.getEnumerator();
   var i=1;   var nextApp; var log; var submitedDate;
 
   while (items.moveNext())
   {
    var listitems = items.get_current();
    var app =  listitems.get_item('AssignedTo').get_lookupValue();
    var outcome = listitems.get_item('WorkflowOutcome');
    var comments =  listitems.get_item('ApproverComments');
    var taskTitle =  listitems.get_item('Title');
    var modifyDate = new Date(listitems.get_item('Modified')).toLocaleString();
    var CreatedDate = new Date(listitems.get_item('Created')).toLocaleString();


 log = "<ul>";
 if(!comments)
   comments ='-';  
   if(i==1)
   {
    requestor = 'Requestor';
 

 if(outcome =='Approve' && taskTitle.indexOf("Request More Information") > -1)
 {
  log = "<li>Submitted to "+app+" for Request more Information by by "+requestor +" on "+CreatedDate+" </li>";
  log += "<li>Approved by "+app+"  on "+modifyDate+" </li>";
 }
 else if(outcome =='Approve')
 {
  log = "<li>Submitted to "+app+" for approval by "+requestor +" on "+CreatedDate+" </li>";
  log += "<li>Approved by "+app+"  on "+modifyDate+" </li>";
 }

 if(outcome =='Request more Information')
 {
   log = "<li>Submitted to "+app+" for Request more Information by "+requestor +" on "+CreatedDate+" </li>";
   log += "<li>Request more Information by "+app+"  on "+modifyDate+" </li>";
 }
 if(outcome =='Reject')
 {
   log = "<li>Submitted to "+app+" for approval by "+requestor +" on "+CreatedDate+" </li>";
   log += "<li>Rejected by "+app+"  on "+modifyDate+" </li>";
 
    }
    if(outcome =='Pending')
    {
     log = "<li>Submitted to "+app+" for approval by "+requestor +" on "+CreatedDate+" </li>";
    }
    submitedDate = modifyDate;
    nextApp = app;
   }
   else
   {  
 
    if(outcome =='Approve' && taskTitle.indexOf("Review") > -1)
 {
   log = "<li>Submitted to "+app+" for review by "+nextApp +" on "+submitedDate+" </li>";
      log += "<li>Reviewed by "+app+"  on "+modifyDate+" </li>";
 }
 else if(outcome =='Approve' && taskTitle.indexOf("Request More Information") > -1)
 {
   log = "<li>Submitted to "+app+" for Request More Information by "+nextApp +" on "+submitedDate+" </li>";
      log += "<li>Approved by "+app+"  on "+modifyDate+" </li>";
 }
    else if(outcome =='Approve')
    {
     log = "<li> Submitted to "+app+" for approval by "+nextApp +" on "+submitedDate+" </li>";
     log += "<li>Approved by "+app+"  on "+modifyDate+" </li>";
    }

 if(outcome =='Request more Information' && taskTitle.indexOf("Review") > -1)
    {
      log = "<li> Submitted to "+app+" for review by "+nextApp +" on "+submitedDate+" </li>";
      log += "<li>Request more Information by "+app+"  on "+modifyDate+" </li>";
    }
    else if(outcome =='Request more Information')
    {
      log = "<li> Submitted to "+app+" for approval by "+nextApp +" on "+submitedDate+" </li>";
      log += "<li>Request more Information by "+app+"  on "+modifyDate+" </li>";
    }
    if(outcome =='Reject')
    {
      log = "<li> Submitted to "+app+" for approval by "+nextApp +" on "+submitedDate+" </li>";
    log += "<li>Rejected by "+app+"  on "+modifyDate+" </li>";
 }

 if(outcome =='Pending' && taskTitle.indexOf("Review") > -1)
    {
      log = "Submitted to "+app+" for Review by "+nextApp +" on "+submitedDate+" ";
    }
    else if(outcome =='Pending' && taskTitle.indexOf("Request More Information") > -1)
    {
      log = "Submitted to "+app+" for Request More Information by "+nextApp +" on "+submitedDate+" ";
    }
 else if(outcome =='Pending')
 {
    log = "Submitted to "+app+" for approval by "+nextApp +" on "+submitedDate+" ";
 }
 
     log += "</ul>";

     nextApp = app;
     submitedDate = modifyDate;
   }
 
     i = i+1;
 
    divHtml +="<tr><td width='120px'>"+app+"</td><td width='250px'>"+log+"</td><td>"+comments+"</td></tr>";
  }
 
  divHtml +="</tbody></table>";
  var txtArea = NWF$('#'+ LogBox).closest('tr').find('div[id$="_inplacerte"]').eq(1).html(divHtml);NWF$('#'+ LogBox).closest('tr').find('div[id$="_inplacerte"]').eq(1).css('overflow-x','hidden');
  NWF$('#'+ LogBox).closest('tr').find('div[id$="_inplacerte"]').eq(1).css('border','none');
  NWF$('#'+ LogBox).closest('tr').find('div[id$="_inplacerte"]').eq(1).css('width','100%');
  NWF$('#'+ LogBox).closest('tr').find('div[id$="_inplacerte"]').eq(1).attr("contentEditable","false");
  NWF$('#'+LogBox).prop("readonly", true);

       
 }
} function OnfailGetTaskComments()
 {
 
 }  

 var approveOrReview = "Approve";

 function CheckMsgForLastUserInWF()
 {
  var i = 0; var userMessage; var flag = '0';
  for(i=0 ; i<finalApprovers.length ;i++)
  {
   var currentUserid = _spPageContextInfo.userId;
 
   if(finalApprovers[i].key == currentUserid && finalApprovers[i].value == 'Pending')
   {
    if(finalApprovers[i+1])
    {
  if(finalApprovers[i+1].type == "rev1" || finalApprovers[i+1].type == "rev2")
  {
      if(finalApprovers[i+1].type == "rev2")
   {
       userMessage = "Once you review this new deal, it will be sent to "+finalApprovers[i+1].UName+" for review.  Are you sure you want to continue?";
   }
   else
   {
    userMessage = "Once you approve this new deal, it will be sent to "+finalApprovers[i+1].UName+" for review.  Are you sure you want to continue?";
   }
 
  }
  else
  {
           userMessage = "Once you approve this new deal, it will be sent to "+finalApprovers[i+1].UName+" for approval.  Are you sure you want to continue?";
        }
    }
    else
    {
  if(finalApprovers[i].type == "rev1" || finalApprovers[i].type == "rev2")
  {
    userMessage = "You are about to review this New deal. Are you sure you want to continue?" ;
 
  }
  else
  {
     userMessage = "You are about to approve this New deal. Are you sure you want to continue?" ;
  }
    }
     
    flag = '1';
   }
    if(flag == '0')
   {
     userMessage = "Once you approve this new deal, it will be sent to "+finalApprovers[0].UName+" for approval.  Are you sure you want to continue?";
   }
 
  }
  if(userMessage.indexOf("review") > -1 && userMessage.indexOf("approve") == -1)
  {
   approveOrReview = "review";
  }
  return userMessage;
 }


 function ApproverAction(outcome)
 {
   
    var value = outcome.split('-')[0];
    var result;
 
    if(value =='Approve')
    {
  result = confirm(CheckMsgForLastUserInWF());
 
   if(result)
    {
  try
   {
       UpdateTaskList(outcome);
   }
   catch(e)
   {
    alert("Something went wrong...");
   }
 }
    return;
    }
 if(value =='Reject')
    {
     result = confirm("Are you sure you want to Reject New Deal?");
  if(result)
  {
   var value = NWF$('#'+ CommentBox).val();
   if(!value)
   {
    alert("Enter your Remarks before rejecting the New Deal.");
    return;
   }
   else
   {
   try
   {
       UpdateTaskList(outcome);
   }
   catch(e)
   {
    alert("Something went wrong...");
   }
   
   }
  }
    }
  if(value =='Request more Information')
    {
      result = confirm("Are you sure you want to Request for More information?");
   if(result)
   {
    var value = NWF$('#'+ CommentBox).val();
    if(!value)
    {
     alert("Enter your Remarks before Requesting More information.");
     return;
    }
    else
    {
   try
   {
       UpdateTaskList(outcome);
   }
   catch(e)
   {
    alert("Something went wrong...");
   }
 
 }
   }
 }
 
 }

  var outcomeValue;
  function UpdateTaskList(outcome)
  {
  outcomeValue =  outcome.split('-')[0];
 var outcomeId =  outcome.split('-')[1];
 var comments = NWF$('#'+ CommentBox).val();
 
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle(taskListName);
 
    oListItem = oList.getItemById(taskItemId);
    oListItem.set_item('WorkflowOutcome', outcomeValue);
    oListItem.set_item('Completed',true);
    oListItem.set_item('PercentComplete',1);
    oListItem.set_item('Status','Completed');
    oListItem.set_item('FormData','Completed');
    oListItem.set_item('Decision',outcomeId);
    oListItem.set_item('ApproverComments',comments);

    oListItem.update();
 clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryUpdateTaskSucceeded), Function.createDelegate(this, this.onQueryUpdateTaskFailed));
  }
 
function onQueryUpdateTaskSucceeded()
  {
   var isREQ =  NWF$('#' +REQ).val();
   var url = window.location.href;
   if(outcomeValue =="Approve")
   {
    if(approveOrReview == "review")
    {
      alert("New Deal request is Reviewed");  
    }
    else if(isREQ == 'Yes')
    {
     alert('New Deal is sent for Approval');
    }
   else
   {
     alert("New Deal request is Approved");
      window.location.href = window.location;
   }
     
     
   }
   if(outcomeValue =="Reject")
   {
    alert("New Deal request is Rejected");
     
   }
   if(outcomeValue =="Request more Information")
   {
    requestor =  'Requestor';
    alert("New Deal request is sent to "+requestor+" for Request more Information");
 
   }
   
     location.reload(true);

  }
 
  function onQueryUpdateTaskFailed()
  {
    alert("Something went wrong...");
  }
 


 var itemsColl; var currentWeb; var notionvalueGTval; var notionvalueLTval; var isValid;

 function CheckForRequestorNameInAppLimits()
 {
  var context  = new SP.ClientContext.get_current();
  var list     = context.get_web().get_lists().getByTitle(listName);
  var camlQuery = new SP.CamlQuery();
  currentWeb = _spPageContextInfo.webServerRelativeUrl;
 
  camlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='TraderID' /><Value Type='Text'>"+_spPageContextInfo.userId+"</Value></Eq></Where></Query></View>");
  itemsColl = list.getItems(camlQuery);
  context.load(itemsColl);
  context.executeQueryAsync(onSuccesCall, OnFailCall);
  }

 function onSuccesCall(sender, args)
 {
  var count = itemsColl.get_count();
 
 if(count > 0)
  {
    var items = itemsColl.getEnumerator();
    while(items.moveNext())
    {
      var notionalValue = NWF$('#'+NotionalVal).val();
      if(notionalValue)
      {
  var listItem = items.get_current();
  notionvalueGTval = listItem.get_item("Notional_x0020_Value_x003e_");
  notionvalueLTval = listItem.get_item("Notional_x0020_Value_x003c__x003");
  var notionalValue = NWF$('#'+NotionalVal).val();
   if(notionalValue >= notionvalueGTval && notionalValue <= notionvalueLTval)
   {
     
    var result = confirm("This New Deal will be submitted  to "+app1+" for approval. Are you sure you want to continue ?");
    if(result)
    {
      try
   {
         SubmitApproval();
   }
   catch(e)
   {
    alert("Something went wrong...");
   }
    }
    else
    {
     return;
    }
   }
   else
   {
      NWF$('.btnSubmitWFCss').eq(1).attr('disabled','disabled');
     alert("Unable to populate approvers for this new deal. Please contact your administrator to ensure that there is an approval limit for this notional value for your approver’s type in the Approver Limits");
   }
        }
     }
  }
  else
  {
   alert('Your are not part of Approval Limits, Contact your administrator/site owner to have your name added to the Approval Limits & Approvers Profile Form.');
   window.location =  ndpListUrl;
  }
  return isValid;
 }
 
 function OnFailCall(sender, args)
 {
  alert("Something went wrong...");
 }



 function SubmitForApproval(outcome)
 {
  var isREQ =  NWF$('#' +REQ).val();
  var IsSubmitForApproval =  NWF$('#' +SubForApproval).val();
  var currentUid = _spPageContextInfo.userId;

   var result = confirm("This New Deal will be submitted  to "+app1+" for approval. Are you sure you want to continue ?");
   if(result)
   {
     if(currentUid == initiatorId && isREQ == 'Yes' && IsSubmitForApproval == 'Yes')
       {
    var value = NWF$('#'+ CommentBox).val();
    if(!value)
    {
          alert("Enter your Remarks before submitting the New Deal.");
          return;
    }
    else
    {
      try
   {
       UpdateTaskList(outcome);
   }
   catch(e)
   {
    alert("Something went wrong...");
   }
    }
  }
  else
   {
      try
   {
         SubmitApproval();
   }
   catch(e)
   {
    alert("Something went wrong...");
   }
   }
   }
   return;
 }  
 
 
 
var modalDialog;

function SubmitApproval()
{
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle(ndpList);
    var ID = getParam("ID");
 var notionalValue = NWF$('#'+NotionalVal).val();
 oListItem = oList.getItemById(ID);
 oListItem.set_item('SubmitForApproval','Yes');
 oListItem.set_item('Status','InProgress');
 oListItem.set_item('National_x0020_Value',notionalValue);
 oListItem.update();
  modalDialog = SP.UI.ModalDialog.showWaitScreenWithNoClose('Submitting New Deal for approval...');
 clientContext.executeQueryAsync(OnSuccessSubmitForApproval,OnFailSubmitForApproval);
}
function OnSuccessSubmitForApproval()
{
 modalDialog.close(0);
 alert('New Deal is sent for Approval');
 window.location = ndpListUrl;

}
function OnFailSubmitForApproval()
{
 RedirectToAllitemsView();
}
    

Get PeoplePicker Value on Nintex form -(Approval Limits)



 var traderList = 'Trader/Approver';var approversList = 'Approval Limits';


 NWF.FormFiller.Events.RegisterAfterReady(function()
{  
   NWF$('.ip-container').eq(0).addClass('ip-container nf-filler-highlightonvalidationerror ip-disabled');
   NWF$('.ip-container').eq(0).attr('style','background-color: #dedede !important; border:none !important;height:28px');
   NWF$('#'+approverType).attr('style', 'background-color: #dedede !important; border:none !important;width:458px;height:28px');
   NWF$('#'+approverType).prop("readonly", true);     NWF$('#'+traderDdl).change(function()
    {
     var id = NWF$('#'+traderDdl).val().split(';')[0];
             GetManagerOfTrader(id);
     });

});
var items;
function GetManagerOfTrader(Id)
{
  var ctx = new SP.ClientContext.get_current();
  var list = ctx.get_web().get_lists().getByTitle(traderList);
  var camlQuery = new SP.CamlQuery();
  var query = "<View><Query><Where><Eq><FieldRef Name='ID'/><Value Type='Number'>"+Id+"</Value></Eq></Where></Query></View>";
 
  camlQuery.set_viewXml(query);
  items = list.getItems(camlQuery);
  ctx.load(items);
  ctx.executeQueryAsync(OnSuccess,Onfail);
}
function OnSuccess()
{
 var count = items.get_count();
 if(count > 0)
 {
  var listItems = items.getEnumerator();
  while(listItems.moveNext())
  {
    var item = listItems.get_current();
    var managerName = item.get_item("Approver").get_lookupValue();
    var managerId = item.get_item("Approver").get_lookupId();
   // var approvertype = item.get_item("ApproverTypeLabel");
 var managerId = item.get_item("Approver").get_lookupId();

 var traderId = item.get_item("Trader").get_lookupId();
 var AppType = item.get_item("Approver_x0020_Type").get_lookupValue();
 
      //  NWF$('#'+FirstApprover).prop("readonly", true);
    var approverPicker = new NF.PeoplePickerApi('#' + FirstApprover);
 
 approverPicker.clear();

// RemoveOtherAppInApp1Field();
    var waitscreen = SP.UI.ModalDialog.showWaitScreenWithNoClose('Working on it...');
    approverPicker.search(managerName).done(function (data) {
                //add line manager to people picker field
    approverPicker.clear();
                approverPicker.add(data[0]);
                waitscreen.close(0);
                NWF$('.ip-item span div').eq(1).removeClass('ip-close');
             
             });
 
    NWF$('#'+approverType).val(AppType);      NWF$('#'+traderIdtext).val(traderId);

  }
 }
}
function Onfail()
{}


 function RemoveOtherAppInApp1Field()
 {
 var len = NWF$('.ip-disabled div.ip-item').length;
 if(len > 0)
 {
  for(var i=0;i<len;i++)
  {
   NWF$('.ip-disabled div.ip-item').eq(i).remove();
  }
 }
 }

Call the Service from JQuery

Call the Service from JQuery

The following demonstrates how to call the service from a Script Editor Web Part using simple HTML, JavaScript and JQuery.
source: Source
  1. <script src="http://sp13.dev/SiteAssets/jquery-1.10.2.min.js"></script>
    
    <h2>SharePoint 2013: Consume a custom WCF REST service hosted in SharePoint 2013.</h2>
    <h3>This is a quick sample to demonstrate calling a custom SharePoint-hosted WCF REST service from a
        Script Editor Web Part using simple HTML, JavaScript and JQuery.
    </h3>
    
    <div>
        <br />
        <p id="message">Loading presidents...</p>
    </div>
    
    <div id="resultsPanel"></div>
    
    <script type="text/javascript">
        $(document).ready(function () {
            getPresidentsData();
        });
      
    function getPresidentsData() {
        var serviceUri = _spPageContextInfo.webAbsoluteUrl +
            "/_vti_bin/BarkesServices/PresidentsService.svc/GetAllPresidents";
        $.ajax({
            type: "GET",
            contentType: "application/json",
            url: serviceUri,
            dataType: "json",
            success:
                function (response) {
                    showPresidentsList(response);
                    $('#message').html("<a href=" + serviceUri + ">" + serviceUri + "</a>");
                },
            error:
                function (err) {
                    alert(err);
                }
        });
    }
    
    function showPresidentsList(presidentsData) {
        $.each(presidentsData, function () {
            $('#resultsPanel').append($(this)[0].Id + ' - ');
            $('#resultsPanel').append($(this)[0].FirstName + ' ');
            $('#resultsPanel').append($(this)[0].LastName + ' (');
            $('#resultsPanel').append($(this)[0].EmailAddress + ')');
            $('#resultsPanel').append('<br><br>');
        });
    }
    </script>

Friday, June 30, 2017

Set people picker value to nintex form field by javascript

Set people picker value to nintex form field by javascript


var traderList = 'XYZ';
var approversList = 'ABC';

NWF.FormFiller.Events.RegisterAfterReady(function()
{
   NWF$('#'+traderDdl).change(function() 
    {
      // alert(NWF$('#'+traderDdl).val());
    var id =NWF$('#'+traderDdl).val().split(';')[0];
   // alert(id);
    GetManagerOfTrader(id);
    });
});



var items;
function GetManagerOfTrader(Id)
{
  var ctx = new SP.ClientContext.get_current();
  var list = ctx.get_web().get_lists().getByTitle(traderList);
  var camlQuery = new SP.CamlQuery(); 
  var query = "<View><Query><Where><Eq><FieldRef Name='ID'/><Value Type='Number'>"+Id+"</Value></Eq></Where></Query></View>";
   
  camlQuery.set_viewXml(query);
  items = list.getItems(camlQuery);
  ctx.load(items);
  ctx.executeQueryAsync(OnSuccess,Onfail);
}
function OnSuccess()
{
 var count = items.get_count();
 if(count > 0)
 {
  var listItems = items.getEnumerator();
  while(listItems.moveNext())
  {
    var item = listItems.get_current();
    var managerName = item.get_item("Approver").get_lookupValue();
    var managerId = item.get_item("Approver").get_lookupId();
             alert(managerName+"-"+managerId);
       
    var approverPicker = new NF.PeoplePickerApi('#' + FirstApprover);
    var waitscreen = SP.UI.ModalDialog.showWaitScreenWithNoClose('Working on it...');  
    approverPicker.search(managerName).done(function (data) {
                //add line manager to people picker field
                approverPicker.add(data[0]);
    waitscreen.close(0);
             });
   
   
  }
 }
}
function Onfail()
{
 alert('failed')
}

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'); 
    } 
 
}