Friday, 25 December 2015

Pass QueryString Value From SharePoint Page To Provider Hosted App In SharePoint 2013

Instruction 
In the new SharePoint App model, web parts are replaced with app parts. The problem is they don't have an equivalent to Web Part Connections. So how can you pass parameters from one part to another? 

To answer this you have to consider several things:
  • App parts are basically small applications that are presented in your SharePoint site through iframes.
  • Each app is running in a separate domain and so are their app parts. Because of this any direct manipulation through some javascript code is out of the question because it would mean cross-domain scripting and all you would get is an "access denied" message.
This post explains about how to create an user defined custom property for a Client Web Part in SharePoint 2013 Provider Hosted App and its relationship with the query string and the standard tokens. The option for getting the data from Client Web Part's custom property is bit different from Farm based or Sandboxed Web Parts. In Provider Hosted App, the value of the property has to be accessed via query string.

Steps:
  1. Add Client web part to app part.
  2. Open element.xml and add one Property right click on Client web part, then Custom properties.


  3. Go to host web where you are having query string.
  4. Add App part.
  5. Add one script editor web part. It should be below to App.

    Code
  6. Now in the App landing page load read the Query string value in .Cs file.
    1. protected void Page_Load(object sender, EventArgs e)  
    2. {  
    3.    string _ID = Request.QueryString["ID"];  
    4. }  

How to Check User Permission in SharePoint 2013 Using REST API

Introduction
In this article I explore how to check whether the login user has full permission or not using the SharePoint 2013 REST API.
I wanted to avoid using JSOM and do everything with REST. Fortunately, I understand that you must rely on JSOM for certain things. In this case JSOM has the SP.BasePermissions type with methods for combining sets of permissions. This type is defined in SP.js. JSOM also exposes the types of permissions as a basic integer enumeration as SP.PermissionKind. This enumeration is defined in SP.Runtime.js. I still could not figure out how to get the high and low values for the permission. I knew what the values were supposed to be for the EditLisitItems permission. Looking at the permission in debug view I noticed the values were exposed by the typical nonsensical property names $4_1 and $5_1. Whenever you set the permission with a permission kind the JSOM function will bit-shift the values and re-calculate the high and low values.
Normally we need to perform tasks such as:
  • Does the current user have admin permission on the site
  • and so on
SharePoint provides a method called doesUserHavePermissions to do that. First of all we need to understand how SharePoint defines user roles by assigning permission levels such as Full Control, Contributor, design and so on.
For example, a site admin is assigned by Full Control that is a composite of a few permission items we call the permission kind.
Example:
Assume that we want to check whether the current user is an admin of the site. For that we need to check that the user has the manageWeb permission kind. (Actually we need to check whether other permission kinds are assigned full control as well but if the user has manage web permission then it is more likely the user can perform admin tasks. In my other example I will show how to check the full permission kinds).

  1. function getUserWebPermissionREST() {  
  2.   
  3.     //Permission for admin to show or hide the entries on memory board using ShowOnHomePage Field  
  4.     var perm = new SP.BasePermissions();  
  5.     perm.set(SP.PermissionKind.manageWeb);  
  6.     $.ajax({  
  7.         url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/doesuserhavepermissions(@v)?@v={'High':'" + perm.$4_1.toString() + "', 'Low':'" + perm.$5_1.toString() + "'}",  
  8.         type: "GET",  
  9.         headers: { "accept""application/json;odata=verbose" },  
  10.         success: function (data) {  
  11.             var d = data.d.DoesUserHavePermissions;  
  12.   
  13.             if (d === true) {  
  14.                 //Show Check Box if Full Control  
  15.             }  
  16.             else {  
  17.                 //hide Check Box  
  18.             }  
  19.   
  20.         },  
  21.   error: function (err) {  
  22.             alert(JSON.stringify(err));  
  23.         }  
  24.   
  25.     });  
  26.   
  27. }  

Get Current Login User Profile Properties Through REST API

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"></script>  
  2.   
  3.     <script type='text/javascript'>  
  4.   
  5.           
  6.         var workEmail = "";  
  7.         var EmployeeID = "";  
  8.         var Division = "";  
  9.         var userDisplayName = "";  
  10.         var AccountName = "";  
  11.   
  12.         $.ajax({  
  13.   
  14.             url: _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties",  
  15.             headers: { Accept: "application/json;odata=verbose" },  
  16.             success: function (data) {  
  17.                 try {  
  18.                     //Get properties from user profile Json response  
  19.                     userDisplayName = data.d.DisplayName;  
  20.                     AccountName = data.d.AccountName;  
  21.                     var properties = data.d.UserProfileProperties.results;  
  22.                     for (var i = 0; i < properties.length; i++) {  

  23.                         var property = properties[i];

  24.                         if (property.Key == "WorkEmail") {  
  25.                             workEmail = property.Value;  
  26.                         }  
  27.                          
  28.                         if (property.Key == "EmployeeID") {  
  29.                             EmployeeID = property.Value;  
  30.                         }  
  31.                         if (property.Key == "Division") {  
  32.                             Division = property.Value;  
  33.                         }  
  34.   
  35.                     }  
  36.                     $('#AccountName').text(AccountName);  
  37.                     $('#userDisplayName').text(userDisplayName);  
  38.                     $('#EmployeeID').text(EmployeeID);  
  39.                     $('#workEmail').text(workEmail);  
  40.                     $('#Division').text(Division);  
  41.                     
  42.   
  43.                 } catch (err2) {  
  44.                     //alert(JSON.stringify(err2));  
  45.                 }  
  46.             },  
  47.             error: function (jQxhr, errorCode, errorThrown) {  
  48.                 alert(errorThrown);  
  49.             }  
  50.         });  
  51.   
  52.     </script>  
  53.      
  54.     <h2><strong>Employee Details</strong></h2>  
  55.     <br />  
  56.     AccountName   <span id="AccountName"></span>  
  57.     DisplayName   <span id="userDisplayName"></span>  
  58.     EmployeeID    <span id="EmployeeID"></span>  
  59.     Email Address <span id="workEmail"></span>  
  60.     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

How to Solve Rest API Not Working Issue After Saving Page in SharePoint

Introduction and Issue
When you select a page the URL Parameters for Site Pages, in that page you write REST API jQuery and after adding in the script editor if you save the page the API does not work after saving because of the Minimal Download Strategy Site Features is active.

After adding in script editor Before saving Page 


Proposed Solution 

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

To access the feature go to Site Settings then Manage Site Features then find the Minimal Download Strategy Feature then click on Deactivate.



After accessing 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 loads correctly.

Dynamically Adding Dropdown Using REST API and jQuery

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 are 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. The following is a list of the basic commands used to get List Items from a SharePoint List using the SharePoint 2013 REST Services.



Imagine
In my example, I'm accessing a Custom list (of countries) and output the result binding it to a dynamic dropdown. I have sorted by a column in ascending only. Using SharePoint's REST API lets us add these filters to our request. The results are given to us as a JSON object that 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 inserted into our predefined container element. jQuery helps make this an easy process.



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:
  1. <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.1.min.js"></script>  
  2. <script>  
  3.   
  4.     $(document).ready(function () {  
  5.         countriesDrpDownBind();  
  6.       });  
  7.     function countriesDrpDownBind() {  
  8.         var listName = "countries";  
  9.         var url = _spPageContextInfo.webAbsoluteUrl;  
  10.   
  11.         getListItems(listName, url, function (data) {  
  12.             var items = data.d.results;  
  13.              
  14.             var inputElement = '<select id="drpcountries"> <option  value="">Select</option>';  
  15.                // Add all the new items  
  16.             for (var i = 0; i < items.length; i++) {  
  17.                  var itemId = items[i].Title,  
  18.                    itemVal = items[i].Title;  
  19.                  inputElement += '<option value="' + itemId + '"selected>' + itemId + '</option>';  
  20.                 
  21.                }  
  22.                 inputElement += '</select>';  
  23.                 $('#divisiondrp').append(inputElement);  
  24.   
  25.               $("#drpcountries").each(function () {  
  26.                 $('option'this).each(function () {  
  27.   
  28.                     if ($(this).text() == 'Select') {  
  29.                         $(this).attr('selected''selected')  
  30.                     };  
  31.                 });  
  32.             });  
  33.                // assign the change event to provide an alert of the selected option value  
  34.               $('#drpcountries').on('change'function () {  
  35.               alert($(this).val());  
  36.                   });  
  37.              
  38.           }, function (data) {  
  39.             alert("Ooops, an error occured. Please try again");  
  40.         });  
  41.     }  
  42.     // READ operation  
  43.     // listName: The name of the list you want to get items from  
  44.     // siteurl: The url of the site that the list is in.  
  45.     // success: The function to execute if the call is sucesfull  
  46.     // failure: The function to execute if the call fails  
  47.     function getListItems(listName, siteurl, success, failure) {  
  48.         $.ajax({  
  49.             url: siteurl + "/_api/web/lists/getbytitle('" + listName + "')/items?$orderby=Title asc",  
  50.             method: "GET",  
  51.             headers: { "Accept""application/json; odata=verbose" },  
  52.             success: function (data) {  
  53.                 success(data);  
  54.             },  
  55.             error: function (data) {  
  56.                 failure(data);  
  57.             }  
  58.         });  
  59.     }  
  60.   
  61. </script>  
  62. Division  
  63. <div id="divisiondrp"></div>  
Finally the result looks as in the following:

SharePoint 2013 - Uploading Multiple Attachments To The New Item On List Using JSOM And REST API

  Introduction In this article, we will explore how we can attach multiple attachments to the new item on list using JSOM and REST API. Ther...