Archive for April, 2015

Introduction

In this article, we will learn how to get current user group collection through REST API in JQuery.



Initially we have to obtain the current user of SharePoint group they belong to, which can be achieved using SharePoint 2013 REST API.

Let’s proceed

When we use /_api/web/CurrentUser and /_api/web/GetUserById(“+UserID+”)/Groups , we get the current user’s group collection . Right now I am using a work around that iterates through the (big) result set. To get the group for the current Login User follow below steps:

Step 1

Navigate to your SharePoint 2013 site.

Step 2

From this page select the Site Actions | Edit Page.

Edit the page, go to the “Insert” tab in the Ribbon and click the “Web Part” option. In the “Web Parts” dialogue, go to the “Media and Content” category, select the “Script Editor” Web Part and click the “Add button”.

Step 3

Once the Web Part is inserted into the page, you will see an “EDIT SNIPPET” link; click it. You can insert the HTML and/or JavaScript as in the following.

  1. <script src=http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.1.min.js&#8221;></script>
  2. <script type=“text/javascript”>
  3.     $(document).ready(function () { getCurrentUser(); });
  4.     function getCurrentUser() {
  5.         getUserWebPermissionREST();
  6.         $.ajax({
  7.             url: _spPageContextInfo.webAbsoluteUrl + “/_api/web/CurrentUser”,
  8.             method: “GET”,
  9.             headers: { “Accept”“application/json; odata=verbose” },
  10.             success: function (data) {
  11.                 getCurrentUserGroupColl(data.d.Id);
  12.             },
  13.             error: function (data) {
  14.                 failure(data);
  15.             }
  16.         });
  17.     }
  18.     function getCurrentUserGroupColl(UserID) {
  19.         $.ajax
  20.         ({
  21.             url: _spPageContextInfo.webAbsoluteUrl + “/_api/web/GetUserById(“   + UserID + “)/Groups”,
  22.             method: “GET”,
  23.             headers: { “Accept”“application/json; odata=verbose” },
  24.             success: function (data) {
  25.                 /* get all group’s title of current user. */
  26.                 var results = data.d.results; var InnrHtmlgrp = “<ul>”;
  27.                 for (var i = 0; i < results.length; i++) {
  28.                     InnrHtmlgrp += “<li>” + results[i].Title + “</li>”;
  29.                 }
  30.                 $(“#Group”).append(InnrHtmlgrp + “</ul>”);
  31.             }
  32.         });
  33.     }
  34. </script>
  35.   <strong>security Group Name:</strong>
  36.       <div id=“Group”></div>

Final Output Result:

Introduction

User profile properties provide information about SharePoint users, such as display name, email, account name and other business and personal information including custom properties.

Imagine

Imagine I want to retrieve a custom field from the user profile property with REST. The property is searchable in a search box. The name of the custom properties are “Employee ID” and “Division”.

But when I try to use http://siteurl/_api/SP.UserProfiles.PeopleManager/GetMyProperties, it does not retrieve the custom properties, on the contrary I can see only the built-in properties like:

  • AccountName
  • DisplayName

I get a node that says UserProfileProperties. Where is a key? So how do I use this?

Let’s proceed

I’ve created a UserProfile with some custom properties.

When I use http://siteurl/_api/SP.UserProfiles.PeopleManager/GetMyProperties, I get a result set with all UserProfile properties, including my custom properties. Right now I am using a workaround that iterates through the (big) result set with all properties to get my custom property.

Step 1: Navigate to your SharePoint 2013 site.

Step 2: From this page select the Site Actions | Edit Page.

Edit the page, go to the “Insert” tab in the Ribbon and click the “Web Part” option. In the “Web Parts”dialogue, go to the “Media and Content” category, select the “Script Editor” Web Part and click the “Add button”.

Step 3: Once the Web Part is inserted into the page, you will see an “EDIT SNIPPET” link; click it. You can insert the HTML and/or JavaScript as in the following:

  1. <script src=http://ajax.aspnetcdn.com/ajax/jQuery/jquery:1.10.1.min.js&#8221;></script>
  2.     <script type=‘text/javascript’>
  3.         var workEmail = “”;
  4.         var EmployeeID = “”;
  5.         var Division = “”;
  6.         var userDisplayName = “”;
  7.         var AccountName = “”;
  8.         $.ajax({
  9.             url: _spPageContextInfo.webAbsoluteUrl + “/_api/SP.UserProfiles.PeopleManager/GetMyProperties”,
  10.             headers: { Accept: “application/json;odata=verbose” },
  11.             success: function (data) {
  12.                 try {
  13.                     //Get properties from user profile Json response
  14.                     userDisplayName = data.d.DisplayName;
  15.                     AccountName = data.d.AccountName;
  16.                     var properties = data.d.UserProfileProperties.results;
  17.                     for (var i = 0; i < properties.length; i++) {
  18.                         if (property.Key == “WorkEmail”) {
  19.                             workEmail = property.Value;
  20.                         }
  21.                         if (property.Key == “EmployeeID”) {
  22.                             EmployeeID = property.Value;
  23.                         }
  24.                         if (property.Key == “Division”) {
  25.                             Division = property.Value;
  26.                         }
  27.                     }
  28.                     $(‘#AccountName’).text(AccountName);
  29.                     $(‘#userDisplayName’).text(userDisplayName);
  30.                     $(‘#EmployeeID’).text(EmployeeID);
  31.                     $(‘#workEmail’).text(workEmail);
  32.                     $(‘#Division’).text(Division);
  33.                 } catch (err2) {
  34.                     //alert(JSON.stringify(err2));
  35.                 }
  36.             },
  37.             error: function (jQxhr, errorCode, errorThrown) {
  38.                 alert(errorThrown);
  39.             }
  40.         });
  41.     </script>
  42.     <h2><strong>Employee Details</strong></h2>
  43.     <br />
  44.     AccountName   <span id=“AccountName”></span>
  45.     DisplayName   <span id=“userDisplayName”></span>
  46.     EmployeeID    <span id=“EmployeeID”></span>
  47.     Email Address <span id=“workEmail”></span>
  48.     Division      <span id=“Division”></span>


User Properties

The following is the list of User Properties (use the GetPropertiesFor function for these):

AccountName
DirectReports
DisplayName
Email
ExtendedManagers
ExtendedReports
IsFollowed
LatestPost
Peers
PersonalUrl
PictureUrl
Title
UserProfileProperties
UserUrl

User Profile Properties

The following is the list of User Profile Properties:

AboutMe

SPS: LastKeywordAdded
AccountName

SPS: Locale
ADGuid

SPS: Location
Assistant

SPS: MasterAccountName
CellPhone

SPS: MemberOf
Department

SPS: MUILanguages
EduExternalSyncState

SPS: MySiteUpgrade
EduOAuthTokenProviders

SPS: O15FirstRunExperience
EduPersonalSiteState

SPS: ObjectExists
EduUserRole

SPS: OWAUrl
Fax

SPS: PastProjects
FirstName

SPS: Peers
HomePhone

SPS: PersonalSiteCapabilities
LastName

SPS: PersonalSiteInstantiationState
Manager

SPS: PhoneticDisplayName
Office

SPS: PhoneticFirstName
PersonalSpace

SPS: PhoneticLastName
PictureURL

SPS: PrivacyActivity
PreferredName

SPS: PrivacyPeople
PublicSiteRedirect

SPS: ProxyAddresses
QuickLinks

SPS: RegionalSettings:FollowWeb
SID

SPS: RegionalSettings:Initialized
SISUserId

SPS: ResourceAccountName

SPS: AdjustHijriDays

SPS: ResourceSID
SPS: AltCalendarType

SPS: Responsibility

SPS: Birthday

SPS: SavedAccountName
SPS: CalendarType
SPS: SavedSID
SPS: ClaimID
SPS: School
SPS: ClaimProviderID
SPS: ShowWeeks
SPS: ClaimProviderType
SPS:SipAddress
SPS:ContentLanguages
SPS:Skills
SPS:DataSource
SPS:SourceObjectDN
SPS:Department
SPS:StatusNotes
SPS:DisplayOrder
SPS:Time24
SPS:DistinguishedName
SPS:TimeZone
SPS:DontSuggestList
SPS: UserPrincipalName
SPS:Dotted:line
SPS:WorkDayEndHour
SPS:EmailOptin
SPS:WorkDayStartHour
SPS:FeedIdentifier
SPS:WorkDays
SPS:FirstDayOfWeek

Title

SPS:FirstWeekOfYear
UserName

SPS:HashTags
UserProfile_GUID

SPS:HireDate
WebSite

SPS:Interests
WorkEmail

SPS:JobTitle
WorkPhone

SPS:LastColleagueAdded

Introduction

SharePoint 2013 has greatly expanded the REST services available to developers.  With this, we have much more SharePoint functionality exposed via CSOM and Web Services. Also, all of the new REST Services in SharePoint 2013. SharePoint 2013 was able to provide me with  a REST API, I could call with jQuery ajax requests, and this was exactly what I wanted.

REST Services – High Level Overview

Let’s start out with our basic get commands in REST. Below is a list of the basic commands used to get List Items from a SharePoint List through the SharePoint 2013 REST Services.

COMMAND URL
 Get All Lists http://server/site/_api/lists
 Get All List Items From a Single List http://server/site/_api/lists/getbytitle(‘listname’)/items
 Get a Single List Item http://server/site/_api/lists/getbytitle(‘listname’)/items
 Get Back Certain Columns http://server/site/_api/lists/getbytitle(‘listname’)/items?$select=Title,Id
 Order Your Results  http://server/site/_api/lists/getbytitle(‘listname’)/items? $orderby=Title asc

 

Imagine

In my example, I’m accessing a Custom list(countries) and output the result binding it to dynamical dropdown . I have order by column in Ascending only. Using  SharePoint’s REST API lets us add these filters in our request. The results are given to us as a JSON object, which we can then loop through and insert into a dropdown runtime. I also used a modular pattern to structure my code. We can generate our REST request. _spPageContextInfo is a SharePoint object that gives us useful information about the page and site we’re on, including the base URL of our site.

After successfully getting our list information, we just need to loop through our data, put it in a dropdown, and then insert into our predefined container element. jQuery helps make this an easy process.

pic15

Let’s proceed

Step 1: Navigate to your SharePoint 2013 site.

Step 2: From this page select the Site Actions | Edit Page.

Edit the page, go to the “Insert” tab in the Ribbon and click the “Web Part” option. In the “Web Parts” picker area, go to the “Media and Content” category, select the “Script Editor” Web Part and press the “Add button”.

Step 3: Once the Web Part is inserted into the page, you will see an “EDIT SNIPPET” link; click it. You can insert the HTML and/or JavaScript as in the following

<script src=”http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.1.min.js”></script&gt;

<script>

 

$(document).ready(function () {

countriesDrpDownBind();

});

function countriesDrpDownBind() {

var listName = “countries”;

var url = _spPageContextInfo.webAbsoluteUrl;

 

getListItems(listName, url, function (data) {

var items = data.d.results;

 

var inputElement = ‘<select id=”drpcountries”> <option  value=””>Select</option>’;

// Add all the new items

for (var i = 0; i < items.length; i++) {

var itemId = items[i].Title,

itemVal = items[i].Title;

inputElement += ‘<option value=”‘ + itemId + ‘”selected>’ + itemId + ‘</option>’;

 

}

inputElement += ‘</select>’;

$(‘#divisiondrp’).append(inputElement);

 

$(“#drpcountries”).each(function () {

$(‘option’, this).each(function () {

 

if ($(this).text() == ‘Select’) {

$(this).attr(‘selected’, ‘selected’)

};

});

});

// assign the change event to provide an alert of the selected option value

$(‘#drpcountries’).on(‘change’, function () {

alert($(this).val());

});

 

}, function (data) {

alert(“Ooops, an error occured. Please try again”);

});

}

// READ operation

// listName: The name of the list you want to get items from

// siteurl: The url of the site that the list is in.

// success: The function to execute if the call is sucesfull

// failure: The function to execute if the call fails

function getListItems(listName, siteurl, success, failure) {

$.ajax({

url: siteurl + “/_api/web/lists/getbytitle(‘” + listName + “‘)/items?$orderby=Title asc”,

method: “GET”,

headers: { “Accept”: “application/json; odata=verbose” },

success: function (data) {

success(data);

},

error: function (data) {

failure(data);

}

});

}

 

</script>

Division

<div id=”divisiondrp”></div>

Finally the result looks as below:

pic16

Introduction and Issue

When you select page the URL Parameters for Site Pages, in that page you write REST API jquery and after adding in script editor if you save page API does not work after saving because of

Minimal Download Strategy   Site Features Active 

After adding in script editor Before saving Page

pic11

Proposed Solution

 

pic12

To validate if everything was working correctly, deactivate the MDS Feature and access to a SharePoint Page.

Feature go to site Settings -> Manage Site Features – > Find Minimal Download Strategy Feature – > Click on Deactivate.

pic13
After access the SharePoint page you will be able to see the URL change, it’s not calling “_layouts/15/start.aspx#/” but the correct Page “/sitesPages//POCForDropDown.aspx” and the Ribbon Load correctly.

pic14

Introduction

 

In SharePoint SharePoint List Column Person or Group Allow multiple selections after we add multiple user in that column after config list with dataview webpart this column show like Ex. 2; #abc;3;#pqr remove special character using javascript

  1. Ex. 2; #abc;3;#pqr
  2. Ans: abc;pqr
  3. <script type=“text/javascript”>
  4.      function CleanNames(textclean) {
  5.           return text2clean.replace(/[;#0-9]+/g, “; “);
  6.      }
  7. </script>
  8. Then call it from your XSL
  9. <xsl:if test=“string-length(@Employess) != 0”>
  10.      <script type=“text/javascript”>document.write(CleanNames(“<xsl:value-of select=“@Employess” />“));</script>
  11. </xsl:if>
In Sharepoint 2010 Dataview Webpart Create Trim Function for Multiline Texbox in xslt expresion.
for example:
SharePoint multi line text box column
O/p: SharePoint multi line text…….
  1. <xsl:value-of select=“concat(substring(@Description,1,180),’…’)/”>
  2. </xsl:value-of>

Introduction 

This code describe how to create web part custom properties in SharePoint 2010.

 

1.TextBox

  1. [Browsable(true),Category (“Miscellaneous”),DefaultValue (“ListName”),
  2. WebPartStorage(Storage.Personal),
  3. Friendly Name(“ListName”),Description(“Text Property”)]
  4. Public string ListName
  5. {
  6.      get
  7.      {
  8.           Return  strList;
  9.      }
  10.      Set
  11.      {
  12.           strList=Value;
  13.      }
  14. }

2. CheckBox

  1. [Browsable(true),Category (“Miscellaneous”),DefaultValue (false),
  2. WebPartStorage(Storage.Personal),
  3. Friendly Name(“NeedCheckBox”),Description(“Checkbox Property”)]
  4. Public bool NeedCheckBox
  5. {
  6.       get
  7.       {
  8.             Return  boolCheckBox;
  9.       }
  10.       Set
  11.       {
  12.             boolCheckBox =Value;
  13.       }
  14. }

3. RadioButton

  1. [Browsable(true),Category (“Miscellaneous”),DefaultValue (true),
  2. WebPartStorage(Storage.Personal),
  3. Friendly Name(“NeedRadioButton”),Description(“RadioButton Property”)]
  4. Public bool NeedRadioButton
  5. {
  6.       get
  7.       {
  8.             Return  boolRadioButton;
  9.       }
  10.       Set
  11.       {
  12.             boolRadioButton;=Value;
  13.       }
  14. }