Wednesday, January 13, 2016

Display Pages Version Information in SharePoint 2013


In SharePoint 2013, I had a requirement to display page versions in drop down and on selection of each version respective version information should open in new window.
This requirement consists of two parts.
  1.          Display drop down  on each page
  2.          Add versions in drop down and on selection of each drop down open version information.

For achieving 1st part, I created page layout and added html Drop down code on page layout source, so every page created using that page layout will have drop down on this page.

Code:

 
               










For 2nd part – I added below script in page layout. This code extracts version number and sets it as text for drop down option and value as URL for opening version information.
In SharePoint under layouts directory we can get all versions information on Versions.aspx.
I am calling this page using JQuery Ajax API to read page content. Once we get all html source which will have all versions information, I am extracting required values using JQuery.
So on drop down change you have to open URL in value field in new window. That’s it.
This code requires {LIST ID} as Pages library ID and Item ID is Page ID.  



var VersonNumberArray = new Array;
$(document).ready(function() {
 getItemVersions(function(versionEntries){
  for ( i = 0; i < versionEntries.length; i++ )
  {
    var opt = document.createElement("option");      
     opt.text = VersonNumberArray[i];
   
    var urlVal = versionEntries[i].href
       
        if (urlVal.indexOf("?") > -1)
        {
          urlVal = urlVal.split('=')[1];
          urlVal = "/Pages/Forms/DispForm.aspx?ID={ItemID}&VersionNo=" + urlVal;
        }
        else
        {
         urlVal = "/Pages/Forms/DispForm.aspx?ID={ItemID}&VersionNo="
        }
       
        opt.value = urlVal;
        document.getElementById('versionid').options.add(opt);
  }


});

 
  });


function getItemVersions(success)
{
var itemid =  document.getElementById('pageid').value;
var versionsUrl = 'http://{SiteURL}/_layouts/15/versions.aspx?list={ListID}&ID='+ itemid;
   $.get( versionsUrl, function( data ) {
 
      var versionEntries = parseVersionList(data);
      success(versionEntries);
   });
 
   }


function parseVersionList(data){
 
   var versionList = $(data).find('table.ms-settingsframe');
   var verurlList =  $(versionList).find('a[onfocus="OnLink(this)"]');
   var versonRows = $(versionList).find('> tbody > tr');
 
   var children = null;
 
   for(var i=0; i < versonRows.length ; i++)
   {
    var td = $(versonRows[i]).children('td:first');
   
     if(td.length == 1)
     {
       if(td[0].vAlign == "top" && td[0].className == "ms-vb2")
        {
          VersonNumberArray.push(td[0].outerText);
        }
     }
    }
    return verurlList;
}

Happy SharePointing
 

Sunday, November 29, 2015

Change Display Name of current user using REST API in SharePoint 2013

In one SharePoint 2013 portal, we had a requirement to change display name of current logged in User, which appears in Welcome Menu.
We had below script in master page, which successfully changed display name as First Name & Last Name.

_ spPageContextInfo.userId   will give user id in User Info List.
After that we can construct REST URL to access User Info List and retrieve User Details (First Name, Last Name, Department, Email etc.) using REST API.
.ms-core-menu-root CSS class gives User Display Name object and by using Jquery syntax below we can set name as per our requirement.

var userid = _spPageContextInfo.userId;
   var reqUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/Web/SiteUserInfoList/Items("+ userid +")?$select=FirstName,LastName";
   var displayName ;
   
   
   $.ajax({
                url: reqUrl,
                type: "GET",
                headers: {
                    "accept": "application/json;odata=verbose",
               },
        success: function (data) { 

         $(".ms-core-menu-root")[1].innerText= data.d.FirstName + " " +  data.d.LastName;

                 },
        error: function (error) {
              alert("error in REST API call");
        }

       });

Sunday, July 27, 2014

Retrieve List item Attachments using REST API


In previous blog, I explained about adding attachments to list item using html5 and Jquery. Now let’s use some REST API to pull these attachments and display them in list.
I am using same page from previous post to display or edit list item. And MY page URL is as below

{Site URL}/SitePages/File.aspx?RID={ID}
Now on document ready event I have used below code which retrieves item as well as attachment and display in my custom form:

 getListItem function uses item ID from query string and passes CAML query to retrieve particular item

In Succeed delegate method we are iterating collection and assigning respective Tittle ,
Description values to textboxes. For retrieving attachments I am using REST API, using ListData WCF service. URL for all attachments collection can be built like below

{Site URL}/_vti_bin/ListData.svc/{List Name} ([item ID])/Attachments 
       
This returns all attachments JSON result collection object , now  get file  Name of each file by iterating through it. And we can build URL for file path as below

{Site URL}/Lists/{List Name} /Attachments/{Item ID}/{FileName}
 


















When your page will load , output will be as shown in below. Click on each attachment will open respective file.
 
 





That's it. 
 

Saturday, July 26, 2014

Add Attachment to List using Jquery and Html5

In this week, I have spent lot of time with finding ways to upload attachment with list item in SharePoint 2010. Everyone knows we can achieve this very easily using Server side code. However as my blog title suggests my requirement was to accomplish this task without any server side code.
So here are steps to do this using html5 and Jquery SPService library:
1.      Create a list “Test” in your SP2010 Team site.
2.      Create a Column’s like Title, Description (Single line of text) etc.
3.       Add a tag for Html 5 in your site master page. (v4.master).
 


4.      Add Meta tag in same master page .This tag tells IE browsers to display your webpage in IE 10 mode.
5.      Create a (.aspx) page using SPD in Site Pages library.
6.      Create a html for your custom form and file upload control page will look like as below :
 
Source Code for html:
 
 
 
 Input type “File” is html5 control, it has attribute for setting multiple files selection.Also I have used output control for displaying list of files.
7.      Add a reference to Jquery library and SPServices Jquery library JavaScript files.
8.      Below is source code for event capture for displaying uploaded files  in my web page 
 
 
 
 
 
 
This code adds event receiver for file upload control and displays selected file names in output list.
 
 
9.      On Submit button click I am using Client object model (COM) for saving item in List.
After that I have used FileReader for reading uploaded files .Using SPService method I am pushing files as attachment to list item just created.
 
 
FileReader is basically asynchronous object, therefore we can use on load event .Also I have used readAsDataURL method, which is best API to read file which gives URL at the end of reading file.

 
That’s it your list item with multiple or single attachments will be saved successfully.


Saturday, July 5, 2014

SharePoint Apps Vs. SharePoint Solutions

In MOSS 2007 we used to develop as “WSP” solution packages. These WSP files are deployed on farm which contains custom managed code, declarative scripts etc. Farm administrator used to deploy solutions.      
In SP2010 one more concept was introduced called “Sandbox Solutions” which are uploaded in site collection gallery and installed on site collection by site owner also.
Now in SP2013 we have new development model “SharePoint Apps”, everything in SharePoint 2013 is app.


MOSS 2007
SP2010
SP2013
Farm Solution (.wsp)
Yes
Yes
Yes
Sandbox solution(.wsp)
No
Yes
Yes
SharePoint Apps
(.app)
No
No
Yes

We can use wsp in SharePoint 2013 whenever we want to use develop below components: 

  •    Site definitions
  •    Delegate controls
  •    Custom themes
  •    Custom action groups

SharePoint app model is flexible and can be deployed office store for apps, on premise farms and SharePoint online. Below are few points for why to of SharePoint app model 
·        Apps are nothing but Safe SharePoint extensions to Administrators.
·        Apps are easy to search on online store and simple installation process which can be done by SharePoint end users. (Site owners, members)
·        Apps provide maximum flexibility in developing new versions.
·        It gives option to use your other programming skills like html5, JQuery/JavaScript.
·        Apps help in integrating cloud-based resources (windows azure) in smoother and more flexible ways.
·        You can use SharePoint cross-domain JavaScript library/OAuth to read SharePoint data.
·        Apps enable your extension to have permissions that are distinct from the permissions of the user who is running the app.
·        Apps help in use of cross-platform standards, including REST API, OData and OAuth.

Using SharePoint Apps You can develop below components

  •          Custom Web Parts
  •          Event and Feature Receivers
  •          Custom Field Types
  •         Application Pages


Saturday, June 28, 2014

SharePoint Data View web part Linked Data Source

SharePoint designer is very powerful tool for SharePoint branding as well as accomplishing tasks with minimal efforts. I always liked the Data view web part I have created number of DW web parts wherever required.
In this post I will explain Linked Data Source Data view and some challenges while filtering this view.
I had 10 lists with similar structure and I was looking for merging these in single data source and display filtered data for current login user. So let’s start with implementation.

1.      Create Linked Data Source : -
·        Open your SP site in SharePoint Designer. Data Sources option will be available in left section in Site Objects.
·        Click on Data Sources. Linked Data Source, Database connection etc. option will be displayed in ribbon.
·        Click on Linked Data Source -> In General Tab give name for your Data source. In Source tab click Configure Linked Source; wizard will open to select lists you want to be in your data source. Select lists and click next to select Merge/Join to finish Linked Data Source Creation.

2.      Create Data View web part:-
·         Create a new page and empty Data view web part on page. (Insert -> Data View -> Empty Data View)
·        Click on Select Data Source, all data sources will be shown to you .Our data source will be shown in category “Linked Sources”. Select source in step 1.
·        Select fields you want to display from right section and display them as multiple item view.
·        This is it; your data view web part is ready with linked Data Source.

3.      Filtering Data View :-
                Now I was trying to filter above Data view with Current login user .I was comparing this with AssignedTo  user field in above Data Sources. My Filter criteria was below
AsignedTo equals [Current User]

It works with list Data view web part, however somehow it was not working here. After some analysis I found filter section in XSLT of this web part as below:







I checked fields added, and modified above code to below and my current user filter Worked …!


select="/dsQueryResponse/Rows/Row[normalize-space(@AssignedTo.title) = $UserID]"

4.      Change Created Date
Use below function to modify Date formatting in Data View :   
ddwrt:FormatDateTime(string(@Created), 1033, ‘MM/dd/yyyy’)"
          

Thursday, June 19, 2014

Internet Explorer Dev Tool - unable to open


Internet explorer has awesome tool for debugging  client side scripting as well as many things -

Page styling / font - color changes etc.

Recently I faced problem with IE 8 - I was unable to open  Dev. Tool  by pressing F12

or Clicking  from IE settings menu ..

There could me multiple solution either dev. tools might be minimized in unable to see or Hidden

The solution for me was - updating flag in Registry - Default Developer Tool was disabled.

Here is path is Registry

HKEY_LOCAL_MACHINE  => SOFTWARE => POLICIES =>MICROSOFT =>

INERNET EXPLORER => IEDevTools

Set value for Type REG_DWORD to 0

Your Dev. Tool will be Back ...!

Happy Debugging ..

Monday, June 16, 2014

Display SharePoint data in chart


I had a requirement to display Tasks Status from SharePoint in a pie chart. We can do this in several ways; in this post will explain about using REST API and Google charts to display your data.

Everyone is familiar with Tasks list and very commonly used in SharePoint .Status field in this list has below options and would like to display my chart based on this status.

·         Not Started

·         In Progress

·         Completed

·         Deferred

·         Waiting on someone else

SharePoint 2010 had WCF data service that gives REST interface. Using this we can query on SharePoint data.

URL: -  <Site URL >/_vti_bin/ListData.svc

Steps:

1.       Get count of each status by using below query  on Task list

<Site URL>/_vti_bin/ListData.svc/Task/$count?$expand=Status&$filter=Status/Value eq 'Not Started'


2.       Build array of all status with count as shown in code html.

3.       Use google API to create Pie chart

4.       Upload this html and add as a CEWP.
 
 
Source Code :





Output :









 
 
 
 
 

 

Sunday, June 8, 2014

Working with Person or Group and DateTime using Jquery/client object model – Part 2

Please read part one before reading this  - Working with Person or Group and DateTime using Jquery/ COM – Part 1.

In this post I will explain about update operation for task added using custom form in previous post.
I am using same form and same function for update operation .I will build url for update operation as below:

/MyCustomPage.aspx?RID=[Task ID value]
I have added code retrieve data and set on respective controls in document.Ready event as below



We have to delay code execution in document.Ready until SP.Js is loaded else client context will be null.
For setting People picker value we need extract User/Group display using code and pass that to SPFindPeoplePicker as in code.
valueToSet – user display name
checkNames – setting true will trigger event for check name image and will validate name.
All values will be set in same my custom form.

Now update value in any field and submit data swill call same method for insert with small modification

As below:

 
 
 
 
 
 



List data will update. That’s it.
 
 

 
 
 
 
 
 
 
 
 
 
 


Saturday, June 7, 2014

Working with Person or Group and DateTime using Jquery/client object model – Part 1


Client object model for SharePoint introduced in SharePoint 2010 and it has been helping developers to accomplish many tasks without writing server side code and deployment of same etc.  And that too with minimum efforts.

I like this new way of writing code at client side and am exploring JavaScript client object model and use of jquery.

I have observed that many developers face issues while working with Person or Group and Date Time fields. So I will explain code for working with these fields using JavaScript client object model and jquery, for list operations like insert/update.

 I want to insert/update data in list using custom form.

I created custom list name - MyTasks with following field:

·        Title – Single line of text

·        Description – Multiple line of text

·         AssignedTo – People or Group (User or Group)

·         DueDate - Date Time fields.

For custom form I created – Simple aspx page by opening site in designer and applied master page for consistent look and feel.

 Now I create custom form as below .

 
Code for above form


I have to add element around People picker field for using SPFindPeoplePicker function in

SPServices-0.7.2.js

Add reference for Jquery and SPServices Jquery library on  page.

After this Add below code for Insert operation:
 
 
 
 
 
In above code I have used SPFindPeoplePicker function in SPServices JS for getting people picker value this function is doing super awesome job for me .

 Function checks for element with display name we passed and gets complete object of people picker in that particular row.

One more thing this people picker accepts User as well as Group value – I have written code considering user will be added to this fields every time.

For group we need to modify code as below:

ppAssignedTo.dictionaryEntries[0].SPGroupID + ";#" + ppAssignedTo.currentValue;

.currentValue – gives display name

ppAssignedTo – object  retruns almost all thing you required for user or group field.
 

Click on Submit button it should save your data in List.