Error in SharePoint hosted app: Add permission level to the list programmatically

I am trying to add permission to the list which I have created in my app. I am trying to give current user some permission to add update delete items from my list. I have used one article from MSDN(http://msdn.microsoft.com/en-us/library/office/jj247079.aspx)
site. And my code is as bellow:
function execOperation() {
debugger;
context = new SP.ClientContext(appweburl);
var factory =
new SP.ProxyWebRequestExecutorFactory(
appweburl
context.set_webRequestExecutorFactory(factory);
appContextSite = new SP.AppContextSite(context, appweburl);
var appContextSite2 = new SP.AppContextSite(context, hostweburl);
var siteColl = appContextSite2.get_site();
hostweb = appContextSite2.get_web();
context.load(hostweb);
web = appContextSite.get_web();
context.load(web);
user = web.get_currentUser();
context.load(user);
que_list = web.get_lists().getByTitle("MyList1");
context.load(que_list);
que_list.breakRoleInheritance(true, true);
var permissions = new SP.BasePermissions();
permissions.set(SP.PermissionKind.viewListItems);
permissions.set(SP.PermissionKind.addListItems);
permissions.set(SP.PermissionKind.editListItems);
permissions.set(SP.PermissionKind.deleteListItems);
// Create a new role definition.
var roleDefinitionCreationInfo = new SP.RoleDefinitionCreationInformation();
roleDefinitionCreationInfo.set_name('Manage List Items');
roleDefinitionCreationInfo.set_description('Allows a user to manage list items');
roleDefinitionCreationInfo.set_basePermissions(permissions);
var roleDefinition = web.get_roleDefinitions().add(roleDefinitionCreationInfo);
web.breakRoleInheritance(true, false);
// Create a new RoleDefinitionBindingCollection.
var newBindings = SP.RoleDefinitionBindingCollection.newObject(context);
// Add the role to the collection.
newBindings.add(roleDefinition);
// Get the RoleAssignmentCollection for the target list.
var assignments = que_list.get_roleAssignments();
que_list.breakRoleInheritance(true, true);
// Add the user to the target list and assign the use to the new RoleDefinitionBindingCollection.
var roleAssignment = assignments.add(web.get_currentUser(), newBindings);
context.executeQueryAsync(onSuccess, onFail);
I have just copied the code from that article. But when I run my app it give me error :
You cannot customize permission levels in a web site with inherited permission levels
Any suggestions, What am I doing wrong?
Thank you in advance...!

Problem solved. 
It turns out there should be NO leading '/' in the relative URL despite the example shown in http://msdn.microsoft.com/en-us/library/office/dn292553.aspx#Folders with "/Shared Folder".
The correct GetFolderByServerRelativeUrl-parameter in my case is 'Lists/Productdocuments'.
Unsure whether example is wrong or if it applies to other cases than mine.

Similar Messages

  • Error with Provider Hosted App on Edit Form of a list item

    We have an error on the Edit Form of one of our pages.
    We have developed a SharePoint Online Provider Hosted app which replaces the standard edit form of a list item and has some further events behind the save button. Since this is rather new territory for us, we're using a roundabout way of achieving this by
    using a script editor web part to display an iFrame of our app. That way we can pass the Url through to our app and retrieve query strings from them.
    Our issue comes quite intermittently in that we sometimes get a "web page cannot be found" error or sometimes a "resource cannot be found" error, however, when we load another app on the site (from the same app project, but using an app
    part), then go back to the Edit Form, the information in the iFrame suddenly renders.
    Any ideas on what might be causing this issue at all? Ideally, we should be rendering the app to the Edit Form is the proper manner, rather than scripting an iFrame that points to out app in Azure. Would this be the cause of the problem?
    Thanks
    Tom

    Hi thumper, if you have access to InfoPath, you can add the form to a page using the InfoPath web part. Otherwise, use SP Designer with instructions below:
    http://sharepoint.stackexchange.com/questions/70287/display-new-form-of-a-list-in-a-web-part-page
    cameron rautmann

  • Can't add images to announcements in SharePoint-hosted app in Office 365

    I tried something very simple:
    Create a new SharePoint-hosted app
    Add a new list to the app, based on the Announcements template
    Deploy the app to my Dev site on Office 365
    When I now add a new item (aka a new announcement) and try to add an image to the Body field, I encounter two errors (depending on whether I try to add an image from my Computer or from SharePoint)
    Adding from my computer gives me an unexpected error:
    Adding from SharePoint shows me a structure of all the apps in my hostweb, but no way to upload an image either to the hostweb or the appweb:
    Is it not possible to add images to a Rich Text field in a list in an app?

    Hi Rene,
    For inserting any image from you computer to you App web, you need to create a separate picture library in your app web manually i.e. in your SharePoint hosted app add a new list item, under list settings window choose "create a list instance
    base on existing list template" and in the drop down select
    picture library. Now deploy the app and try again.
    Generally when we insert any image from our computer to a SharePoint rich text field, the image gets upload in one of the document libraries, but this option is not available in the newly created app web, as it doesn't contains any separate library..
    For you next error, make sure that in the app manifest you are providing
    read access on the web, this will resolve you second problem.
    Hope it helps you.....

  • How to open List when Page loads in SharePoint Hosted App?

    I  want to create an app same like InstantPracticeManager by InstantQuick.
    Now I want to know that in a SharePoint Hosted App How can I show the Whole List in a page. 
    Here I have added one image:
    Here there is one list and there are 4 views of that list.
    Now the App will be like when I load the page It will show like the image above. Now how can we show the list like this in sharepoint hosted app?
    I want the same scenario which is shown in the following blogs:
    http://sp2013.blogspot.in/2012/08/use-list-view-in-sharepoint-2013-apps.html
    and
    http://www.sharepointnutsandbolts.com/2013/08/working-with-web-parts-within.html
    where they add a list to an app
    Can any one suggest me the idea? I am bit confused.
    thanks in advance.

    Hi,
    According to your post, my understanding is that you want to show the different list view in a page in SharePoint Hosted App.
    We can use jQuery and cross-domain library to achieve it.
    The following articles for your reference:
    Adding a Tabbed View to A Web Part Page Using jQueryUI
    http://sympmarc.com/2011/11/09/adding-a-tabbed-view-to-a-web-part-page-using-jqueryui/
    How to: Access SharePoint 2013 data from apps using the cross-domain library
    http://msdn.microsoft.com/en-us/library/office/fp179927(v=office.15).aspx
    SharePoint 2013: Get list items by using the cross-domain library (JSOM)
    http://code.msdn.microsoft.com/office/SharePoint-2013-Get-items-d48150ae/view/SourceCode#content
    Thanks,
    Dennis Guo
    TechNet Community Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
    [email protected]
    Dennis Guo
    TechNet Community Support

  • Visual Studio 2013 problem during develop basic SharePoint-hosted app

    Hi,
    i am begginer in developing Sharepoint apps using Visual studio 2013.
    I followed this instructions http://msdn.microsoft.com/en-us/library/fp142379.aspx for creating a basic SharePoint-hosted app.  
    When i tried to build my application (Step 10 in create and deploy your first Sharepoint-hosted app) i got the following error: 
    Error occurred in deployment step 'Install app for SharePoint': Sideloading of apps is not enabled on this site.
    What is the problem?
    thanks, Aphrodite

    http://blogs.msdn.com/b/josrod/archive/2013/02/04/quot-sideloading-of-apps-is-not-enabled-on-this-site-quot.aspx
    In order to publish a SharePoint hosted app to a site collection the site must be based on the developer site template or have the “Developer” Feature enabled on it.  The “Developer” Feature is marked as hidden in its definition so you must use PowerShell
    to enable the Feature. 
    Enable-SPFeature e374875e-06b6-11e0-b0fa-57f5dfd72085 –url
    http://sp.contoso.com
    Also check below:
    http://blogs.msdn.com/b/officeapps/archive/2013/12/10/enable-app-sideloading-in-your-non-developer-site-collection.aspx
    If this helped you resolve your issue, please mark it Answered

  • SharePoint Hosted App - Creating cascaded drop down on hosted web lists

    Hi,
    I have created an SharePoint Hosted App(Javascript Object Model) that creates lists on the host web.
    I need to put some javascript into new and edit forms in order to create the cascaded drop down effect on 2 lookup fields.
    Can you please give me some advise?
    Regards,
    Marian

    Hope below article should help you
    http://blog.pentalogic.net/2010/11/editing-the-sharepoint-list-item-menu-part-2-using-javascript/
    http://www.getinthesky.com/2014/03/hide-text-field-sharepoint-form-using-jquery/
    http://social.msdn.microsoft.com/Forums/sharepoint/en-US/030471b2-d19a-470f-9a9e-0fd8a229138b/how-do-i-create-a-new-item-form-that-allows-to-save-and-continue-editing?forum=sharepointcustomizationlegacy

  • How to redirect to SharePoint hosted app when user lands on site collection

    is it possible to redirect user directly to SharePoint hosted app when he enters to the site collection? Currently
    user have to click on the app to navigate to SharePoint hosted app and I would like them to directly navigate to app without any clicks required.

    <script type="text/javascript" >
    SP.SOD.executeFunc('SP.JS', 'sp.ClientContext', function() {
    var ctx = new SP.ClientContext.get_current();
    var web = ctx.get_web();
    var appInstances = SP.AppCatalog.getAppInstances(ctx, web);
    ctx.load(appInstances);
    ctx.executeQueryAsync(
    function() {
    window.location =
    appInstances.getItemAtIndex(1).get_appWebFullUrl();
    function(sender, args) {
    console.log(JSON.stringify(args));
    </script>

  • OnPremise: Sharepoint Hosted App gives 401 unauthorized error while accessing UserProfile Rest Service

    Hi All,
    I have SharePoint hosted app deployed on On-Premise using(F5) which reads User Profile data consumes WCF(Hosted on same server) through REST API to insert data in to SQL DB(Different server).
    SharePoint hosted app was working as expected and suddenly it started asking for credential and not login(any user) to the application landing page.
    Checked SharePoint Logs, IIS Logs and Windows log but did not get any clue.
    WCF is accessible, User Profile access is also happening but not sure what changes done on server or infra level which causing this issue.
    I have an On-Premise Environment for SharePoint 2013. where we have created SharePoint hosted app which calls "http:///_api/SP.UserProfiles.PeopleManager/GetMyProperties" to get current user's data. but this gives me 401 unauthorized error.
    Notes:
    I had given read permission to user profile and full control to sitecollection in appmanifest. If I run this app on Office 365 developer site it works fine, but on premise environment it give 401 error.
    On premise environment when I deploy this app 3 times it prompt for  credential and finally gives the following error
    Error message after login 3 times:
    {"error":{"code":"-2147024891, System.UnauthorizedAccessException","message":{"lang":"en-US","value":"Access
    denied. You do not have permission to perform this action or access this resource."}}}
    -Lovekush Kumar 

    Add your site (http://*.app.contoso.com) to your local intranet sites in IE. 
    "app.contoso.com" is app domain.
    My Blog- http://www.sharepoint-journey.com|
    If a post answers your question, please click Mark As Answer on that post and Vote as Helpful

  • Getting error while uploading multiple files in sharepoint hosted app in 2013 with REST API

    Hi All,
    In one of my tasks, I was struck with one issue, that is "While uploading multiple files into custom list with REST API".
    Iam trying to upload multiple files in library with REST calls for an APP development, my issue is if i wants to upload 4 image at once its storing only
    3 image file and further giving "Conflict" error". Below is the attached screenshot of exact error.
    Error within screenshot are : status Code : 409
    status Text :conflict
    For this operation i am uploading different files as an attachment to an list item, below is the code used for uploading multiple files.
    my code is
    function PerformUpload(listName, fileName, listItem, fileData)
        var urlOfAttachment="";
       // var itemId = listItem.get_id();
        urlOfAttachment = appWebUrl + "/_api/web/lists/GetByTitle('" + listName + "')/items(" + listItem + ")/AttachmentFiles/add(FileName='" + fileName + "')"
        // use the request executor (cross domain library) to perform the upload
        var reqExecutor = new SP.RequestExecutor(appWebUrl);
        reqExecutor.executeAsync({
            url: urlOfAttachment,
            method: "POST",
            headers: {
                "Accept": "application/json; odata=verbose",
                "X-RequestDigest": digest              
            contentType: "application/json;odata=verbose",
            binaryStringRequestBody: true,
            body: fileData,
            success: function (x, y, z) {
                alert("Success!");
            error: function (x, y, z) {
                alert(z);

    Hi,
    THis is common issue if your file size exceeds 
     upload a document of size more than 1mb. worksss well for kb files.
    https://social.technet.microsoft.com/Forums/office/en-US/b888ac78-eb4e-4653-b69d-1917c84cc777/getting-error-while-uploading-multiple-files-in-sharepoint-hosted-app-in-2013-with-rest-api?forum=sharepointdevelopment
    or try the below method
    https://social.technet.microsoft.com/Forums/office/en-US/40b0cb04-1fbb-4639-96f3-a95fe3bdbd78/upload-files-using-rest-api-in-sharepoint-2013?forum=sharepointdevelopment
    Please remember to click 'Mark as Answer' on the answer if it helps you

  • Unable to add aspx file to document library using REST and JSOM in SharePoint Hosted App

    Hi,
    I am unable to add an aspx file to document library.  I was actually trying to create a WIKI page and upload to Pages library but that wasn't working so I tried simple document library.  It keeps failing with Access Denied error.  I have checked
    the blocked types and aspx is not included.  I can upload it directly from the browser so that shouldn't be the case.  I have read that it can be achieved with CSOM but I need this to work with a SharePoint Hosted App.  Here is my JSOM:
    factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
        context.set_webRequestExecutorFactory(factory);
        appContextSite = new SP.AppContextSite(context, hostweburl);
        oWeb = appContextSite.get_web();
        oList = oWeb.get_lists().getByTitle('Documents');
        fileCreateInfo = new SP.FileCreationInformation();
        fileCreateInfo.set_url("mywiki.aspx");
        fileCreateInfo.set_content(new SP.Base64EncodedByteArray());
        fileContent = "<%@ Page Inherits=\"Microsoft.SharePoint.Publishing.TemplateRedirectionPage,Microsoft.SharePoint.Publishing,Version=15.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c\" %> <%@ Reference VirtualPath=\"~TemplatePageUrl\"
    %> <%@ Reference VirtualPath=\"~masterurl/custom.master\" %>";
        for (var i = 0; i < fileContent.length; i++) {
            fileCreateInfo.get_content().append(fileContent.charCodeAt(i));
        newFile = oList.get_rootFolder().get_files().add(fileCreateInfo);
        context.load(newFile);
        context.executeQueryAsync(function () {
            alert('yo');
        }, function (sender, args) {
            alert(args.get_message() + '\n' + args.get_stackTrace());
    If I change the file extension to "txt", it works.  Same with REST implementation, it works with "txt" but fails with "aspx".  Maybe what I am trying to do will not work using JSOM or REST.  Any suggestions?  Your
    help is always appreciated.
    Regards,
    kashif

    Your code works fine in both my on-premises and SharePoint Online. I have given the app full control, so I suspect this is a permissions issue. I would check your permissions on your appmanifest. Must be something to do with publishing permissions. Try
    giving full control and work the permissions down.
    Blog | SharePoint Field Notes Dev Tools |
    SPFastDeploy | SPRemoteAPIExplorer

  • Sharepoint-Hosted App giving FORBIDDEN error when i use REST Api

    Hi,
    I have created a sharepoint hosted app which will create Team site on button click.
    I used REST Api  and  NAPA Tool to develop this app.
    Napa tool gives to things ClientWebpart.aspx and Default.aspx.
    When i run my Default.aspx code is working fine but ClientWebpart.aspx is giving FORBIDDEN error when i am trying to create site.
    Below is the code which i used to create site
    code:
    var hostweburl;
    var appweburl;
    $(document).ready(function () {
    hostweburl= decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
    function createSPWeb() {
    $.ajax(
    url: appweburl +
    "/_api/SP.AppContextSite(@target)/web/webinfos/add?@target='" +
    hostweburl + "'",
    type: "POST",
    data: JSON.stringify(
    'parameters':
    '__metadata': { 'type': 'SP.WebInfoCreationInformation' },
    'Url': 'RestSubWeb',
    'Title': 'RestSubWeb',
    'Description': 'REST created web',
    'Language': 1033,
    'WebTemplate': 'sts#0',
    'UseUniquePermissions': false
    headers: {
    "accept": "application/json;odata=verbose",
    "content-type": "application/json;odata=verbose",
    "X-RequestDigest": $("#__REQUESTDIGEST").val()
    success: successHandler,
    error: errorHandler
    NOTE:This is on sharepoint online.
    Please help
    Regards,
    sudeep

    So in the app you are testing, are you using the FQDN or the NetBIOS name? Bad practice but could you test with both (hard code the absolute URL for testing purposes) then retest your app?
    If you are making a web part based on the new app model this will be an "app part" and probably have the same issues you are experiencing. If this is for something internal rather than a product you are developing to resell then the script editor /
    content editor web part approach could work for you.
    Paul
    Paul Mather | Twitter |
    http://pwmather.wordpress.com | CPS

  • SharePoint hosted app error log

    Hi,
      I'd like to log the error in ULS log from sharepoint hosted app [Client side]. Is it possible, if yes, please let me know how to do it..
    Balaji -Please click mark as answer if my reply solves your problem.

    Hi,
    You could write informations to the "App Error Log".
    Have a look at these links :
    http://exxlence.com/2013/01/07/add-logging-to-your-sharepoint-app-using-logcustomapperror-method/
    http://sp2013.blogspot.fr/2013/01/sharepoint-apps-logging.html
    Regards
    Gilles Martinez
    Twitter
    Blog
    Please mark as helpful/answer if this resolved your post

  • Error when trying to retrieve Document Library in Sharepoint Hosted App using REST

    I have created the following REST request in order to retrieve the root folder of a Document Library added to a Sharepoint Hosted App
    getProductDocumentFolder: function () {
    $.ajax({
    url: _spPageContextInfo.webServerRelativeUrl +
    "/_api/web/GetFolderByServerRelativeUrl('/Lists/ProductDocuments')",
    type: "GET",
    headers: {
    "accept": "application/json;odata=verbose",
    success: function () {
    alert("Success!");
    //REST.Operator.readAll();
    error: function (err) {
    alert("Oops, error!");
    alert(JSON.stringify(err));
    The Document Library was added to the App from the Add > New Item menu in Visual Studio. I selected List and Selected Document Library from the Create a customizable list... dialog. The list is defined as shown in the picture below.
    I get the generic error "Value does not fall within the excepted range".
    I have tried both 
    "/_api/web/GetFolderByServerRelativeUrl('/Lists/ProductDocuments')"
    and
    "/_api/web/GetFolderByServerRelativeUrl('/ProductDocuments')"
    for the Document Library URL both I get the same error in both cases.
    What am I missing here?

    Problem solved. 
    It turns out there should be NO leading '/' in the relative URL despite the example shown in http://msdn.microsoft.com/en-us/library/office/dn292553.aspx#Folders with "/Shared Folder".
    The correct GetFolderByServerRelativeUrl-parameter in my case is 'Lists/Productdocuments'.
    Unsure whether example is wrong or if it applies to other cases than mine.

  • Create SharePoint hosted app when i debug project in IE browser getting error "Operation aborted" .

    Hi all,
    I am create SharePoint hosted app for SharePoint online. When i debugs project in IE browser getting error "Operation aborted".
     Please Suggest appropriate Way.
    Thanks
    Akash Anand 

    This happens sometimes if you are using third party library which IE does not support. Change the default browser of Visual Studio to Google Chrome and try.
    Let us know either it works or not
    Regards
    Khalil Kothia, PMP
    Blog

  • How to get inputted value in a RTE field on custom page and submit by REST call in 'Sharepoint hosted app'.

    Hi I am facing the three questions below.
    1. How to use default RTE in custom page in Sharepoint hosted app.
     I saw the article of Rich text Editor (ribbon based) in a webpart in SharePoint 2013 and tried it. But it did not work well. I guess it needs code-behind setting, however sharepoint hosted app does not support code-behind.
    Does anybody know how to do this?
    2. In above case, I placed the below code on custom page and tried to get the field's value when submit button was clicked.
    <SharePoint:InputFormTextBox ID="rftDefaultValue"
    RichText="true"
    RichTextMode="FullHtml" runat="server"
    TextMode="MultiLine" Rows="5">
    </SharePoint:InputFormTextBox>
    In debugger, the returned value was 'undefined'.
    var note = $('#hogehoge').val();
    Is it possible to get the RTE value? If yes, please let me know how to do this.
    3. I need to submit the RTE value using REST call.
    In this
    article in MSDN, the item creation sample treats single line text field. Does anybody know the sample for RTE?

    Hi,
    According to your description, you might want to use Rich Text Editor control in your SharePoint hosted app.
    First of all, I would suggest you post one question in one thread to make it easier to be discussed, which would also help you get a quick solution.
    Though we can add this control into a SharePoint hosted app, however, as we can’t add code behind for it, plus with the potential compatibility issues in different
    browsers, I would suggest you use other JavaScript Rich Text Editor plugins instead.
    Two JavaScript Rich Text Editor plugins for your reference:
    http://quilljs.com/
    http://nicedit.com/
    If you want to submit the value of Rich Text Editor control to a SharePoint list using REST call, since the content in the Multiple Line of Text column is wrapped
    with nested HTML tags, the similar requirement would also be applied to the content to be submitted.
    Here is a code snippet about how to update a Multiple Line of Text column for your reference:
    updateListItem(_spPageContextInfo.webAbsoluteUrl, "List018", 1);
    function updateListItem(siteUrl, listName, itemId)
    var itemType = GetItemTypeForListName(listName);
    var item = {
    "__metadata": { "type": itemType },
    "MultiTextEnhanced": "<div><a href='http://bing.com/'>Bing</a><br></p></div>",
    "Title": "123"
    $.ajax({
    url: siteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items(" + itemId + ")",
    method: "GET",
    headers: { "Accept": "application/json; odata=verbose" },
    success: function (data) {
    console.log(data);
    $.ajax({
    url: data.d.__metadata.uri,
    type: "POST",
    contentType: "application/json;odata=verbose",
    data: JSON.stringify(item),
    headers: {
    "Accept": "application/json;odata=verbose",
    "X-RequestDigest": $("#__REQUESTDIGEST").val(),
    "X-HTTP-Method": "MERGE",
    "If-Match": data.d.__metadata.etag
    success: function (data) {
    console.log(data);
    error: function (data) {
    console.log(data);
    error: function (data) {
    console.log(data);
    // Getting the item type for the list
    function GetItemTypeForListName(name)
    return"SP.Data." + name.charAt(0).toUpperCase() + name.slice(1) + "ListItem";
    Thanks
    Patrick Liang
    Forum Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support,
    contact [email protected]
    Patrick Liang
    TechNet Community Support

Maybe you are looking for