Friday, February 17, 2017

Dynamic SiteURL & RestURL call with X-RequestDigest Sharepoint


siteUrl = _spPageContextInfo.webAbsoluteUrl;

var restUrlnew = siteUrl + "/_api/web/lists/getbytitle('" + priviewList + "')/items(" + itemid+ ")?$select=Downloads";
            $.ajax({
                url: restUrlnew,
                method: "GET",
       headers: { "Accept": "application/json; odata=verbose",
       "X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
        },                
                async: false,
                success: function (data) {

Change DATE Format DDMMYYYY OR MMDDYY


Function to get DD MM YYYY  OR MMDDYY


function formattedDate(date) {
    var d = new Date(date || Date.now()),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
   year = d.getFullYear();
   if (month.length < 2) month = '0' + month;
   if (day.length < 2) day = '0' + day;
   return [day,month,year].join('/');
}

Updating Sp list onclick of download or Open button

On click of download and Open button in document preview



//onClick of open button
        $('.preview-template').on('click', '.open-test', function (ev) {
            //ev.preventDefault();          
            updateToDownloadDetails();
            //window.location.href=serviceURL;        
        });

        //ONCLICK OF download
        $('.preview-template').on('click', '.download-test', function (ev) {
            //ev.preventDefault();
            updateToDownloadDetails();
        });
       

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

function updateToDownloadDetails() {
    try {
        var DownloadDate = new Date();
        var DownloadBy = CurrentUserID;
        DownloadCount = 1;
        var itemID = rowID;
        var listItem = ["Title", downloadURL, DownloadDate, DownloadBy, DownloadCount, olistName];
        clientContext = new SP.ClientContext(siteUrl);
        oList = clientContext.get_web().get_lists().getByTitle(downloadListName);
        var itemCreateInfo = new SP.ListItemCreationInformation();
        oListItem = oList.addItem(itemCreateInfo);
        oListItem.set_item('Title', "New Title");
        oListItem.set_item('DocumentUrl', listItem[1]);
        oListItem.set_item('DownloadDate', listItem[2]);
        oListItem.set_item('DownloadBy', listItem[3]);
        oListItem.set_item('DownloadCount', listItem[4]);
        oListItem.set_item('SourceLibrary', listItem[5]);
        oListItem.update();
        clientContext.executeQueryAsync
       (
           Function.createDelegate(this, function () { onSucceededDownloadUpdates(olistName,rowID); }),
           Function.createDelegate(this, this.onSucceededDownloadUpdates(olistName,rowID))
       );  
      }
       
        catch (err) {
            console.log(err.message);
        }
        }

function onSucceededDownloadUpdates(priviewList,itemid) {
GetDownloadCount(priviewList,itemid)
    console.log('Item updated!');
}

function onFailedDownloadUpdates(sender, args) {
    console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    return false;
}

function GetDownloadCount(olistName,itemid){
 try {
           var restUrlnew = siteUrl + "/_api/web/lists/getbytitle('" + olistName+ "')/items(" + itemid+ ")?$select=Downloads";
            $.ajax({
                url: restUrlnew,
                method: "GET",
       headers: { "Accept": "application/json; odata=verbose",
       "X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
        },                
                async: false,
                success: function (data) {
                var count=data.d.Downloads;
                UpdateListData(olistName,itemid,count);
                     }, //succss function
                error: function (data) {
                    alert("error");
                }
            });
        }        
        catch (err) {
            console.log(err.message);
        }            
}

function UpdateListData(ListName,itemId,cntdownloads) {
    try{
        var oList = clientContext.get_web().get_lists().getByTitle(ListName);
        var oListItem = oList.getItemById(itemId);
        var Count;
        Count=cntdownloads+1;
        oListItem.set_item('Downloads', Count);
        oListItem.update();
        clientContext.load(oListItem);
        clientContext.executeQueryAsync
           (
               Function.createDelegate(this, function () { onQuerySucceededUpdateList(); }),
               Function.createDelegate(this, this.onQueryFailed)
           );
    }
    catch(err){
        console.log(err.message);
    }
}

function onQuerySucceededUpdateList() {
    console.log('Item updated!');
     location.reload(false);
}
---------------------




Thursday, January 12, 2017

LIST OF INTERNAL NAMES FOR SHAREPOINT FIELDS

TITLEINTERNAL NAME
Approval Status_ModerationStatus
Approver Comments_ModerationComments
Check In Comment_CheckinComment
Checked Out ToCheckoutUser
Checked Out ToCheckedOutTitle
Checked Out ToLinkCheckedOutTitle
Content TypeContentType
Content Type IDContentTypeId
Copy Source_CopySource
CreatedCreated
CreatedCreated_x0020_Date
Created ByAuthor
Document Created ByCreated_x0020_By
Document Modified ByModified_x0020_By
EditEdit
Edit Menu Table End_EditMenuTableEnd
Edit Menu Table Start_EditMenuTableStart
Effective Permissions MaskPermMask
Encoded Absolute URLEncodedAbsUrl
File SizeFile_x0020_Size
File SizeFileSizeDisplay
File TypeFile_x0020_Type
GUIDGUID
Has Copy Destinations_HasCopyDestinations
Html File Linkxd_ProgID
HTML File TypeHTML_x0020_File_x0020_Type
IDID
ID of the User who has the item Checked OutCheckedOutUserId
Instance IDInstanceID
Is Checked out to localIsCheckedoutToLocal
Is Current Version_IsCurrentVersion
Is Signedxd_Signature
Item TypeFSObjType
Level_Level
MergeCombine
ModifiedModified
ModifiedLast_x0020_Modified
Modified ByEditor
NameFileLeafRef
NameLinkFilenameNoMenu
NameLinkFilename
NameBaseName
OrderOrder
owshiddenversionowshiddenversion
PathFileDirRef
ProgIdProgId
Property BagMetaInfo
RelinkRepairDocument
ScopeIdScopeId
SelectSelectTitle
SelectSelectFilename
Server Relative URLServerUrl
Shared File Index_SharedFileIndex
Source Name (Converted Document)ParentLeafName
Source Url_SourceUrl
Source Version (Converted Document)ParentVersionString
Template LinkTemplateUrl
TitleTitle
TypeDocIcon
UI Version_UIVersion
Unique IdUniqueId
URL PathFileRef
Version_UIVersionString
Virus StatusVirusStatus
Workflow Instance IDWorkflowInstanceID
Workflow VersionWorkflowVersion
Reference
http://blog.softartisans.com/2009/12/08/list-of-internal-names-for-sharepoint-fields/

Get LookUp and Author Name Using REST API + SharePoint 2013

How to get Author/Title or Name from AuthorID = dataResults.Title

function getUser(id, tdHtml){

var returnValue;
 jQuery.ajax({
  url: "https://YourSite/_api/Web/GetUserById(" + id + ")",
  type: "GET",
  headers: { "Accept": "application/json;odata=verbose" },
  success: function(data) {
         var dataResults = data.d;
      alert(dataResults.Title);
   
  }
});
}

How to get Author/Title or Name from AuthorID in one single Rest call / query


/_api/web/lists/getbytitle('KhaitanDocLib')/items?$select=Author/Title,PracticeArea/Title&$expand=Author/Id,PracticeArea


Wednesday, January 11, 2017

REST URLS to get items from DOCUMENT Library

To get MetaData details
https://gkms.sharepoint.com/sites/Khaitan/_api/web/lists/getbytitle('KhaitanDocLib')/items("+rowID+")

To get Document Properties like Name and etc
https://gkms.sharepoint.com/sites/Khaitan/_api/web/lists/getbytitle('KhaitanDocLib')/items("+ItemID+")/File

Custom Document Preview on Click of Document Link in GRID ( DataTable)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <script type="text/javascript" src="https://gkms.sharepoint.com/sites/Khaitan/SiteAssets/jquery-3.1.1.js"></script>
    <script type="text/javascript" src="https://gkms.sharepoint.com/sites/Khaitan/SiteAssets/jeditable.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.13/datatables.min.css" />
    <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.13/datatables.min.js"></script>

    <script type="text/javascript" src="https://gkms.sharepoint.com/sites/Khaitan/SiteAssets/jquery.SPServices-2014.02.js"></script>

    <script type="text/javascript" charset="utf-8">
       $(document).ready(function () {
            SP.SOD.executeFunc('sp.js', 'SP.ClientContext', retrieveListItems);
            ExecuteOrDelayUntilScriptLoaded(CallOut, "callout.js");
            var aHtml="";
            var rowID;        
            var siteUrl = "https://gkms.sharepoint.com/sites/Khaitan/";
            var restUrl="";
           
            function retrieveListItems() {
             // This piece of code retrieves list items from the list called "Resources"
                // you can change the name of the list in the variable 'listName'
                // Also, the fields revieved are 'ows_Title' and 'ows_Cost', you can change those too
                $().SPServices({
                    operation: "GetListItems",
                    async: false,
                    listName: "KhaitanDocLib",
                    CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><FieldRef Name='EncodedAbsUrl'/></ViewFields>",
                    completefunc: function (xData, Status) {
                        //alert(xData.responseText);
                        $(xData.responseXML).SPFilterNode("z:row").each(function () {
                            var aHtml = "<a href=" + $(this).attr("ows_EncodedAbsUrl") + ">" + $(this).attr("ows_Title") + "</a>";
                            var tdHtml = "<tr class='gradeX' id='" + $(this).attr("ows_ID") + "'> <td class='DocLinkID'>" + aHtml + "</td>";
                            tdHtml += "<td class='two'>" + $(this).attr("ows_PracticeArea") + "</td>";
                            $(".tablebodyresources").append(tdHtml);
                        });
                    }
                });

                // the table is constructed dynamically where results are going to be placed
                var nCloneTh = document.createElement('th');
                var nCloneTd = document.createElement('td');
                nCloneTd.innerHTML = '<img class="editRowIMG" src="https://gkms.sharepoint.com/sites/Khaitan/Style Library/details_open.png" height="25" width="25"  alt="EDIT"><img class="delItemImg" src="https://gkms.sharepoint.com/sites/Khaitan/Style Library/Delete.png" height="25" width="25" alt="Delete">';
                nCloneTh.innerHTML = 'Actions';
                nCloneTd.className = "center";
                // this is an 'Add' image  inserted in front of each row
                $('#resourcepool thead tr').each(function () {
                    //this.insertBefore( nCloneTh, .childNodes[0]);
                    $(this).append(nCloneTh);
                });

                $('#resourcepool tbody tr.gradeX').append(nCloneTd);
                var resourceTable = $('#resourcepool').dataTable();
                //this is an event handler to handle users clicking on the 'Add' image in front of each row
               
                $('#resourcepool').on( 'click', 'tbody tr .DocLinkID', function () {
                    rowID=this.parentElement.id;
//alert(rowID);
restUrl = "https://gkms.sharepoint.com/sites/Khaitan/_api/web/lists/getbytitle('KhaitanDocLib')/items("+rowID+")";
$.ajax({
                    url: restUrl,
                    method: "GET",                  
                    headers: { "Accept": "application/json; odata=verbose" },
                    success: function (data) {
                    var metaDataCols ="";
                    $("#metadatav").html(metaDataCols);
                      alert("success");
                        $("#frame").attr("src", data.d.ServerRedirectedEmbedUrl);
                        metaDataCols="<table><tr><td>Practice Area:</td><td>"+data.d.PracticeArea+"</td><td>Sub Practice Area:</td><td>"+data.d.SubPracticeArea+"</td></tr>";
                        metaDataCols +="<tr><td>Comments</td><td>"+data.d.Comments+"</td></tr><table>";
                        $("#metadatav").append(metaDataCols);
                        $("#openDocID").attr("href", data.d.ServerRedirectedEmbedUrl);
                        GetDocNameLinkURL();
                                       
                    },
                    error: function (data) {
                        alert("error");
                    }  
                });//onclick of row            

});
               
            }//retrieve item method
         
function GetDocNameLinkURL(){
restUrl="https://gkms.sharepoint.com/sites/Khaitan/_api/web/lists/getbytitle('KhaitanDocLib')/items("+rowID+")/File";
   $.ajax({
    url: restUrl,
                    method: "GET",                  
                    headers: { "Accept": "application/json; odata=verbose" },
       success: function(results){
//alert(results);
var docURL = results.d.LinkingUrl.split('?');
     $("#downloadDocID").attr("href",docURL[0]);
     var arr = results.d.Name.split('.');
     $("#DocNameID").text(arr[0]);

       }
   });
}
    function myFunction(){
     alert("Document downloaded");
      }// download completes
     
        });//DOCUMENT.READY      
       
   


     </script>

    <style type="text/css">
   
        .edit-row-modal {
            display: none;
        }
       
     
    </style>

</head>
<body id="dt_example">
    <table cellpadding="0" cellspacing="0" border="0" class="display" id="resourcepool">
        <thead>
            <tr>
                <th>Name Of Document</th>
                <th>Practice Area</th>
            </tr>
        </thead>
        <tbody class="tablebodyresources"></tbody>
    </table>

  <div id="mydiv" width="100%" height="100%">
  <h1 id="DocNameID"></h1>
  <iframe Id="frame" height="440px"></iframe>
  <div id="metadatav"></div>  
<a id="openDocID"><input type="button" value="Open" ></a>
<a id="downloadDocID" onclick="myFunction()"><input type="button" value="Download" ></a>
</div>

</body>
</html>

Tuesday, January 3, 2017

Check Current user is an Admin or not

SPUser.IsSiteAdmin Property

SP.User.isSiteAdmin property (sp.js)


if(currUser.get_isSiteAdmin)
{
console.log("Current user is site Admin");
}
else{
console.log("Current user is not site Admin");
}

Tuesday, December 27, 2016

JQGRID from SharePoint 2013 online List Data using RestApi

First include reference of the following JavaScript Libraries download it from this site.

1. jquery.jqGrid.src.js
2. grid.locale-en.js
3. jquery-ui-1.8.21.custom.min.js
4. ui.jqgrid.css




SCRIPT

var dataTableExample = 'undefined';
 var requestUri = "https://servername/_vti_bin/ListData.svc/DownloadTrackingList";

$(document).ready(function () {
      loadDataTable();
});
function loadDataTable() {
console.log("loadDataTable");
$('#gridID').jqGrid({
datatype: 'json',
//Change url here it just dummy.
           url: "https://servername//_vti_bin/ListData.svc/DownloadTrackingList",
           type:"GET",
             dataType:"json",
               contentType: 'application/json;odata=verbose',
                ajaxGridOptions: { contentType: "application/json; charset=utf-8" },
                 colNames:['Id','DocID','Title','DocName','DocURL','UserName','DownloadDate','Modified'], //define column names
colModel:[
{name:'Id',index:'Id',key: true,  width:55, editable:true, editoptions:{readonly:true}, sorttype:'int'},
{name:'DocID', index:'DocID', width:150,sortable:true,editable:true},
{name:'Title', index:'Title',  width:150,sortable:true,editable:true},
{name:'DocName', index:'DocName',  width:150,sortable:true,editable:true},
{name:'DocURL', index:'DocURL',  width:200,sortable:true,editable:true},
{name:'UserName', index:'UserName', width:150,sortable:true,editable:true},
{name:'DownloadDate', index:'DownloadDate', width:100,sortable:false,editable:true},
{name:'Modified', index:'Modified', width:100, sorttype:'date', editable:true, editrules:{date:true},formatter:'date', datefmt:'d/m/Y'}

],            
jsonReader : {
              root: "d.results",
              cell: "",
            repeatitems: false
     },
      rowNum:10,
    rowTotal: 50,
  rowList:[10,20,30],
  pager: '#pager',
    sortname: 'id',
    loadonce: true,
    viewrecords: true,
  sortorder: "desc",
    editurl: 'https://servername/_vti_bin/ListData.svc/DownloadTrackingList', // 
    caption:"CRUD on SharePoint server Data"
     });

 $("#gridID").jqGrid('navGrid','#pager',{});
 $("#gridID").jqGrid('filterToolbar',{stringResult: true,searchOnEnter : false});

 
}



HTML

<head>
<script type="text/javascript" src="https://gkms.sharepoint.com/sites/Khaitan/SiteAssets/jquery-3.1.1.js"></script>
<!-- Add your CSS styles to the following file -->

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqgrid/4.6.0/css/ui.jqgrid.css" />


    <!-- Add your JavaScript to the following file -->


<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" />

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/eggplant/jquery-ui.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-ui-bootstrap/0.5pre/css/custom-theme/jquery-ui-1.10.0.custom.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqgrid/4.6.0/css/ui.jqgrid.css" />
 
    <!-- Add your JavaScript to the following file -->
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jqgrid/4.6.0/js/jquery.jqGrid.src.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jqgrid/4.6.0/js/i18n/grid.locale-en.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
 

<!--
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jqgrid/4.6.0/plugins/ui.multiselect.js"></script>
<link rel="Stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jqgrid/4.6.0/plugins/ui.multiselect.css" />
    Add your JavaScript to the following file -->
    <script type="text/javascript" src="https://servername/sites/sitename/Shared%20Documents/JQGridExample.js"></script>
 
 
<style>
.form-control {
border-radius: 0;
}
</style>
</head>

<body>
 <div>
<div id='tblMain' style="float:left">
<table id="gridID"></table>
<div id="pager"></div></div>
</div>
</body>

</html>



References
Here most important thing to be take care is jsonReader here 
https://stackoverflow.com/questions/23127039/unable-to-load-sharepoint-list-item-rest-api-response-in-jqgrid


http://www.json.org/js.html



http://sharepointrestapi.blogspot.in/



Tuesday, September 27, 2016

wsdl to cs generator using visual studio

wsdl to cs generator using visual studio


Step 1: Generate or Obtain the Web Service WSDLs for Your Organization


To generate the metadata and enterprise WSDL files for your organization:
  1. Log in to your Salesforce account. You must log in as an administrator or as a user who has the “Modify All Data” permission.
  2. From Setup, enter API in the Quick Find box, then select API.
  3. Click Generate Metadata WSDL and save the XML WSDL file to your file system.
  4. Click Generate Enterprise WSDL and save the XML WSDL file to your file system.

c:\Program Files\Microsoft WSE\v3.0\Tools\WseWsdl3.exe


VISUAL STUDIO COMMAND PROMTS
C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\Shortcuts


To have the WSDL to Proxy Class tool generate a proxy class that derives from the WebServicesClientProtocol class, the .NET Framework SDK 2.0 WSDL.exe tool must be installed and accessible. When the SDK Command Prompt is used to run the WSDL to Proxy Class tool, the WSDL.exe tool is accessible.
Visual Studio Tools

Developer prompt command and run below command

WseWsdl3 {URL | path} [Options]

ArgumentDescription
URL
The URL to a WSDL file (.wsdl).
path
The path to a local WSDL file (.wsdl).

WseWsdl3 http://hostServer/WebServiceRoot/WebServiceName.asmx?WSDL /out:MyProxyClass.cs

How to Deploy Your HTML Website on a Linux Server (Apache + SFTP)

Launching a simple HTML website on your own Linux server is easier than you might think. Whether you're sharing a static landing page or...