​​​

Blog

Apr 29
SharePoint 2013: Access User Profile Service Data using JSOM

In this article, we will learn to manage or access User Profile Service(UPS) Application using JSOM (Javascript Object Model) and create a basic App. Before we start, lets go through basic UPS terminology first.

User Profile – It has all the information of people in an organization in an organized manner. It displays all properties like AccountName, FirstName, LastName, WorkEmail etc. related to a user.

User Profile Service Application – It is considered as centralized location to store all user profiles and also allows the administrators to configure or manage profiles, profile synchronization, My Site, Social Tags etc. It can also pull information from Directory Services like Active Directory.

My Site – A personalized site for individual user to manage their information and store documents, links etc. It provides rich networking and social features by enabling users to share information about themselves or their activities. My Site is accessible by clicking on User Name on top right corner of SharePoint page.

Manage and Access User Profile Data

Since we are going to work using JSOM, we can perform only 'Read ' operations with an exception that Profile picture can be changed using JSOM (or CSOM or REST)

*Server Side Code allows Read/Write both operations.

Retrieve User Profile Properties using JSOM

Lets create a SharePoint Hosted App and retrieve user information in that app –

  1. Launch Visual Studio 2013 and select "App for SharePoint 2013" from New Project.
  2. After selecting above project type, you are presented with a window to connect to SharePoint site and select type of app to be deployed (see below screenshot)

Here I have provided mu SharePoint Online developer site URL and selected SharePoint Hosted App. Click Finish.

1.png

3.)    After the project is created, you will see a set of folders/filers added in Solution Explorer added by default to the project.

2.png

4.)    If you open "Default.aspx" page, you will find some JavaScript libraries already added to page.

3.png
Here we need to add one more library to start working with User Profiles

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

5.) Now open App.js file , there you will find some code already added to display current user name-

4.png

Here we will add below code to extract User Profile Properties for a User and code will look like this.

5.png

In this code I have provided my id to retrieve few details.

Hit F5 to execute the code and it will deployed to SharePoint site provided initially. But you see it will give message "Error: Access Denied. You do not have permission to perform this action or access this resource."

Reason: You have to set App access permissions for User Profile Service. In solution open AppManifest.XML file and set the permissions using dropdowns as per below screenshot.

6.png

Few things to remember :-         

1.)    Format of username to be passed will vary based on environment, like-

For SharePoint Online or on premise forms authentication, it will be –

i:0#.f|membership|user@domain.com

For SharePoint 2013 On Premise windows authentication, it will be –

i:0#.w|domain\user

For SharePoint 2013 On Premise SAML based authentication, it will be –

?i:05:t|adfs with roles|user@domain.com

2.) Set App Access permission in Appmanifest file​

Hope it helps.

Apr 23
Popularity Trends and Most Popular Items reports in SharePoint 2013

​Recently in my project, there was a requirement where site admin wants to view the usage report for list/library items like how many times item viewed/downloaded, unique visits for that item etc. Thanks to Enhanced Search Capabilities and Analytics Processing Component in SharePoint 2013, that we have readymade solution for this. So as we start, we can generate two type of report based on usage-

1.) Popularity Trends

2.) Most Popular Items

Popularity Trends

This is an excel report that shows daily and monthly usage statistics report for item hits/users. We can get this report at different levels - Site Collection, Site and Library/List Item, but here we will see this report only for List/Library Item.

How to view Popularity Trend Report for List/Library Item?

Well, to start with, lets go to the library/list for which report is required. Now follow below steps to generate report-

1.) In the list/library, select the item for which report is required,

2.) From the ribbon, select Item/File tab (corresponding to List/Library) and there you will see there is a Popularity Trend button under "Share & Track" section.

popularitytrendItem.PNG

3.) Click on this button, a excel file is generated and you can open/save this file to view report.

4.) Excel file will have "Views" tab an certain tables/charts for that item.


Here you can see, i generated a report for an item which contains daily and monthly data. Now this daily data is for lat 14 days and monthly data covers last three years.

So this is how we can generate Popularity Trend Report for an Item/File in List/Library.

Most Popular Items

This report shows most popular items per usage type for all items in list/library. We can get this report at different levels - Site Collection, Site and Library/List Item, but here we will see this report only for List/Library Item.

How to view Most Popular Items Report for List/Library Items?

Well, to start with, lets go to the library/list for which report is required. Now follow below steps to generate report-

1.) In the list/library, select all items/files,

2.) From the ribbon, select List/Library tab (corresponding to List/Library) and there you will see there is a Most Popular Items button under "Share & Track" section.

MPIL.PNG 

3.) Click on this button, a report is generated as shown in below screenshot.

MPIR.PNG

4.) By default, the report lists items in the list/library​ that has most views for the Recent time period.

5.) Based on dropdown selection, we can check "Most Views By Unique Users" and "Most Recommendation Clicks" report also.

6.) Also, as you can see from report, that for each item you have "Popularity Trends" link. By clicking on this link excel report can be downloaded/viewed which has popluraity trend data for that item.

For more details, you can also check this technet article-

https://technet.microsoft.com/en-in/library/jj715890.aspx​ 

​​​​Hope it Helps.

Apr 22
SharePoint PowerShell script to update people field with claims token in List

​While migrating existing applications from MOSS 2007 to SharePoint 2013, we came across this issue where user ids were updated to include claims token, but people field in lists were still having ids only with domain name.

So we have a custom list "Project Tasks" where we have a people field "Owner". User IDs in this field have format like "domain-name\user-id" before migration and after migration. So we have to update values for this field to include claims token along with domain name. To achieve this, i wrote below power shell script -

$web = Get-SPWeb <Provide URL of Site>
$list = $web.Lists["<Provide List Name>"]

foreach($item in $list.Items)
{
    $user = $list.GetItemById($item["ID"])["<Provide People Column Name>"]
    
    if($user)
    {
        if($user.Contains(";#"))
        {     
# Check if user is already having claims token then no update
            if($user.Contains("i:0"))
            {
                Write-host "User already updated" -ForegroundColor green
            }
            else
            {
                $user = $user.split("#")[1]
                $user = $user.split("\")[1]                
               
   #Here abc is the domain name
$u = "i:0#.w|abc\" + $user
$spUserId = Get-SPUser -Web $web -Identity $u | ForEach-Object { $_.Id }

$spUser = [string]$spuserId + ";#" + $u
$item["<Provide People Column Name>"] = $spUserId

$item.Update()
Write-host $item["<Provide People Column Name>"] -ForegroundColor blue
            }
        }
    }
}

Before running above script, there is a list setting change that needs to be done which is as mentioned below-

1.) Navigate to List Settings.
2.) Click on Column Name (which is to be updated) under Columns section.
3.) Under "Additional Column Settings" change value of "Show Field" from Name to Account. Click Ok.​ (If not Account already)
4.) Now execute the script.
5.) After executing script, check if claims token is added to user Ids or not.
6.) Revert back settings done in Step 3.

Hope this Helps.
Apr 16
SharePoint List Type Column to show icon based on file type attached

​I came across this sceraio where in SharePoint list i have to show file attachment type. By default when Type column is enabled it shows general icon for all types of attachment irrespective of file type. Using below minimal javascript code, we can achieve the same file type icon functionality that we have in SharePoint library.

Default View:-

FileTypeIcon1.PNG

1.) Create a Choice Column say 'DocumentType' in list with following values:-

pdf
pptx
ppt
docx
doc
xlsx
xls
zip


2.) Update this column value for list items based on type of attachment.

3.) Now add a Content Editor WebPart on page and add below code in that-

Code:

<script type="text/javascript" src="{reference to jquery library}">​
</script>
<script type="text/javascript">
    $(document).ready(function(){ 
$('.ms-listviewtable > tbody > tr').each(function () {
var docTypeIcon = getDocTypeImage($(this).find("td:nth-child(<column count*>)").text());
//alert(docTypeIcon);
$(this).find("td:nth-child(<column count*>)").find("img").attr("src",docTypeIcon);
}); 
function getDocTypeImage(x)
{
var imageUrl = '';
switch(x)
{
case 'pdf' : imageUrl = "/_layouts/images/pdficon_small.gif"; break;
case 'pptx' : imageUrl = "/_layouts/images/icpptx.png"; break;
case 'ppt' : imageUrl = "/_layouts/images/icppt.png"; break;
case 'docx' : imageUrl = "/_layouts/images/icdocx.png"; break;
case 'doc' : imageUrl = "/_layouts/images/icdoc.png"; break;
case 'xlsx' : imageUrl = "/_layouts/images/icxlsx.png"; break;
case 'xls' : imageUrl = "/_layouts/images/icxls.png"; break;
case 'zip' : imageUrl = "/_layouts/images/iczip.gif"; break;
default: imageUrl = "/_layouts/images/icgen.gif"; break;
}
return imageUrl;
}

    });
    </script>

* - Column Count Starts from 1 including default selectAll checkbox column

After Adding Script:-

FileTypeIcon2.PNG

And Voila, now you can see file type icon base don attachment type.

Hope this will help.


Mar 11
Change text in sharepoint search box

​SharePoint adds a search box by default to all site pages created OOB. This text reads as 'Search...' or 'Search This Site' but sometimes we want to customize this text, say, we want it to be 'Search My Site'. This can be done easily in few steps using jQuery as mentioned below:-

1.) Navigate to page where you want to change the text.

2.) Click on gear icon from top right corner and select 'Edit Page'.

3.) Click on 'Add a Web part' and select 'Content Editor Webpart' under 'Media and Content' category.

AddWebpart.PNG

4.) Click on 'Click here to add new content' and select 'Insert' tab from ribbon and click on 'Embed Code' to add javascript code (see below screenshot)

AddContent.PNG

5.) Copy below code to change text.

   <script src="<chnage to correct URL jquery-1.10.2.min.js>" type="text/javascript"></script><script type="text/javascript">
var val = $('.ms-helperText').val();
if (val === "Search..." || val === "Search this site") {
         $('.ms-helperText').val("Search My Site");
     } 

</script>

Hope this helps.
Dec 01
Use jQuery Datatables for SharePoint List Webpart with export to CSV, EXCEL, PDF and Print features

​In this post, i will describe how you can use jQuery Datatables to add more features to SharePoint list web part.

For this you need jQuery library (i prefer to use latest version of jQuery library), download here and jQuery Datatables library that you can download here. Also download jQuery Datatable TableTools extension from same download page. Once you have the required libraries, upload these to a SharePoint Document library, it will be easier to refer these libraries in SharePoint context.

Now add a content editor webpart on the page where you want to implement this, and paste below script in that web part. Make sure to update library/css refrences as per the location from your sharepoint site.

<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="jquery.dataTables.js"></script>
<link type="text/css" rel="stylesheet" href="jquery.dataTables.css">
<script type="text/javascript" src="dataTables.tableTools.js"></script>
<link type="text/css" rel="stylesheet" href="dataTables.tableTools.css">
<script type="text/javascript">
    $(document).ready(function(){ 
       $(".ms-listviewtable").prepend($("<thead></thead>").append($('.ms-listviewtable').find("tr:first"))).DataTable({         "sDom": 'T<"clear">lfrtip',
          
    "tableTools": {            
    "sSwfPath": "copy_csv_xls_pdf.swf"   // Change this path according to file location    
    }   
    });
</script>

Add below style also to that web part to maintain sharepoint css or else datatable css will be applied changing look n feel.
<style type="text/css">
.even, .odd, .sorting_1{
    background-color: transparent !important;
    }
 .dataTable THEAD TH{
    border:0 !important;
    }
</style>

Below is the screenshot of how it will look after performing above steps-


 Features-
1.) Use Copy button to copy list content to clipboard for further use.
2.) Use CSV or Excel or PDF button to export content in desired format.
3.) Use Print button to view the print preview of list content and then using browser print options, print content.
4.) Use Search textbox to filter content basd on keyboard- while typing filter the results.

Note:- To make table tools working flash should be enabled in browser and sharepoint should allow .swf files.
Nov 17
'L_delete_text' is undefined while adding attachments in custom list form

​I created a SharePoint designer custom list form and added form toolbar to enable attachments, but after adding attachment on click of Ok nothing happens.

When checked for any errors, I came across script error in browser which says "L_delete_text is undefined". After searching on google, thanks to this post here which says adding below script code on page resolves the issue.

<script>var L_Delete_Text = "";</script>

​So it worked well but what I observed is that after attachments are added to list item, default "Delete" link for every attachment that appears in default form does not appear anymore.

So overcome this issue, i did a slight modification in above script- 

<script>var L_Delete_Text = "Delete";</script>

​I provided text 'Delete' and voila i can see delete attachment links for every attachment added.

Thanks and Happy Coding...

Nov 17
SharePoint Form Toolbar Custom List Form

​​While working with SharePoint Designer Custom List forms, i came across this issue. Form toolbar to add attachments is visible in the design view but not displaying in page preview.

After struggling for a long time, i decided to use developer tool to see if control is available in source page and yes it was. Then using jquery i set the display mode for this control and it appeared.

Code used is as mentioned below:-

$('.ms-toolbar > span').css('display','block');

​Happy coding..

Aug 27
SharePoint Site URLs not working without appending default.aspx

Recently I faced an issue in SharePoint Server where users were unable to browse sites without appending “Default.aspx”, say I have a site http://servername/sites/abc. When users try to browse this, HTTP 404 error “The webpage cannot be found” is displayed, but this was working earlier. So users have to type in full URL http://servername/sites/abc/default.aspx. This was happening for all sites including Central Administration site.

While searching solution for this issue, many sites suggested to check if Handler Mappings in IIS for aspx is present or not (refer below screenshot). To check this follow below steps-

  1. Start IIS Manager.
  2. Expand Server Name -> Sites, to view all sites.
  3. Select any site and click on Handler Mappings under IIS in right pane.

img1.jpg 

Based on the SharePoint version, you may have different entries here but main thing to notice here is “IsapiModule” entry for “*.aspx” should be there.

Now this did not solve my problem, so I thought of enabling IIS Request Tracing to check exact error message. After I enabled request tracing, I checked the log file and found below error-

img2.jpg So from above screenshot it refers that above shown DLL is blocked due to some reasons (which was not the case earlier). There may be many other reasons also for this error but in my case I followed below steps to solve this-

  1. Start IIS.
  2. Select Server Name and click on “ISAPI & CGI Restrictions” under IIS from right pane.

img3.jpg 

        3. I copied DLL path from log file. Click on Add link to open a popup to add DLL path. Once you provide path and description, select “Allow extension path to execute” and click Ok. Blocked DLL is added as shown below.

img4.jpg 

Now I am able to browse site URLs without appending default.aspx.

Apr 30
SharePoint number column alignment issue in list

​This sounds weird but its true. If you have a list/list view webpart on your page and it has number columns then alignment of number columns will always be right. Even if you try to set the table/cell alignment property or edit xslt for alignment using SharePoint Designer it won’t work. So how to align the number column values ?

So while searching for the possible solutions, I came across a pretty simple and easy solution. Steps are as follows:

1.) Number Column is already present in your list.

2.) Create a calculated column based on the required number column and use the type as ‘Single line of text’.

3.) Now if you see the alignment is set to left side.

In my case, I required left alignment so it solved my problem. But this column’s alignment can be set using SharePoint designer if required.

Happy Learning.

1 - 10Next

 

 Awards