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:

Advertisements

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. }

Using power shell run this below script.

  1. $FolderPath = “c:\Solutions”
  2. foreach ($solution in Get-SPSolution)
  3. {
  4.    $id = $Solution.SolutionID
  5.    $title = $Solution.Name
  6.    $filename = $Solution.SolutionFile.Name
  7.    $solution.SolutionFile.SaveAs(“$FolderPath\$filename”)
  8. }

cmd

Introduction 

In this article we will explore to how to create a custom tab in SharePoint 2013 Custom Action Ribbon.

I wanted to create a Custom Action Tab in my SharePoint Hosted app. Consider that SharePoint 2013 already provides a home that may be suitable for your customization, for list pages at least; the Custom Commands tab. It only appears on list pages and contains just one lonely button under normal circumstances. This tab is actually the post-upgrade home for any SharePoint 2007 CustomActions you had, assuming you don’t introduce changes during your upgrade process, any CustomActions that didn’t target the ECB will end up here. In any case, it could help avoid tab proliferation so don’t forget it when building your customizations.

Solutions

  1. Add a ribbon custom action for the App project that you have created. Right click on the project [Add] [New Item] [Ribbon Custom Action] and enter the Name and click on the Add button. It will start the wizard for creating a custom action for the Ribbon control.

    custom action for Ribbon

  2. In this wizard select the host web where you want to expose the custom action. In other words your custom action will be available in that host web.

    The custom action scoped can be a List template or a List instance or None. In this example I am selecting List template and the item is the custom action scoped to be “Custom list”.

    custom list

  3. Selected “Ribbon.ListItem.Actions”. What this does is, it will show the custom action under the Items section of the List Ribbon control.

    ribbon list item

  4. The following is the Custom Ribbon XML that I created for the Custom Tab. Refer to the Ribbon XML Schema for more options: Server Ribbon schema.
    1. <?xml version=“1.0” encoding=“utf-8”?>
    2. <Elements xmlns=http://schemas.microsoft.com/sharepoint/&#8221;>
    3.   <CustomAction Id=“Team Collaborate”
    4.                 RegistrationType=“List”
    5.                 RegistrationId=“100”
    6.                 Location=“CommandUI.Ribbon”
    7.                 Sequence=“10001”
    8.                 Title=“Team Collaborate”
    9.               >
    10.     <CommandUIExtension>
    11.       <CommandUIDefinitions>
    12.         <CommandUIDefinition Location=“Ribbon.Tabs._children”>
    13.           <Tab Id=“Team Collaborate.Tab”
    14.                 Title=“Team Collaborate”
    15.                 Description=“Special Risk Tracking Functionality”
    16.                 Sequence=“550”>
    17.             <Scaling Id=“Team Collaborate.Tab.Scaling”>
    18.               <MaxSize Id=“Team Collaborate.Tab.EnterpriseRiskGroup.MaxSize”
    19.                         GroupId=“Team Collaborate.Tab.EnterpriseRiskGroup”
    20.                         Size=“OneLarge”/>
    21.               <Scale Id=“Team Collaborate.Tab.EnterpriseRiskGroup.Scaling.CustomTabScaling”
    22.                       GroupId=“Team Collaborate.Tab.EnterpriseRiskGroup”
    23.                       Size=“OneLarge” />
    24.             </Scaling>
    25.             <Groups Id=“Team Collaborate.Tab.Groups”>
    26.               <Group Id=“Team Collaborate.Tab.EnterpriseRiskGroup”
    27.                       Description=“Functions that can be performed on Enterprise Risks”
    28.                       Title=“Sharepoint Consulting”
    29.                       Sequence=“10”
    30.                       Template=“Ribbon.Templates.OneLargeExample”>
    31.                 <Controls Id=“Team Collaborate.Tab.EnterpriseRiskGroup.Controls”>
    32.                   <Button Id=“Team Collaborate.Tab.EnterpriseRiskGroup.Notify”
    33.                           Command=“Team Collaborate.EnterpriseRisk”
    34.                           Sequence=“10”
    35.                           Image16by16=“_layouts/15/TeamCollaborate.png”
    36.                           Image32by32=“_layouts/15/TeamCollaborate.png”
    37.                           Description=“Selected Largest Team of Certified SharePoint developers.”
    38.                           LabelText=“Expert Sharepoint”
    39.                           TemplateAlias=“cust1”/>
    40.                 </Controls>
    41.               </Group>
    42.             </Groups>
    43.           </Tab>
    44.         </CommandUIDefinition>
    45.         <CommandUIDefinition Location=“Ribbon.Templates._children”>
    46.           <GroupTemplate Id=“Ribbon.Templates.OneLargeExample”>
    47.             <Layout Title=“OneLarge” LayoutTitle=“OneLarge”>
    48.               <Section Alignment=“Top” Type=“OneRow”>
    49.                 <Row>
    50.                   <ControlRef DisplayMode=“Large” TemplateAlias=“cust1” />
    51.                 </Row>
    52.               </Section>
    53.             </Layout>
    54.           </GroupTemplate>
    55.         </CommandUIDefinition>
    56.       </CommandUIDefinitions>
    57.       <CommandUIHandlers>
    58.         <CommandUIHandler Command=“Team Collaborate.EnterpriseRisk”
    59.                         CommandAction=“~remoteAppUrl/Pages/TeamCollaborate.aspx?{StandardTokens}&Source={Source}&ListURLDir={ListUrlDir}&list={ListId}&SelectedItems={SelectedItemId}” />
    60.       </CommandUIHandlers>
    61.     </CommandUIExtension>
    62.   </CustomAction>
    63. </Elements>
  5. Build and publish App and add into the apps in the Testing Library and deploy; Trust it.

    Testing Library

    app in testing

    Testing Library and deploy

    The following shows the final output Custom Ribbon Tab:

    Custom Ribbon

Summary

The ribbon is a key building block for SharePoint 2013 solutions and if you see a ribbon tab for a Custom List on the Ribbon Control Bar then it can be customized.

Introduction

This article explains the Custom Ribbon Action to set the Custom Image to a Ribbon button and that is absolutely awesome! I was creating a Custom Action in my SharePoint Hosted app. I wanted to add a Button into the Ribbon of any Custom List to my App Web and do some work based on List Information. I started by adding a Custom Ribbon Action.

Custom Ribbon button

create Custom action for Ribbon

ribbon listItem

You can see the following code snippet of elements.xml of the Custom Ribbon Action that will be generated for you based on your settings selected in the wizard.

selected in the wizard

Have a look at the highlighted code in the previous block. You will notice that the icon of the button is a placeholder you have the ability to change. The next screenshot shows the button with the placeholder icon:

placeholder icon

Solution:

A better workaround is to use Data URIs that is a way of embedding the actual image data in the src attribute of the img tag. The only limitation is browser support for example.

The code after applying this workaround will be like this:

applying this workaround

The following is the final output of the Customize Icon to Ribbon button.

Ribbon button

Note: There are many image data URI generators online like this one.